-
Notifications
You must be signed in to change notification settings - Fork 80
feat: add session management for proxy #1081
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
02c902f
feat: add session management for proxy
taskbot 49efb3c
fixes from review
taskbot 9948379
fix tests
taskbot 1f6d97a
refactor session management
taskbot 591f815
fixes from review
taskbot eb0c1a6
add tests
taskbot b4846a1
fix lint
taskbot 9f62a12
Update pkg/transport/session/proxy_session.go
yrobla ed1e12f
fixes from copilot
taskbot 81a66c6
Merge branch 'main' into issue-1078
yrobla 99edf45
Merge branch 'main' into issue-1078
yrobla 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
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,126 @@ | ||
package transparent | ||
|
||
import ( | ||
"bufio" | ||
"net/http" | ||
"net/http/httptest" | ||
"net/http/httputil" | ||
"net/url" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
|
||
"github.com/stacklok/toolhive/pkg/logger" | ||
) | ||
|
||
func init() { | ||
logger.Initialize() // ensure logging doesn't panic | ||
} | ||
|
||
func TestStreamingSessionIDDetection(t *testing.T) { | ||
t.Parallel() | ||
proxy := NewTransparentProxy("127.0.0.1", 0, "test", "http://example.com", nil) | ||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | ||
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") | ||
w.WriteHeader(200) | ||
|
||
// Simulate SSE lines | ||
w.Write([]byte("data: hello\n")) | ||
w.Write([]byte("data: sessionId=ABC123\n")) | ||
w.(http.Flusher).Flush() | ||
|
||
time.Sleep(10 * time.Millisecond) | ||
w.Write([]byte("data: more\n")) | ||
})) | ||
defer target.Close() | ||
|
||
// set up reverse proxy using ModifyResponse | ||
parsedURL, _ := http.NewRequest("GET", target.URL, nil) | ||
proxyURL := httputil.NewSingleHostReverseProxy(parsedURL.URL) | ||
proxyURL.FlushInterval = -1 | ||
proxyURL.Transport = &tracingTransport{base: http.DefaultTransport, p: proxy} | ||
proxyURL.ModifyResponse = proxy.modifyForSessionID | ||
|
||
// hit the proxy | ||
rec := httptest.NewRecorder() | ||
req := httptest.NewRequest("GET", target.URL, nil) | ||
proxyURL.ServeHTTP(rec, req) | ||
|
||
// read all SSE lines | ||
sc := bufio.NewScanner(rec.Body) | ||
var bodyLines []string | ||
for sc.Scan() { | ||
bodyLines = append(bodyLines, sc.Text()) | ||
} | ||
assert.Contains(t, bodyLines, "data: sessionId=ABC123") | ||
|
||
// side-effect: proxy should have seen session | ||
assert.True(t, proxy.IsServerInitialized, "server should have been initialized") | ||
_, ok := proxy.sessionManager.Get("ABC123") | ||
assert.True(t, ok, "sessionManager should have stored ABC123") | ||
} | ||
|
||
func createBasicProxy(p *TransparentProxy, targetURL *url.URL) *httputil.ReverseProxy { | ||
proxy := httputil.NewSingleHostReverseProxy(targetURL) | ||
proxy.Director = func(r *http.Request) { | ||
r.URL.Scheme = targetURL.Scheme | ||
r.URL.Host = targetURL.Host | ||
r.Host = targetURL.Host | ||
} | ||
proxy.FlushInterval = -1 | ||
proxy.Transport = &tracingTransport{base: http.DefaultTransport, p: p} | ||
proxy.ModifyResponse = p.modifyForSessionID | ||
return proxy | ||
} | ||
|
||
func TestNoSessionIDInNonSSE(t *testing.T) { | ||
t.Parallel() | ||
|
||
p := NewTransparentProxy("127.0.0.1", 0, "test", "", nil) | ||
|
||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | ||
// Set both content-type and also optionally MCP header to test behavior | ||
w.Header().Set("Content-Type", "application/json") | ||
w.WriteHeader(200) | ||
w.Write([]byte(`{"hello": "world"}`)) | ||
})) | ||
defer target.Close() | ||
|
||
targetURL, _ := url.Parse(target.URL) | ||
proxy := createBasicProxy(p, targetURL) | ||
|
||
rec := httptest.NewRecorder() | ||
req := httptest.NewRequest("GET", target.URL, nil) | ||
proxy.ServeHTTP(rec, req) | ||
|
||
assert.False(t, p.IsServerInitialized, "server should not be initialized for application/json") | ||
_, ok := p.sessionManager.Get("XYZ789") | ||
assert.False(t, ok, "no session should be added") | ||
} | ||
|
||
func TestHeaderBasedSessionInitialization(t *testing.T) { | ||
t.Parallel() | ||
|
||
p := NewTransparentProxy("127.0.0.1", 0, "test", "", nil) | ||
|
||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | ||
// Set both content-type and also optionally MCP header to test behavior | ||
w.Header().Set("Content-Type", "application/json") | ||
w.Header().Set("Mcp-Session-Id", "XYZ789") | ||
w.WriteHeader(200) | ||
w.Write([]byte(`{"hello": "world"}`)) | ||
})) | ||
defer target.Close() | ||
|
||
targetURL, _ := url.Parse(target.URL) | ||
proxy := createBasicProxy(p, targetURL) | ||
|
||
rec := httptest.NewRecorder() | ||
req := httptest.NewRequest("GET", target.URL, nil) | ||
proxy.ServeHTTP(rec, req) | ||
|
||
assert.True(t, p.IsServerInitialized, "server should not be initialized for application/json") | ||
yrobla marked this conversation as resolved.
Show resolved
Hide resolved
yrobla marked this conversation as resolved.
Show resolved
Hide resolved
|
||
_, ok := p.sessionManager.Get("XYZ789") | ||
assert.True(t, ok, "no session should be added") | ||
yrobla marked this conversation as resolved.
Show resolved
Hide resolved
yrobla marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.