asnannp commited on
Commit
1d8cd96
·
1 Parent(s): 7e5eaf6

deploy: sync backend to Space root (learn-lesson HF cache fix)

Browse files
.env.production.example CHANGED
@@ -24,7 +24,7 @@ DATABASE_BACKUP_DIR=
24
  # LLM tuition brain for signed-in users.
25
  AUTH_ENABLED=true
26
  AUTH_PROVIDER=supabase
27
- FRONTEND_BASE_URL=
28
 
29
  # Supabase (when AUTH_PROVIDER=supabase). Dashboard → Project Settings.
30
  # SUPABASE_URL → Settings → API → Project URL
@@ -36,6 +36,8 @@ FRONTEND_BASE_URL=
36
  # prefix with postgresql:// (not postgres://).
37
  # Email-code login requires {{ .Token }} in the Supabase Auth Magic Link
38
  # template. Signup verification requires {{ .Token }} in Confirm signup.
 
 
39
  SUPABASE_URL=
40
  SUPABASE_ANON_KEY=
41
  SUPABASE_JWT_SECRET=
@@ -47,7 +49,13 @@ SUPABASE_SIGNUP_OTP_ENABLED=false
47
  JWT_SECRET_KEY=
48
  GOOGLE_CLIENT_ID=
49
  GOOGLE_CLIENT_SECRET=
50
- GOOGLE_OAUTH_REDIRECT_URI=
 
 
 
 
 
 
51
 
52
  BETA_ACCESS_ENABLED=true
53
  BETA_INVITE_CODE=
 
24
  # LLM tuition brain for signed-in users.
25
  AUTH_ENABLED=true
26
  AUTH_PROVIDER=supabase
27
+ FRONTEND_BASE_URL=https://www.docdoe.in
28
 
29
  # Supabase (when AUTH_PROVIDER=supabase). Dashboard → Project Settings.
30
  # SUPABASE_URL → Settings → API → Project URL
 
36
  # prefix with postgresql:// (not postgres://).
37
  # Email-code login requires {{ .Token }} in the Supabase Auth Magic Link
38
  # template. Signup verification requires {{ .Token }} in Confirm signup.
39
+ # Password recovery requires https://www.docdoe.in/reset-password in Supabase
40
+ # Auth -> URL Configuration -> Redirect URLs.
41
  SUPABASE_URL=
42
  SUPABASE_ANON_KEY=
43
  SUPABASE_JWT_SECRET=
 
49
  JWT_SECRET_KEY=
50
  GOOGLE_CLIENT_ID=
51
  GOOGLE_CLIENT_SECRET=
52
+ GOOGLE_OAUTH_REDIRECT_URI=https://www.docdoe.in/api/auth/google/callback
53
+
54
+ # Required only when AUTH_PROVIDER=jwt. With Supabase, its configured SMTP
55
+ # provider sends login codes and recovery links instead.
56
+ EMAIL_PROVIDER=disabled
57
+ RESEND_API_KEY=
58
+ EMAIL_FROM="DocDoe <support@docdoe.in>"
59
 
60
  BETA_ACCESS_ENABLED=true
61
  BETA_INVITE_CODE=
app/routes/auth.py CHANGED
@@ -319,6 +319,8 @@ def _supabase_public_auth_request(
319
  invalid_statuses: set[int],
320
  invalid_detail: str,
321
  invalid_response_status: int = status.HTTP_401_UNAUTHORIZED,
 
 
322
  ) -> dict:
323
  """Call a public Supabase Auth endpoint without privileged credentials.
324
 
@@ -334,15 +336,18 @@ def _supabase_public_auth_request(
334
  status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
335
  detail="Email sign-in is not configured for this deployment.",
336
  )
 
 
 
 
 
 
 
337
  request = urllib.request.Request(
338
  f"{settings.supabase_url.rstrip('/')}/auth/v1/{path.lstrip('/')}",
339
  data=json.dumps(payload).encode("utf-8"),
340
- headers={
341
- "apikey": settings.supabase_anon_key,
342
- "Content-Type": "application/json",
343
- "Accept": "application/json",
344
- },
345
- method="POST",
346
  )
347
  try:
348
  with urllib.request.urlopen(request, timeout=20) as provider_response:
@@ -393,6 +398,52 @@ def _request_supabase_login_otp(email: str) -> None:
393
  raise
394
 
395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  def _verify_supabase_login_otp(
397
  db: Session,
398
  *,
@@ -840,13 +891,18 @@ def forgot_password(
840
  payload: ForgotPasswordRequest,
841
  db: Session = Depends(get_db),
842
  ) -> ForgotPasswordResponse:
 
 
 
 
 
 
843
  if not _password_recovery_available():
844
  raise HTTPException(
845
  status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
846
  detail="Password recovery is temporarily unavailable. Try again shortly.",
847
  )
848
 
849
- normalized_email = payload.email.strip().lower()
850
  user = db.scalar(select(User).where(User.email == normalized_email))
851
  if user is None or not user.password_hash:
852
  return ForgotPasswordResponse(message=PASSWORD_RESET_MESSAGE)
@@ -907,12 +963,16 @@ def reset_password(
907
  payload: ResetPasswordRequest,
908
  db: Session = Depends(get_db),
909
  ) -> ResetPasswordResponse:
910
- if (get_settings().auth_provider or "jwt").strip().lower() != "jwt":
 
 
 
 
 
911
  raise HTTPException(
912
  status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
913
  detail="Password recovery is unavailable for this sign-in provider.",
914
  )
915
- _validate_password(payload.password)
916
  now = datetime.now(timezone.utc)
917
  token_hash = _reset_token_hash(payload.token)
918
  reset_token = db.scalar(
 
319
  invalid_statuses: set[int],
320
  invalid_detail: str,
321
  invalid_response_status: int = status.HTTP_401_UNAUTHORIZED,
322
+ method: str = "POST",
323
+ access_token: str | None = None,
324
  ) -> dict:
325
  """Call a public Supabase Auth endpoint without privileged credentials.
326
 
 
336
  status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
337
  detail="Email sign-in is not configured for this deployment.",
338
  )
339
+ headers = {
340
+ "apikey": settings.supabase_anon_key,
341
+ "Content-Type": "application/json",
342
+ "Accept": "application/json",
343
+ }
344
+ if access_token:
345
+ headers["Authorization"] = f"Bearer {access_token}"
346
  request = urllib.request.Request(
347
  f"{settings.supabase_url.rstrip('/')}/auth/v1/{path.lstrip('/')}",
348
  data=json.dumps(payload).encode("utf-8"),
349
+ headers=headers,
350
+ method=method,
 
 
 
 
351
  )
352
  try:
353
  with urllib.request.urlopen(request, timeout=20) as provider_response:
 
398
  raise
399
 
400
 
401
+ def _request_supabase_password_recovery(email: str) -> None:
402
+ settings = get_settings()
403
+ frontend_base_url = settings.frontend_base_url.rstrip("/")
404
+ if not frontend_base_url.startswith("https://"):
405
+ logger.error(
406
+ "[FIX:supabase-password-recovery] Invalid production redirect configuration"
407
+ )
408
+ raise HTTPException(
409
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
410
+ detail="Password recovery is not configured for this deployment.",
411
+ )
412
+ redirect_to = f"{frontend_base_url}/reset-password"
413
+ path = f"recover?{urllib.parse.urlencode({'redirect_to': redirect_to})}"
414
+ logger.info(
415
+ "[FIX:supabase-password-recovery] Requesting provider recovery email",
416
+ extra={"redirect_to": redirect_to},
417
+ )
418
+ try:
419
+ _supabase_public_auth_request(
420
+ path,
421
+ {"email": email},
422
+ invalid_statuses={400, 401, 404},
423
+ invalid_detail="Password recovery is temporarily unavailable.",
424
+ invalid_response_status=status.HTTP_502_BAD_GATEWAY,
425
+ )
426
+ except HTTPException as exc:
427
+ logger.warning(
428
+ "[FIX:supabase-password-recovery] Provider request failed",
429
+ extra={"status_code": exc.status_code},
430
+ )
431
+ raise
432
+ logger.info("[FIX:supabase-password-recovery] Provider accepted recovery request")
433
+
434
+
435
+ def _update_supabase_password(access_token: str, password: str) -> None:
436
+ _supabase_public_auth_request(
437
+ "user",
438
+ {"password": password},
439
+ invalid_statuses={400, 401, 403, 422},
440
+ invalid_detail="This recovery link is invalid or expired. Request a new one.",
441
+ invalid_response_status=status.HTTP_400_BAD_REQUEST,
442
+ method="PUT",
443
+ access_token=access_token,
444
+ )
445
+
446
+
447
  def _verify_supabase_login_otp(
448
  db: Session,
449
  *,
 
891
  payload: ForgotPasswordRequest,
892
  db: Session = Depends(get_db),
893
  ) -> ForgotPasswordResponse:
894
+ settings = get_settings()
895
+ provider = (settings.auth_provider or "jwt").strip().lower()
896
+ normalized_email = payload.email.strip().lower()
897
+ if provider == "supabase":
898
+ _request_supabase_password_recovery(normalized_email)
899
+ return ForgotPasswordResponse(message=PASSWORD_RESET_MESSAGE)
900
  if not _password_recovery_available():
901
  raise HTTPException(
902
  status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
903
  detail="Password recovery is temporarily unavailable. Try again shortly.",
904
  )
905
 
 
906
  user = db.scalar(select(User).where(User.email == normalized_email))
907
  if user is None or not user.password_hash:
908
  return ForgotPasswordResponse(message=PASSWORD_RESET_MESSAGE)
 
963
  payload: ResetPasswordRequest,
964
  db: Session = Depends(get_db),
965
  ) -> ResetPasswordResponse:
966
+ provider = (get_settings().auth_provider or "jwt").strip().lower()
967
+ _validate_password(payload.password)
968
+ if provider == "supabase":
969
+ _update_supabase_password(payload.token, payload.password)
970
+ return ResetPasswordResponse(reset=True)
971
+ if provider != "jwt":
972
  raise HTTPException(
973
  status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
974
  detail="Password recovery is unavailable for this sign-in provider.",
975
  )
 
976
  now = datetime.now(timezone.utc)
977
  token_hash = _reset_token_hash(payload.token)
978
  reset_token = db.scalar(
app/schemas/user.py CHANGED
@@ -92,7 +92,7 @@ class ForgotPasswordResponse(BaseModel):
92
 
93
 
94
  class ResetPasswordRequest(BaseModel):
95
- token: str = Field(min_length=32, max_length=256)
96
  password: str = Field(min_length=8, max_length=128)
97
 
98
 
 
92
 
93
 
94
  class ResetPasswordRequest(BaseModel):
95
+ token: str = Field(min_length=32, max_length=4096)
96
  password: str = Field(min_length=8, max_length=128)
97
 
98
 
scripts/production_preflight.py CHANGED
@@ -107,11 +107,13 @@ def check_environment(is_prod: bool) -> Iterable[Check]:
107
  if frontend.startswith(LOCAL_HOST_PREFIXES):
108
  yield _fail(sec, "FRONTEND_BASE_URL", "points at localhost in production")
109
  elif not frontend.startswith("https://"):
110
- yield _warn(sec, "FRONTEND_BASE_URL", "should use https in production")
111
  else:
112
  yield _pass(sec, "FRONTEND_BASE_URL", frontend)
113
  elif frontend:
114
  yield _pass(sec, "FRONTEND_BASE_URL", frontend)
 
 
115
  else:
116
  yield _warn(sec, "FRONTEND_BASE_URL", "not set")
117
 
@@ -178,6 +180,41 @@ def check_environment(is_prod: bool) -> Iterable[Check]:
178
  )
179
  else:
180
  yield _pass(sec, "SUPABASE_SERVICE_ROLE_KEY", mask_secret(service_key))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
  rate_limit = env_bool("RATE_LIMIT_ENABLED")
183
  if is_prod and not rate_limit:
 
107
  if frontend.startswith(LOCAL_HOST_PREFIXES):
108
  yield _fail(sec, "FRONTEND_BASE_URL", "points at localhost in production")
109
  elif not frontend.startswith("https://"):
110
+ yield _fail(sec, "FRONTEND_BASE_URL", "must use https in production")
111
  else:
112
  yield _pass(sec, "FRONTEND_BASE_URL", frontend)
113
  elif frontend:
114
  yield _pass(sec, "FRONTEND_BASE_URL", frontend)
115
+ elif is_prod:
116
+ yield _fail(sec, "FRONTEND_BASE_URL", "missing in production")
117
  else:
118
  yield _warn(sec, "FRONTEND_BASE_URL", "not set")
119
 
 
180
  )
181
  else:
182
  yield _pass(sec, "SUPABASE_SERVICE_ROLE_KEY", mask_secret(service_key))
183
+ else:
184
+ email_provider = (env("EMAIL_PROVIDER") or "disabled").lower()
185
+ resend_key = env("RESEND_API_KEY")
186
+ if email_provider != "resend" or not resend_key:
187
+ yield _fail(
188
+ sec,
189
+ "Password recovery email",
190
+ "JWT auth requires EMAIL_PROVIDER=resend and RESEND_API_KEY",
191
+ )
192
+ else:
193
+ yield _pass(sec, "Password recovery email", "Resend configured")
194
+
195
+ google_fields = {
196
+ "GOOGLE_CLIENT_ID": env("GOOGLE_CLIENT_ID"),
197
+ "GOOGLE_CLIENT_SECRET": env("GOOGLE_CLIENT_SECRET"),
198
+ "GOOGLE_OAUTH_REDIRECT_URI": env("GOOGLE_OAUTH_REDIRECT_URI"),
199
+ }
200
+ if any(google_fields.values()):
201
+ missing_google = [name for name, value in google_fields.items() if not value]
202
+ if missing_google:
203
+ yield _fail(
204
+ sec,
205
+ "Google OAuth configuration",
206
+ f"partial configuration; missing {', '.join(missing_google)}",
207
+ )
208
+ elif google_fields["GOOGLE_OAUTH_REDIRECT_URI"] != (
209
+ "https://www.docdoe.in/api/auth/google/callback"
210
+ ):
211
+ yield _fail(
212
+ sec,
213
+ "Google OAuth redirect",
214
+ "must use the DocDoe callback, not the backend host",
215
+ )
216
+ else:
217
+ yield _pass(sec, "Google OAuth redirect", "DocDoe callback configured")
218
 
219
  rate_limit = env_bool("RATE_LIMIT_ENABLED")
220
  if is_prod and not rate_limit:
tests/test_production_preflight.py CHANGED
@@ -29,6 +29,8 @@ PROD_BASE_ENV = {
29
  "CORS_ORIGINS": "https://docdoe.ai,https://www.docdoe.ai",
30
  "JWT_SECRET_KEY": "x" * 48,
31
  "AUTH_ENABLED": "true",
 
 
32
  "RATE_LIMIT_ENABLED": "true",
33
  "STORAGE_PROVIDER": "local",
34
  "AI_PROVIDER": "sarvam",
@@ -60,6 +62,9 @@ def _set_env(monkeypatch: pytest.MonkeyPatch, env: dict[str, str]) -> None:
60
  "SUPABASE_ANON_KEY",
61
  "SUPABASE_JWT_SECRET",
62
  "SUPABASE_SERVICE_ROLE_KEY",
 
 
 
63
  "RATE_LIMIT_ENABLED",
64
  "STORAGE_PROVIDER",
65
  "STORAGE_BUCKET",
@@ -81,6 +86,8 @@ def _set_env(monkeypatch: pytest.MonkeyPatch, env: dict[str, str]) -> None:
81
  "OPENROUTER_API_KEY",
82
  "GEMINI_API_KEY",
83
  "GOOGLE_OAUTH_REDIRECT_URI",
 
 
84
  "DEPLOY_TARGET",
85
  "PORT",
86
  "STRIPE_SECRET_KEY",
@@ -178,6 +185,14 @@ def test_production_with_localhost_frontend_fails(monkeypatch):
178
  assert "FAIL" in _statuses_for(checks, "FRONTEND_BASE_URL")
179
 
180
 
 
 
 
 
 
 
 
 
181
  def test_production_with_auth_disabled_fails(monkeypatch):
182
  env = {**PROD_BASE_ENV, "AUTH_ENABLED": "false"}
183
  _set_env(monkeypatch, env)
@@ -186,6 +201,31 @@ def test_production_with_auth_disabled_fails(monkeypatch):
186
  assert "FAIL" in _statuses_for(checks, "AUTH_ENABLED")
187
 
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  def test_supabase_auth_requires_account_deletion_admin_key(monkeypatch):
190
  env = {
191
  **PROD_BASE_ENV,
 
29
  "CORS_ORIGINS": "https://docdoe.ai,https://www.docdoe.ai",
30
  "JWT_SECRET_KEY": "x" * 48,
31
  "AUTH_ENABLED": "true",
32
+ "EMAIL_PROVIDER": "resend",
33
+ "RESEND_API_KEY": "re_test_" + "e" * 30,
34
  "RATE_LIMIT_ENABLED": "true",
35
  "STORAGE_PROVIDER": "local",
36
  "AI_PROVIDER": "sarvam",
 
62
  "SUPABASE_ANON_KEY",
63
  "SUPABASE_JWT_SECRET",
64
  "SUPABASE_SERVICE_ROLE_KEY",
65
+ "EMAIL_PROVIDER",
66
+ "RESEND_API_KEY",
67
+ "EMAIL_FROM",
68
  "RATE_LIMIT_ENABLED",
69
  "STORAGE_PROVIDER",
70
  "STORAGE_BUCKET",
 
86
  "OPENROUTER_API_KEY",
87
  "GEMINI_API_KEY",
88
  "GOOGLE_OAUTH_REDIRECT_URI",
89
+ "GOOGLE_CLIENT_ID",
90
+ "GOOGLE_CLIENT_SECRET",
91
  "DEPLOY_TARGET",
92
  "PORT",
93
  "STRIPE_SECRET_KEY",
 
185
  assert "FAIL" in _statuses_for(checks, "FRONTEND_BASE_URL")
186
 
187
 
188
+ def test_production_without_frontend_base_url_fails(monkeypatch):
189
+ env = {**PROD_BASE_ENV, "FRONTEND_BASE_URL": ""}
190
+ _set_env(monkeypatch, env)
191
+ _stub_binaries(monkeypatch)
192
+ checks = preflight.collect_all_checks()
193
+ assert "FAIL" in _statuses_for(checks, "FRONTEND_BASE_URL")
194
+
195
+
196
  def test_production_with_auth_disabled_fails(monkeypatch):
197
  env = {**PROD_BASE_ENV, "AUTH_ENABLED": "false"}
198
  _set_env(monkeypatch, env)
 
201
  assert "FAIL" in _statuses_for(checks, "AUTH_ENABLED")
202
 
203
 
204
+ def test_jwt_auth_requires_transactional_email(monkeypatch):
205
+ env = {**PROD_BASE_ENV, "EMAIL_PROVIDER": "disabled", "RESEND_API_KEY": ""}
206
+ _set_env(monkeypatch, env)
207
+ _stub_binaries(monkeypatch)
208
+
209
+ checks = preflight.collect_all_checks()
210
+
211
+ assert "FAIL" in _statuses_for(checks, "Password recovery email")
212
+
213
+
214
+ def test_google_oauth_must_return_through_docdoe_domain(monkeypatch):
215
+ env = {
216
+ **PROD_BASE_ENV,
217
+ "GOOGLE_CLIENT_ID": "google-client",
218
+ "GOOGLE_CLIENT_SECRET": "google-secret",
219
+ "GOOGLE_OAUTH_REDIRECT_URI": "https://asnannp-docdoeai.hf.space/auth/google/callback",
220
+ }
221
+ _set_env(monkeypatch, env)
222
+ _stub_binaries(monkeypatch)
223
+
224
+ checks = preflight.collect_all_checks()
225
+
226
+ assert "FAIL" in _statuses_for(checks, "Google OAuth redirect")
227
+
228
+
229
  def test_supabase_auth_requires_account_deletion_admin_key(monkeypatch):
230
  env = {
231
  **PROD_BASE_ENV,
tests/test_supabase_otp_login.py CHANGED
@@ -82,6 +82,113 @@ def test_supabase_otp_request_is_enumeration_safe_for_unknown_email(monkeypatch)
82
  auth._request_supabase_login_otp("unknown@example.com")
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def test_supabase_signup_sends_confirmation_email_without_returning_session(monkeypatch) -> None:
86
  _configure_supabase(monkeypatch)
87
  captured: dict[str, object] = {}
 
82
  auth._request_supabase_login_otp("unknown@example.com")
83
 
84
 
85
+ def test_supabase_password_recovery_uses_docdoe_redirect(monkeypatch) -> None:
86
+ _configure_supabase(monkeypatch)
87
+ settings = get_settings()
88
+ monkeypatch.setattr(settings, "frontend_base_url", "https://www.docdoe.in")
89
+ captured: dict[str, object] = {}
90
+
91
+ def fake_urlopen(request: urllib.request.Request, timeout: int):
92
+ captured["request"] = request
93
+ return _ProviderResponse()
94
+
95
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
96
+ auth._request_supabase_password_recovery("student@example.com")
97
+
98
+ request = captured["request"]
99
+ assert isinstance(request, urllib.request.Request)
100
+ assert request.full_url == (
101
+ "https://staging-project.supabase.co/auth/v1/recover?"
102
+ "redirect_to=https%3A%2F%2Fwww.docdoe.in%2Freset-password"
103
+ )
104
+ assert json.loads(request.data or b"{}") == {"email": "student@example.com"}
105
+
106
+
107
+ def test_supabase_password_recovery_requires_https_frontend(monkeypatch) -> None:
108
+ _configure_supabase(monkeypatch)
109
+ settings = get_settings()
110
+ monkeypatch.setattr(settings, "frontend_base_url", "")
111
+
112
+ with pytest.raises(HTTPException) as caught:
113
+ auth._request_supabase_password_recovery("student@example.com")
114
+
115
+ assert caught.value.status_code == 503
116
+ assert caught.value.detail == "Password recovery is not configured for this deployment."
117
+
118
+
119
+ def test_supabase_password_recovery_surfaces_provider_configuration_errors(monkeypatch) -> None:
120
+ _configure_supabase(monkeypatch)
121
+ settings = get_settings()
122
+ monkeypatch.setattr(settings, "frontend_base_url", "https://www.docdoe.in")
123
+
124
+ def provider_rejected(_request: urllib.request.Request, timeout: int):
125
+ raise urllib.error.HTTPError(
126
+ url="https://staging-project.supabase.co/auth/v1/recover",
127
+ code=400,
128
+ msg="Bad Request",
129
+ hdrs=None,
130
+ fp=io.BytesIO(b'{"message":"redirect URL not allowed"}'),
131
+ )
132
+
133
+ monkeypatch.setattr(urllib.request, "urlopen", provider_rejected)
134
+
135
+ with pytest.raises(HTTPException) as caught:
136
+ auth._request_supabase_password_recovery("student@example.com")
137
+
138
+ assert caught.value.status_code == 502
139
+ assert caught.value.detail == "Password recovery is temporarily unavailable."
140
+
141
+
142
+ def test_supabase_password_update_uses_recovery_bearer_token(monkeypatch) -> None:
143
+ _configure_supabase(monkeypatch)
144
+ captured: dict[str, object] = {}
145
+
146
+ def fake_urlopen(request: urllib.request.Request, timeout: int):
147
+ captured["request"] = request
148
+ return _ProviderResponse({"id": "supabase-user"})
149
+
150
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
151
+ auth._update_supabase_password("recovery-access-token", "NewStudy2026")
152
+
153
+ request = captured["request"]
154
+ assert isinstance(request, urllib.request.Request)
155
+ assert request.full_url == "https://staging-project.supabase.co/auth/v1/user"
156
+ assert request.method == "PUT"
157
+ assert request.get_header("Authorization") == "Bearer recovery-access-token"
158
+ assert json.loads(request.data or b"{}") == {"password": "NewStudy2026"}
159
+
160
+
161
+ def test_supabase_password_recovery_routes_dispatch_to_provider(auth_client, monkeypatch) -> None:
162
+ _configure_supabase(monkeypatch)
163
+ requested: list[str] = []
164
+ updated: list[tuple[str, str]] = []
165
+ monkeypatch.setattr(
166
+ auth,
167
+ "_request_supabase_password_recovery",
168
+ lambda email: requested.append(email),
169
+ )
170
+ monkeypatch.setattr(
171
+ auth,
172
+ "_update_supabase_password",
173
+ lambda token, password: updated.append((token, password)),
174
+ )
175
+
176
+ requested_response = auth_client.post(
177
+ "/auth/forgot-password",
178
+ json={"email": "Student@Example.com"},
179
+ )
180
+ reset_response = auth_client.post(
181
+ "/auth/reset-password",
182
+ json={"token": "recovery-access-token-that-is-long-enough", "password": "NewStudy2026"},
183
+ )
184
+
185
+ assert requested_response.status_code == 202
186
+ assert requested == ["student@example.com"]
187
+ assert reset_response.status_code == 200
188
+ assert reset_response.json() == {"reset": True}
189
+ assert updated == [("recovery-access-token-that-is-long-enough", "NewStudy2026")]
190
+
191
+
192
  def test_supabase_signup_sends_confirmation_email_without_returning_session(monkeypatch) -> None:
193
  _configure_supabase(monkeypatch)
194
  captured: dict[str, object] = {}