Skip to content

fix(go-models): harden 302.AI driver requests - #15289

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
oktofeesh1:codex/302ai-driver-hardening
May 28, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
oktofeesh1:codex/302ai-driver-hardening

Conversation

@oktofeesh1

Copy link
Copy Markdown
Contributor

Summary

  • Harden the 302.AI model driver request validation and response parsing paths.
  • Add focused tests for chat request mode, model listing, malformed provider responses, and input validation.

What changed

  • Validate API keys, model names, rerank queries, ASR file paths, OCR inputs, parse URLs, task IDs, and model-list IDs before use.
  • Keep chat and streaming methods from accepting conflicting stream values in request payloads.
  • Send ListModels as a bodyless GET and parse the response with typed JSON structs instead of unchecked assertions.
  • Remove raw SSE event logging from stream handling.

Why

The driver could panic or send inconsistent requests when optional config fields were nil, empty, malformed, or contradicted the method path. This keeps provider-driver behavior explicit while preserving the existing supported 302.AI flows.

Validation

  • go test ./internal/entity/models -run TestAI302 -count=1
  • go test ./internal/entity/models -run 'TestAI302|TestJieKouAI' -count=1
  • go test -race ./internal/entity/models -run TestAI302 -count=1
  • git diff --check
  • Codex Security diff scan: no findings
  • CodeRabbit review: 0 issues

Notes

  • go test ./internal/entity/models -count=1 is currently blocked by an unrelated upstream panic in TestAstraflowEmbedReturnsNoSuchMethod.

Closes #14736

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ca1f54d0-c5ce-413a-8e95-5d7e3e5a2eb1

📥 Commits

Reviewing files that changed from the base of the PR and between 383f395 and 3ec12c6.

📒 Files selected for processing (2)
  • internal/entity/models/302ai.go
  • internal/entity/models/302ai_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/entity/models/302ai_test.go
  • internal/entity/models/302ai.go

📝 Walkthrough

Walkthrough

This PR centralizes input validation/trim logic and Authorization header handling across AI302Model methods, adjusts ListModels to use a GET with typed response parsing, ensures ShowTask URL-escapes task IDs, removes internal SSE-line logging, and adds comprehensive tests for request/response flows and input validation.

Changes

AI302 Provider Hardening

Layer / File(s) Summary
Validation helpers and import cleanup
internal/entity/models/302ai.go
Import cleanup and helper functions centralize validation and trimming of API keys, model names, and public document URLs; ChatWithMessages begins using validated API key and model checks.
Chat methods with validation and trimming
internal/entity/models/302ai.go
ChatWithMessages and ChatStreamlyWithSender trim model names, validate API keys, require non-nil sender for streaming, set Authorization headers from validated keys, and remove per-line SSE logging while preserving event parsing.
Embedding and reranking with validation
internal/entity/models/302ai.go
Embed and Rerank validate/trim model names and queries, compute defaults (e.g., top_n), and set Authorization headers from validated keys.
Media and document processing validation
internal/entity/models/302ai.go
TranscribeAudio, OCRFile, and ParseFile validate and trim filenames/URLs, accept data: URLs for content uploads when needed, and set Authorization headers from trimmed API keys.
ListModels structural refactoring
internal/entity/models/302ai.go
ListModels issues a GET without JSON body, sets Accept: application/json, validates the API key, and parses a typed data response, validating that every returned model id is non-empty after trimming.
ShowTask validation and trimming
internal/entity/models/302ai.go
ShowTask validates and trims taskID, uses url.PathEscape for the request path, and sets Authorization from the trimmed API key.
Test server harness and model constructor
internal/entity/models/302ai_test.go
Introduces an in-process HTTP test server that enforces auth and request-body semantics and a test constructor wiring AI302Model endpoints to the server.
Chat method behavior verification
internal/entity/models/302ai_test.go
Tests confirm non-streaming chat forces stream=false and parses Answer/ReasonContent; streaming mode forces stream=true, Accept: text/event-stream, and aggregates SSE delta events.
ListModels request and response tests
internal/entity/models/302ai_test.go
Tests verify GET semantics (no body), whitespace-trimming of model IDs, and rejection of malformed responses (missing data or empty id).
Comprehensive input validation coverage
internal/entity/models/302ai_test.go
Table-driven tests exercise validation failures across multiple methods (API key, model, sender, query, file/URL, task ID) and assert error messages include required-field substrings.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15000: Earlier PR that introduced the initial AI302Model provider implementation; this PR refactors and hardens those methods.
  • infiniflow/ragflow#15034: Related modifications to the 302.ai Go model driver that the current changes build upon.

Suggested labels

🐞 bug

Suggested reviewers

  • Haruko386

Poem

🐰 I trimmed the keys and tidied the names,
I escaped the task that tangled the frames,
Streams now flow with quieter cheer,
Tests hop in to make behavior clear,
A small carrot of safety for callers to claim.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: hardening the 302.AI driver with request validation and response parsing improvements.
Description check ✅ Passed The description covers the problem, changes, rationale, and validation but is missing the required template sections (What problem does this PR solve? and Type of change checkboxes).
Linked Issues check ✅ Passed The PR addresses the 302.AI model provider implementation requirements from #14736 by hardening request validation, response parsing, and adding comprehensive test coverage for driver reliability.
Out of Scope Changes check ✅ Passed All changes are focused on the 302.AI driver implementation: validation logic, request hardening, response parsing, and related tests—directly aligned with the linked issue objectives.

✏️ 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/entity/models/302ai.go (2)

926-946: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't splice raw taskID into the request path.

strings.TrimSpace still allows /, ?, and #, so a crafted task ID can change the request path or query instead of addressing a single task resource. Escape the path segment or reject task IDs containing reserved URL characters before building apiURL.

🤖 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/entity/models/302ai.go` around lines 926 - 946, The code currently
interpolates taskID directly into apiURL allowing reserved characters to alter
the path; sanitize or escape the task id before constructing the URL. Replace
usage of strings.TrimSpace(taskID) when building apiURL with a
trimmed-and-URL-escaped segment (use url.PathEscape on the trimmed taskID) or
alternatively validate/reject taskIDs containing '/', '?', '#' etc., then build
apiURL from a.BaseURL[region], a.URLSuffix.DocumentParse and the escaped task id
so http.NewRequest always targets the intended resource.

697-718: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Validate caller-supplied document URLs before forwarding them.

These paths only trim urls/documentURL, so malformed values still reach 302.ai even though ParseFile now says it requires a valid public document URL. Reject obviously invalid URL strings here so callers fail locally instead of after a network round-trip.

Also applies to: 789-809

🤖 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/entity/models/302ai.go` around lines 697 - 718, The code currently
forwards caller-supplied urls/documentURL without validating them; update the
handler around the urls/documentURL usage (the variables named urls and
documentURL in the 302ai.go flow that also calls ParseFile) to parse and
validate each trimmed URL before proceeding: use net/url (url.Parse or
url.ParseRequestURI) and ensure scheme is http or https and that Host is
non-empty, returning an error (e.g., "invalid document URL") if validation
fails; apply the same change to both occurrences referenced (the block using
urls near where modelName/ apiConfig are validated and the later block at
~789-809) so malformed URLs are rejected locally instead of being sent to
302.ai.
🤖 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.

Outside diff comments:
In `@internal/entity/models/302ai.go`:
- Around line 926-946: The code currently interpolates taskID directly into
apiURL allowing reserved characters to alter the path; sanitize or escape the
task id before constructing the URL. Replace usage of strings.TrimSpace(taskID)
when building apiURL with a trimmed-and-URL-escaped segment (use url.PathEscape
on the trimmed taskID) or alternatively validate/reject taskIDs containing '/',
'?', '#' etc., then build apiURL from a.BaseURL[region],
a.URLSuffix.DocumentParse and the escaped task id so http.NewRequest always
targets the intended resource.
- Around line 697-718: The code currently forwards caller-supplied
urls/documentURL without validating them; update the handler around the
urls/documentURL usage (the variables named urls and documentURL in the 302ai.go
flow that also calls ParseFile) to parse and validate each trimmed URL before
proceeding: use net/url (url.Parse or url.ParseRequestURI) and ensure scheme is
http or https and that Host is non-empty, returning an error (e.g., "invalid
document URL") if validation fails; apply the same change to both occurrences
referenced (the block using urls near where modelName/ apiConfig are validated
and the later block at ~789-809) so malformed URLs are rejected locally instead
of being sent to 302.ai.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d5e5bb15-79f6-45c2-9d44-809651cedb0e

📥 Commits

Reviewing files that changed from the base of the PR and between 2c099bb and 383f395.

📒 Files selected for processing (2)
  • internal/entity/models/302ai.go
  • internal/entity/models/302ai_test.go

@oktofeesh1

Copy link
Copy Markdown
Contributor Author

hi @Haruko386 - another driver improvement - sorry for throwing so many at you, I have many on my list to fix!

@oktofeesh1
oktofeesh1 force-pushed the codex/302ai-driver-hardening branch from 383f395 to 3ec12c6 Compare May 27, 2026 07:07

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label May 27, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 27, 2026
@Haruko386
Haruko386 marked this pull request as draft May 27, 2026 09:02
@Haruko386
Haruko386 marked this pull request as ready for review May 27, 2026 09:02
@codecov

codecov Bot commented May 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (2c099bb) to head (3ec12c6).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15289   +/-   ##
=======================================
  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 Sentry.
📢 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Implement model providers of RAGFlow API server in Go

3 participants