-
Notifications
You must be signed in to change notification settings - Fork 58
fix(gateway): harden AI provider HTTP error handling and context propagation #258
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tlnarayana005
wants to merge
1
commit into
AnkanMisra:main
Choose a base branch
from
tlnarayana005:fix/harden-http-clients-and-response-handling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+138
−7
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| package ai | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| // TestOpenRouterErrorBodyLimit verifies that the OpenRouter provider caps error | ||
| // response body reads at maxErrorResponseBytes to prevent OOM from a malicious | ||
| // upstream. | ||
| func TestOpenRouterErrorBodyLimit(t *testing.T) { | ||
| // Serve a body larger than the limit (8KB > 4KB limit) | ||
| oversizedBody := strings.Repeat("X", 8192) | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| w.Write([]byte(oversizedBody)) | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| p := &OpenRouterProvider{ | ||
| apiKey: "test-key", | ||
| model: "test-model", | ||
| url: srv.URL, | ||
| } | ||
|
|
||
| _, err := p.Generate(context.Background(), "test prompt") | ||
| if err == nil { | ||
| t.Fatal("expected error from 500 response, got nil") | ||
| } | ||
|
|
||
| // The error message should NOT contain the full 8KB body | ||
| errMsg := err.Error() | ||
| if len(errMsg) > int(maxErrorResponseBytes)+200 { | ||
| t.Errorf("error message too long (%d bytes), expected capped at ~%d", len(errMsg), maxErrorResponseBytes) | ||
| } | ||
| } | ||
|
|
||
| // TestOllamaErrorBodyLimit verifies that the Ollama provider caps error | ||
| // response body reads at maxOllamaErrorResponseBytes. | ||
| func TestOllamaErrorBodyLimit(t *testing.T) { | ||
| oversizedBody := strings.Repeat("Y", 8192) | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| w.Write([]byte(oversizedBody)) | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| p := &OllamaProvider{ | ||
| url: srv.URL, | ||
| model: "test-model", | ||
| } | ||
|
|
||
| _, err := p.Generate(context.Background(), "test prompt") | ||
| if err == nil { | ||
| t.Fatal("expected error from 500 response, got nil") | ||
| } | ||
|
|
||
| errMsg := err.Error() | ||
| if len(errMsg) > int(maxOllamaErrorResponseBytes)+200 { | ||
| t.Errorf("error message too long (%d bytes), expected capped at ~%d", len(errMsg), maxOllamaErrorResponseBytes) | ||
| } | ||
| } | ||
|
|
||
| // TestOpenRouterContextCanceled verifies that context.Canceled is returned | ||
| // (not wrapped in a connection error) when the context is canceled. | ||
| func TestOpenRouterContextCanceled(t *testing.T) { | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| // Never respond — let the context cancel | ||
| <-r.Context().Done() | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| p := &OpenRouterProvider{ | ||
| apiKey: "test-key", | ||
| model: "test-model", | ||
| url: srv.URL, | ||
| } | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| cancel() // Cancel immediately | ||
|
|
||
| _, err := p.Generate(ctx, "test prompt") | ||
| if err == nil { | ||
| t.Fatal("expected error from canceled context, got nil") | ||
| } | ||
| if err != context.Canceled { | ||
| t.Errorf("expected context.Canceled, got: %v", err) | ||
| } | ||
| } | ||
|
|
||
| // TestOllamaContextCanceled verifies the same for the Ollama provider. | ||
| func TestOllamaContextCanceled(t *testing.T) { | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| <-r.Context().Done() | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| p := &OllamaProvider{ | ||
| url: srv.URL, | ||
| model: "test-model", | ||
| } | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| cancel() | ||
|
|
||
| _, err := p.Generate(ctx, "test prompt") | ||
| if err == nil { | ||
| t.Fatal("expected error from canceled context, got nil") | ||
| } | ||
| if err != context.Canceled { | ||
| t.Errorf("expected context.Canceled, got: %v", err) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
http.DefaultClient.Doreturns a deadline/cancellation error from the client or transport rather than from the passed request context,ctx.Err()is still nil; for example, settinghttp.DefaultClient = &http.Client{Timeout: ...}makes this branch return("", nil). That makesGeneratelook successful with an empty summary, so a paid summarize request can get a 200/receipt instead of an upstream error. Returnctx.Err()only when it is non-nil, otherwise return the matchederror the appropriate context sentinel; the identical Ollama branch needs the same treatment.Useful? React with 👍 / 👎.