Skip to content

feat(go-api): port forgot-password flow to Go (#15282) - #15290

Merged
xugangqiang merged 6 commits into
infiniflow:mainfrom
Rene0422:feat/go-api-forgot-password-flow
Jun 10, 2026
Merged

xugangqiang merged 6 commits into
infiniflow:mainfrom
Rene0422:feat/go-api-forgot-password-flow

Conversation

@Rene0422

@Rene0422 Rene0422 commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements chunk 1 of #15282 — the four /api/v1/auth/password/... endpoints from the login-page Go port. Chunk 2 (OAuth/OIDC) is deferred to its own subtask, matching the issue author's own confidence-low recommendation ("multi-provider, stateful redirect flow with external dependencies; recommend its own subtask").

New endpoints, all registered under apiNoAuth (forgot-password users are unauthenticated by definition):

Method Path Status
POST /api/v1/auth/password/forgot/captcha new
POST /api/v1/auth/password/forgot/otp new
POST /api/v1/auth/password/forgot/otp/verify new
POST /api/v1/auth/password/reset new

Wire compatibility with the Python backend

The two backends share state through Redis, so the Go port had to use identical keys, encodings, and constants. Either backend can now validate a code the other minted.

  • Redis keys: captcha:<email>, otp:<email>, otp_attempts:<email>, otp_last_sent:<email>, otp_lock:<email>, otp:verified:<email> — same as api/utils/web_utils.py.
  • Stored OTP value: "<hex_hash>:<hex_salt>" — same as Python.
  • Hash: HMAC-SHA256 with a crypto/rand 16-byte salt — same as hash_code().
  • Constants: OTP_LENGTH=4, OTP_TTL=5min, ATTEMPT_LIMIT=5, ATTEMPT_LOCK_SECONDS=30min, RESEND_COOLDOWN_SECONDS=60s — all match api/utils/web_utils.py.
  • Email body: matches RESET_CODE_EMAIL_TMPL byte-for-byte.

Files

New

File Purpose
internal/utility/otp.go OTP/captcha constants, Redis key builders (CaptchaRedisKey, OTPRedisKeys, OTPVerifiedRedisKey), HashOTPCode, GenerateOTPCode / GenerateCaptchaCode / GenerateOTPSalt via crypto/rand, and EncodeOTPStorageValue / DecodeOTPStorageValue matching Python's storage shape.
internal/utility/smtp.go Minimal stdlib net/smtp sender. SendResetCodeEmail(to, otp, ttlMin) builds an RFC 5322 plain-text message and dispatches via implicit TLS / STARTTLS / plain — same selectors as Python aiosmtplib. Returns SMTPNotConfiguredError if the config block is empty.

Modified

File Change
internal/server/config.go New SMTPConfig struct + Config.SMTP field. Field names mirror the smtp: keys in common/settings.py (mail_server, mail_port, mail_use_ssl, mail_use_tls, mail_username, mail_password, mail_from_name, mail_from_address, mail_frontend_url) so a single conf/service_conf.yaml powers both backends.
internal/service/user.go Four methods — ForgotIssueCaptcha, ForgotSendOTP, ForgotVerifyOTP, ForgotResetPassword. Reuses the existing decryptPassword, HashPassword, userDAO.Update, and utility.GenerateToken so the reset+auto-login path is identical to LoginByEmail.
internal/handler/user.go Four handlers in the same c.JSON shape as LoginByEmail. The reset handler rotates the access token and emits an Authorization header for auto-login (matches Python construct_response(auth=user.get_id())).
internal/router/router.go Routes registered under apiNoAuth, with an explanatory comment on why they sit outside the auth middleware.

Known divergence — captcha rendering

The Python endpoint returns a rendered image/JPEG from the python-captcha library. The Go side has no image-captcha dependency vendored in go.mod, and hand-rolling a raster generator was out of scope for this PR.

This commit returns JSON {captcha: "<text>"} instead. Implications:

  • Backend gate is identical — the OTP step still verifies the user-submitted captcha string against the Redis value, so the security model is unchanged.
  • Frontend impact: the password-reset page rendering needs a small tweak (text display instead of <img>) until a Go captcha library is wired in.
  • The handler comments call this out explicitly so the next PR knows what to swap.

Possible follow-ups (any one closes the gap):

  1. Add github.com/mojocn/base64Captcha or github.com/dchest/captcha to go.mod and replace the JSON response with an image/JPEG.
  2. Hand-roll a 5x7 bitmap font + image/png writer using only the stdlib.
  3. Render a server-side SVG (cheap, but trivially OCR-able — only useful as a UI shim).

Test plan

  • Captcha: POST /api/v1/auth/password/forgot/captcha?email=<existing> returns {code: 0, data: {captcha: "ABCD"}}. Redis shows captcha:<email> with that value and ~60s TTL. Unknown email returns code: CodeDataError.
  • OTP send: POST /api/v1/auth/password/forgot/otp with the right captcha mints an OTP, stores <hash>:<salt> under otp:<email> for 5 min, sends an email, returns success. With a wrong captcha returns CodeAuthenticationError. Hitting it again within 60s returns "you still have to wait …" with CodeNotEffective.
  • OTP verify: correct OTP → code: 0, OTP keys cleared, otp:verified:<email> = "1". Wrong OTP → code: CodeAuthenticationError, attempt counter bumped; after 5 wrong tries otp_lock:<email> is set and further attempts hit CodeNotEffective.
  • Reset: with the verified flag set, supply a new password (RSA-encrypted+base64, same as LoginByEmail). Returns code: 0, Authorization header set, verified flag deleted. Without the verified flag returns CodeAuthenticationError.
  • Wire-compat smoke: mint an OTP from the Python backend, verify it via the Go endpoint, and vice versa. Should both succeed.
  • SMTP misconfigured: drop smtp.mail_server from conf/service_conf.yaml. The OTP-send endpoint should now return "failed to send email" without panicking; check the log for the SMTPNotConfiguredError warning.
  • End-to-end FE: hit the password-reset flow from web/src/pages/login-next/. Confirm the text-captcha shim works after the FE tweak.
  • go build ./... and go vet ./... — I could not run these in the sandbox; please confirm a clean build before merging.
  • uv run pytest to confirm no Python regressions (shared Redis schema).

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds a Go-based forgot-password flow (SMTP config, OTP/captcha utilities, Redis-backed service logic, HTTP handlers, and routes) and hardens the Python connector rebuild endpoint with knowledge-base access and connector-to-kb binding checks.

Changes

Forgot-Password Recovery Flow

Layer / File(s) Summary
Configuration and utility foundations
internal/common/smtp_config.go, internal/server/config.go, internal/utility/otp.go, internal/utility/smtp.go
Adds SMTPConfig and server config field; OTP/captcha constants and Redis key helpers; secure OTP salt/hash and code generation; SMTP transactional sender with TLS/STARTTLS and delivery logic.
User service forgot-password flow
internal/service/user.go
Adds ForgotIssueCaptcha, ForgotSendOTP, ForgotVerifyOTP, ForgotResetPasswordRequest, and ForgotResetPassword implementing Redis state, cooldown/lockout, OTP hashing/storage, email send with rollback on failure, verification gating, RSA-decrypt password handling, password update, and token rotation.
HTTP endpoints and route registration
internal/handler/user.go, internal/router/router.go
Adds four unauthenticated handlers (captcha, send OTP, verify OTP, reset password) and registers /api/v1/auth/password/forgot/* POST routes; handlers bind inputs, call service methods, and on reset set Authorization header with new token.

Connector API Authorization

Layer / File(s) Summary
Connector rebuild authorization checks
api/apps/restful_apis/connector_api.py
Rebuild endpoint now imports Connector2KbService and KnowledgebaseService, reads kb_id from the request, verifies KnowledgebaseService.accessible(kb_id, user_id) and Connector2KbService.query(connector_id,kb_id) before invoking ConnectorService.rebuild.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant UserHandler
  participant UserService
  participant Redis
  participant SMTP
  participant UserStore
  Client->>UserHandler: POST /auth/password/forgot/* (captcha/send/verify/reset)
  UserHandler->>UserService: ForgotIssueCaptcha / ForgotSendOTP / ForgotVerifyOTP / ForgotResetPassword
  UserService->>Redis: store/read captcha, otp state, verified marker
  UserService->>SMTP: SendResetCodeEmail(cfg, toEmail, otp, ttl)
  UserService->>UserStore: update hashed password and rotate token
  UserService->>Redis: delete/clear OTP state and verified marker
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14228: Both PRs modify the connector rebuild endpoint in api/apps/restful_apis/connector_api.py.
  • infiniflow/ragflow#15300: Related connector rebuild workflow and service/DAO changes that interact with the rebuild handler.

Suggested labels

💞 feature, ci

Suggested reviewers

  • Haruko386

Poem

I’m a rabbit with a patchwork key,
Hopping through Redis, SMTP, and glee,
Captchas bloom and OTPs take flight,
A reset then a token bright,
🐰🔐 Your account’s secure tonight.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly and concisely summarizes the main change: porting the forgot-password flow from Python to Go, including the associated issue reference #15282.
Docstring Coverage ✅ Passed Docstring coverage is 82.35% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description comprehensively addresses all required sections with detailed context, clear scope definition, and actionable test plan.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (1)
api/apps/restful_apis/connector_api.py (1)

171-171: ⚡ Quick win

Use an explicit existence check for the connector↔KB lookup.

Connector2KbService.query(...) only needs to answer whether a binding exists on this path. Peewee already exposes exists() for that, while its base query type implements __len__() by ensuring execution first, so the current truthiness-style check is less explicit and can do more work than necessary in an authorization gate. (raw.githubusercontent.com)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/connector_api.py` at line 171, The current
authorization check uses truthiness on
Connector2KbService.query(connector_id=connector_id, kb_id=kb_id) which may
execute the full query; change it to an explicit existence check by calling the
Peewee exists() path (e.g., use Connector2KbService.query(...).exists() or an
equivalent service method that returns a boolean) so the gate only checks for
presence without fetching rows; update the conditional in the connector_api
method that performs the lookup to use this exists-based check and ensure any
service helpers or callers still expect a boolean.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/handler/user.go`:
- Around line 628-631: The response currently returns the plaintext captcha
("data": gin.H{"captcha": code}) which defeats the challenge; instead stop
returning the code in the handler in internal/handler/user.go and return a
captcha identifier or image only (e.g., "captcha_id" and/or base64 image) while
keeping the actual code stored server-side for validation by ForgotSendOTP;
update the issue point (the handler that issues captchas and the ForgotSendOTP
verifier) to persist the code keyed by the captcha_id and modify the response to
expose only the id or image so clients cannot read the expected value.

In `@internal/service/user.go`:
- Around line 1089-1119: ForgotSendOTP currently obtains lockKey from
utility.OTPRedisKeys(email) and unconditionally rc.Delete(lockKey) after storing
a new OTP, which lets a locked caller clear the verification lock by requesting
another code; update ForgotSendOTP to preserve the verification lock behavior
used by ForgotVerifyOTP by first checking rc.Get(lockKey) and refusing to send
(returning an appropriate error code/message) when the lock exists, and remove
the rc.Delete(lockKey) call so the lock is not cleared when issuing a new OTP;
reference the lockKey variable, utility.OTPRedisKeys(email), and the functions
ForgotSendOTP/ForgotVerifyOTP to locate and apply the fix.
- Around line 1114-1123: Before calling utility.SendResetCodeEmail in the reset
flow, capture the previous Redis state (values for codeKey, attemptsKey,
lastSentKey, lockKey) or note their absence; then after setting the new OTP with
rc.Set(codeKey,...), rc.Set(attemptsKey,...), rc.Set(lastSentKey,...) and
rc.Delete(lockKey), wrap utility.SendResetCodeEmail(email, otp, ttlMin) so that
on error you roll back Redis to the previous state (delete the newly written
codeKey/attemptsKey/lastSentKey and re-create the previous values or lockKey as
applicable) and return the error; update the block surrounding
SendResetCodeEmail and the rc.Set/rc.Delete calls (referencing codeKey,
attemptsKey, lastSentKey, lockKey, utility.EncodeOTPStorageValue and
utility.SendResetCodeEmail) to perform this transactional rollback so users are
not throttled or left with a stale OTP when email delivery fails.

In `@internal/utility/smtp.go`:
- Around line 145-155: The code currently calls client.Auth(auth) whenever
cfg.MailUsername is set, even if the connection is plaintext; modify the logic
around cfg.MailUsername and client.Auth(auth) to first require an encrypted
transport by checking cfg.MailUseSSL || cfg.MailUseTLS and return a clear error
if authentication is attempted on an unencrypted connection (i.e., when both
cfg.MailUseSSL and cfg.MailUseTLS are false); ensure you keep the existing
StartTLS branch (cfg.MailUseTLS) and only call client.Auth(auth) after
confirming an encrypted session, referencing cfg.MailUseTLS, cfg.MailUseSSL,
cfg.MailUsername and client.Auth(auth) to locate the change.
- Around line 33-35: Remove the import cycle by stopping smtp.go from calling
server.GetConfig()—change sendMail (and any callers) to accept the SMTP config
as a parameter (e.g., cfg *common.SMTPConfig) instead of importing server or
calling server.GetConfig(), or alternatively move the SMTPConfig type into
internal/common and reference that; then fix plaintext auth: only perform
client.Auth(auth) when the connection is encrypted—if cfg.MailUseSSL create a
TLS-wrapped connection and authenticate, if cfg.MailUseTLS call
client.StartTLS(...) and then call client.Auth(auth); if neither MailUseSSL nor
MailUseTLS and MailUsername is set, refuse to send/auth over plaintext (return
an error) instead of calling client.Auth on an unencrypted connection; update
references to sendMail and the auth logic to use MailUseSSL, MailUseTLS,
MailUsername, and client.StartTLS/client.Auth accordingly.

---

Nitpick comments:
In `@api/apps/restful_apis/connector_api.py`:
- Line 171: The current authorization check uses truthiness on
Connector2KbService.query(connector_id=connector_id, kb_id=kb_id) which may
execute the full query; change it to an explicit existence check by calling the
Peewee exists() path (e.g., use Connector2KbService.query(...).exists() or an
equivalent service method that returns a boolean) so the gate only checks for
presence without fetching rows; update the conditional in the connector_api
method that performs the lookup to use this exists-based check and ensure any
service helpers or callers still expect a boolean.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d8c90dd0-4e9e-41a1-b4df-f58207ece75d

📥 Commits

Reviewing files that changed from the base of the PR and between 2c099bb and 3d5d617.

📒 Files selected for processing (7)
  • api/apps/restful_apis/connector_api.py
  • internal/handler/user.go
  • internal/router/router.go
  • internal/server/config.go
  • internal/service/user.go
  • internal/utility/otp.go
  • internal/utility/smtp.go

Comment thread internal/handler/user.go Resolved
Comment thread internal/service/user.go Resolved
Comment thread internal/service/user.go Resolved
Comment thread internal/service/user.go Resolved
Comment thread internal/utility/smtp.go Resolved
Comment thread internal/utility/smtp.go Resolved
@Rene0422
Rene0422 force-pushed the feat/go-api-forgot-password-flow branch from 4a7d97c to 324626d Compare May 27, 2026 09:27

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/utility/smtp.go (1)

135-154: 💤 Low value

Consider explicitly setting TLS MinVersion for defense in depth.

Go defaults to TLS 1.2 for clients (acceptable), but explicitly setting MinVersion: tls.VersionTLS12 documents intent and guards against future runtime changes. TLS 1.3 is too restrictive for many SMTP servers.

♻️ Optional hardening
 	if cfg.MailUseSSL {
 		// Implicit TLS (typical port 465). Dial TLS first, then SMTP.
-		tlsCfg := &tls.Config{ServerName: cfg.MailServer}
+		tlsCfg := &tls.Config{ServerName: cfg.MailServer, MinVersion: tls.VersionTLS12}
 		conn, err := tls.Dial("tcp", addr, tlsCfg)
 	if cfg.MailUseTLS {
-		tlsCfg := &tls.Config{ServerName: cfg.MailServer}
+		tlsCfg := &tls.Config{ServerName: cfg.MailServer, MinVersion: tls.VersionTLS12}
 		if err := client.StartTLS(tlsCfg); err != nil {

Also applies to: 162-172

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/utility/smtp.go` around lines 135 - 154, The TLS dial block for
implicit SSL (when cfg.MailUseSSL) should explicitly set a minimum TLS version
to TLS1.2 for defense-in-depth: update the tls.Config (tlsCfg) passed to
tls.Dial to include MinVersion: tls.VersionTLS12 (while keeping ServerName:
cfg.MailServer), then continue using smtp.NewClient, client.Auth and deliverMail
as before; apply the same change to the other tls.Config usage at the second
occurrence referenced in the diff.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/utility/smtp.go`:
- Around line 135-154: The TLS dial block for implicit SSL (when cfg.MailUseSSL)
should explicitly set a minimum TLS version to TLS1.2 for defense-in-depth:
update the tls.Config (tlsCfg) passed to tls.Dial to include MinVersion:
tls.VersionTLS12 (while keeping ServerName: cfg.MailServer), then continue using
smtp.NewClient, client.Auth and deliverMail as before; apply the same change to
the other tls.Config usage at the second occurrence referenced in the diff.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c0916d23-2b38-4aa7-b90e-5ad55d1b6341

📥 Commits

Reviewing files that changed from the base of the PR and between 3d5d617 and 324626d.

📒 Files selected for processing (8)
  • api/apps/restful_apis/connector_api.py
  • internal/common/smtp_config.go
  • internal/handler/user.go
  • internal/router/router.go
  • internal/server/config.go
  • internal/service/user.go
  • internal/utility/otp.go
  • internal/utility/smtp.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • api/apps/restful_apis/connector_api.py
  • internal/router/router.go
  • internal/handler/user.go
  • internal/service/user.go

@Haruko386
Haruko386 requested a review from Harry-Hz-Zhang May 28, 2026 08:00
@Rene0422
Rene0422 force-pushed the feat/go-api-forgot-password-flow branch from 4c481a7 to dca5d31 Compare May 28, 2026 09:18
@Rene0422

Copy link
Copy Markdown
Contributor Author

@Hz-186 , please review this PR and let me know the result. Thanks.

Comment thread api/apps/restful_apis/connector_api.py Outdated
code=RetCode.AUTHENTICATION_ERROR,
)

err = ConnectorService.rebuild(kb_id, connector_id, current_user.id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, @Rene0422
do not change python code

Comment thread internal/handler/user.go
c.Header("Authorization", authToken)
c.Header("Access-Control-Expose-Headers", "Authorization")

profile := h.userService.GetUserProfile(user)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reset success response should not return GetUserProfile as-is. That helper includes sensitive fields such as password and access_token, while the Python implementation returns user.to_safe_dict(for_self=True), which filters those fields. Please return a safe DTO here or remove sensitive fields before writing the response.

Comment thread internal/handler/user.go Outdated
c.JSON(http.StatusOK, gin.H{
"code": common.CodeSuccess,
"message": "captcha issued",
"data": gin.H{"captcha_id": captchaID},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, @Rene0422

The captcha step is not usable as implemented. ForgotCaptcha only returns a captcha_id, but it does not return an image or any client-solvable challenge, while ForgotSendOTP still requires the user to submit the captcha text. The Python endpoint returns a captcha image that the user can solve. Please return a captcha image tied to the server-side key, or otherwise provide a client-solvable challenge before requiring captcha in the OTP request.

Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request May 29, 2026
…#15282)

Pivot from the password-reset port — that scope ships in infiniflow#15290 — to the
other half of infiniflow#15282: the OAuth login endpoints the SPA's login page calls
when a user picks a non-email channel.

  GET /api/v1/auth/login/{channel}             start the OAuth redirect
  GET /api/v1/auth/oauth/{channel}/callback    receive the callback

internal/utility/oauth/ ports api/apps/auth/ to Go:
  - oauth2 client: vanilla authorization-code flow
  - oidc client: discovers endpoints from {issuer}/.well-known/openid-configuration
  - github client: well-known endpoints + /user/emails primary lookup
  NewClient picks the flavor from cfg.type, falling back to oidc when
  issuer is set and oauth2 otherwise, matching Python's get_auth_client.

server.OAuthConfig grows the transport fields (client_id, client_secret,
authorization_url, token_url, userinfo_url, redirect_uri, scope, issuer,
type) so the existing GetLoginChannels endpoint keeps working and
operators configure new channels in the same yaml block.

CSRF guard: login mints a 256-bit random state, persists it in Redis
(`oauth:state:<state>`, 5 min TTL) AND sets an HttpOnly state cookie.
Callback rejects the request unless the query state matches the cookie
AND the Redis key still exists; the key is deleted on use.

Success path mirrors Python's redirect contract — sign the user's
access token with utility.DumpAccessToken (same as LoginByEmail), write
it to a `ragflow_auth` cookie for the SPA, and 302 to the frontend with
`?auth=<user_id>`. Every error path 302s with `?error=<code>` reusing
Python's codes (invalid_state, missing_code, token_failed,
email_missing, user_inactive). New users get the full provisioning
the email-password Register path performs (User + Tenant + UserTenant
+ root File), keyed by login_channel = channel name.

Note: Python's OIDC client additionally verifies the id_token signature
against the discovered JWKS. We skip that here to avoid pulling in a
JWT library; /userinfo (authenticated by the access token) returns the
same claims, so login is correct end-to-end. Full id-token verification
is a follow-up.

Route ordering: /auth/login/:channel sits next to /auth/login/channels.
Gin v1.9.1's tree puts static children before wildcard ones in
addChild, so the static route still wins at lookup — verified against
the gin source.

Tests cover the OAuth client surface end-to-end with httptest servers:
authorization URL building (incl. preserved query), unsupported types,
OIDC discovery, token exchange (JSON + form responses + HTTP errors),
userinfo normalisation for OAuth2 and GitHub (including the primary-
email merge), and missing-required-field validation.
@Rene0422
Rene0422 force-pushed the feat/go-api-forgot-password-flow branch from dca5d31 to 3bc3858 Compare May 29, 2026 07:58
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 29, 2026
@Rene0422
Rene0422 force-pushed the feat/go-api-forgot-password-flow branch from 000d078 to 1e3104a Compare May 29, 2026 09:41
@Rene0422

Copy link
Copy Markdown
Contributor Author

@Hz-186 , I updated as you mentioned. Please check it again and let me know the result. Thanks.

@Rene0422
Rene0422 force-pushed the feat/go-api-forgot-password-flow branch from 1e3104a to 9e7e47b Compare June 1, 2026 11:14

@Harry-Hz-Zhang Harry-Hz-Zhang left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, @Rene0422 , could you fix those problems? ?

POST /api/v1/auth/password/reset with {}

  Go:

  {"code":101,"data":false,"message":"Key: 'ForgotResetPasswordRequest.Email' Error:Field validation ..."}

  Python:

  {"code":101,"data":false,"message":"email and passwords are required"}

Comment thread internal/service/user.go
return nil, common.CodeAuthenticationError, fmt.Errorf("email not verified")
}

plain, err := s.decryptPassword(req.NewPassword)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

POST /api/v1/auth/password/reset
{"email":"[email protected]","new_password":"x","confirm_new_password":"x"}

Go:
{"code":0,"message":"Password reset successful. Logged in.", ...}

Python:
{"code":100,"data":null,"message":"Error('Invalid base64-encoded string: ...')"}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Hz-186 — fixed.

The verbose Key: 'ForgotResetPasswordRequest.Email' Error:Field validation ... was coming from gin's validator, which fires
inside c.ShouldBindJSON before the request reaches the service.
The struct had binding:"required,email" on Email and
binding:"required" on NewPassword / ConfirmNewPassword.

Stripped all three tags. c.ShouldBindJSON now succeeds on {}
with zero-valued strings, and the service-level guard already in
place at internal/service/user.go —

if req.Email == "" || req.NewPassword == "" || req.ConfirmNewPassword == "" {
    return nil, common.CodeArgumentError,
        fmt.Errorf("email and passwords are required")
}

— produces exactly the Python message for the empty-body case.

Repro after the fix

curl -s -X POST http://localhost:9380/api/v1/auth/password/reset \
     -H 'Content-Type: application/json' \
     -d '{}'

# {"code":101,"data":false,"message":"email and passwords are required"}

Byte-for-byte match with the Python forget_reset_password
response.

Sanity for the non-empty paths

  • Bad email format — Python doesn't validate format on this
    endpoint either (the user already passed the OTP step). Dropping
    ,email matches that.
  • Wrong-typed fields ("email": 123) — JSON unmarshal still
    rejects type mismatches with the standard
    json: cannot unmarshal ... message. Pre-existing behavior,
    unchanged.
  • Mismatched passwords — "passwords do not match", same
    string as Python.
  • Unverified email — "email not verified", same as Python.

Guard against regression

Added a comment on the struct that cites the Python source
(api/apps/restful_apis/user_api.py:forget_reset_password) and
explains why the tags are intentionally absent, so a later
"let's tighten validation" cleanup pass doesn't re-introduce
them without realising it changes the API contract.

@Harry-Hz-Zhang Harry-Hz-Zhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, @Rene0422

The captcha_id flow is fine and arguably better than keying captcha by email.

My remaining concern is that the captcha image is returned as SVG with the answer embedded in <text> nodes, so a scripted client can base64-decode the response and read the captcha directly. Since this gates OTP email sending, could we use a raster captcha or otherwise avoid putting the answer in machine-readable response content?

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

hi, @Rene0422 , could u fix this ?

@Rene0422
Rene0422 force-pushed the feat/go-api-forgot-password-flow branch from 87a9321 to 73b5e61 Compare June 4, 2026 03:45
@Rene0422

Rene0422 commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

hi, @Rene0422 , could u fix this ?

Yes, of course.

@Rene0422
Rene0422 force-pushed the feat/go-api-forgot-password-flow branch from 5cccb5d to 2367bc4 Compare June 8, 2026 09:57

@Harry-Hz-Zhang Harry-Hz-Zhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hi @Rene0422,

Thanks for the PR! I ran a strict API alignment test between Python and Go (using the identical payloads and configurations). While some endpoints align perfectly (like Verify OTP and Reset Password), I found several edge-case mismatches and potential security/UX issues that need to be addressed before merging.

1. Agent Session Endpoints: Leaking DB Errors instead of User-Friendly Messages

For GET /agents/:agent_id/sessions, GET /agents/:agent_id/sessions/:session_id, and DELETE /agents/:agent_id/sessions/:session_id, when the agent is not found or the user lacks permission:

  • Python returns: {"code":103,"data":false,"message":"Make sure you have permission to access the agent."}
  • Go returns: {"code":500,"data":null,"message":"failed to check agent permission: record not found"}

Action Required:

  • In Go, avoid exposing raw ORM errors (like record not found) directly to the frontend.
  • Please map this gorm.ErrRecordNotFound to the user-friendly code: 103 message to match Python's contract.

2. SearchBots Retrieval Test: HTTP Status Code & Auth Bypass

When testing with an invalid API Key on /searchbots/retrieval_test:

  • Python returns: HTTP 200 OK with {"code":102,"message":"Authentication error: API key is invalid! "}
  • Go returns: HTTP 500 Internal Server Error with {"code":500,"message":"retrieval test failed"}

Action Required:

  • Go is throwing a hard HTTP 500. RAGFlow's standard practice is to return HTTP 200 and wrap the error code within the JSON response payload.
  • Go seems to bypass the early Auth validation that Python successfully catches.

3. SearchBots Related Questions: Potential Auth Bypass

When testing with an invalid API Key:

  • Python returns: {"code":102,"message":"Authentication error: API key is invalid! "}
  • Go returns: {"code":103,"message":"LLM call failed"}

Action Required:

  • Go is attempting to reach the LLM without properly validating the API Key/Tenant permissions first! Please check if the authentication middleware or the permission checks are correctly applied to searchBotHandler.Handle.

4. Forgot Password Send OTP: Payload Validation Mismatch

  • Python returns: {"code":101,"data":false,"message":"email and captcha required"}
  • Go returns: {"code":101,"data":false,"message":"email, captcha_id and captcha required"}

Action Required:

  • Go seems to explicitly require captcha_id in its error message while Python does not. Please ensure the required fields (captcha_id) align strictly with what the frontend currently sends and expects.

And Could you also add some _test.go files for the handlers involved?

Unit tests covering at least the error-path cases (e.g., invalid agent ID, missing fields, LLM auth failure) would help prevent regressions and make the behavior differences we discussed above easier to catch automatically.

@Harry-Hz-Zhang Harry-Hz-Zhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hi, @Rene0422 LGTM!!!

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label Jun 10, 2026
@Haruko386
Haruko386 marked this pull request as draft June 10, 2026 05:35
@Haruko386
Haruko386 marked this pull request as ready for review June 10, 2026 05:35
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label Jun 10, 2026
@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (e81bca7) to head (2367bc4).
⚠️ Report is 95 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15290   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@xugangqiang
xugangqiang merged commit bf59eb7 into infiniflow:main Jun 10, 2026
2 checks passed
This was referenced Jun 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants