-
Notifications
You must be signed in to change notification settings - Fork 2
feat: add direct-to-vm browser routing #95
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
rgarcia
wants to merge
11
commits into
next
Choose a base branch
from
raf/browser-scoped-client
base: next
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.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ef994b4
feat: add browser-scoped session client
rgarcia 64f7f81
fix: align browser-scoped routing with base_url
rgarcia 3e3e33f
fix: tighten browser-scoped helper surface
rgarcia 0ac61ef
refactor: narrow browser-scoped helper exports
rgarcia b6a77bc
feat: generate browser-scoped service bindings
rgarcia 92dc96e
docs: add browser-scoped raw http example
rgarcia 3452e53
refactor: remove browser session wrapper layer
rgarcia 6bdf25f
refactor: simplify direct-to-vm route caching
rgarcia 909c377
refactor: rename browser routing subresources config
rgarcia 77bda33
fix: clean up go browser routing follow-ups
rgarcia d594f39
fix: remove old go browser scope package
rgarcia 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,34 @@ | ||
| package kernel | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "net/http" | ||
| "slices" | ||
|
|
||
| "github.com/kernel/kernel-go-sdk/internal/requestconfig" | ||
| "github.com/kernel/kernel-go-sdk/lib/browserrouting" | ||
| "github.com/kernel/kernel-go-sdk/option" | ||
| ) | ||
|
|
||
| // HTTPClient returns an [http.Client] that performs HTTP requests through the | ||
| // browser VM's internal /curl/raw path using cached browser route data. | ||
| func (r *BrowserService) HTTPClient(id string, opts ...option.RequestOption) (*http.Client, error) { | ||
| opts = slices.Concat(r.Options, opts) | ||
| cache := browserRouteCacheFromOptions(opts) | ||
| if cache == nil { | ||
| return nil, fmt.Errorf("kernel: browser route cache is not configured") | ||
| } | ||
|
|
||
| route, ok := cache.Load(id) | ||
| if !ok { | ||
| return nil, fmt.Errorf("kernel: browser route cache does not contain session %s", id) | ||
| } | ||
|
|
||
| cfg, err := requestconfig.NewRequestConfig(context.Background(), http.MethodGet, "https://example.com", nil, nil, opts...) | ||
| if err != nil { | ||
| return browserrouting.NewHTTPClient(route.BaseURL, route.JWT, nil), nil | ||
| } | ||
|
|
||
| return browserrouting.NewHTTPClient(route.BaseURL, route.JWT, cfg.HTTPClient), nil | ||
| } | ||
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,84 @@ | ||
| package kernel | ||
|
|
||
| import ( | ||
| "github.com/kernel/kernel-go-sdk/internal/requestconfig" | ||
| "github.com/kernel/kernel-go-sdk/lib/browserrouting" | ||
| "github.com/kernel/kernel-go-sdk/option" | ||
| ) | ||
|
|
||
| // BrowserRoutingConfig controls which browser subresources route directly to the browser VM. | ||
| type BrowserRoutingConfig struct { | ||
| Enabled bool | ||
| Subresources []string | ||
| } | ||
|
|
||
| type browserRoutingOption struct { | ||
| cache *browserrouting.RouteCache | ||
| config BrowserRoutingConfig | ||
| } | ||
|
|
||
| type browserRouteCacheOption struct { | ||
| cache *browserrouting.RouteCache | ||
| } | ||
|
|
||
| // WithBrowserRouting enables direct-to-VM routing for the configured browser subresources. | ||
| func WithBrowserRouting(config BrowserRoutingConfig) option.RequestOption { | ||
| return &browserRoutingOption{config: config} | ||
| } | ||
|
|
||
| func (o *browserRoutingOption) Apply(r *requestconfig.RequestConfig) error { | ||
| if !o.config.Enabled { | ||
| return nil | ||
| } | ||
| r.Middlewares = append(r.Middlewares, browserrouting.DirectVMRoutingMiddleware(o.cache, o.config.Subresources)) | ||
| return nil | ||
| } | ||
|
|
||
| func (o *browserRoutingOption) browserRouteCache() *browserrouting.RouteCache { | ||
| return o.cache | ||
| } | ||
|
|
||
| func (o *browserRouteCacheOption) Apply(*requestconfig.RequestConfig) error { | ||
| return nil | ||
| } | ||
|
|
||
| func (o *browserRouteCacheOption) browserRouteCache() *browserrouting.RouteCache { | ||
| return o.cache | ||
| } | ||
|
|
||
| func withBrowserRouteCache(cache *browserrouting.RouteCache) option.RequestOption { | ||
| return &browserRouteCacheOption{cache: cache} | ||
| } | ||
|
|
||
| func browserRouteCacheFromOptions(opts []option.RequestOption) *browserrouting.RouteCache { | ||
| for _, opt := range opts { | ||
| if carrier, ok := opt.(interface{ browserRouteCache() *browserrouting.RouteCache }); ok { | ||
| if cache := carrier.browserRouteCache(); cache != nil { | ||
| return cache | ||
| } | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func storeBrowserRouteCache(opts []option.RequestOption, refs ...browserrouting.Ref) { | ||
| cache := browserRouteCacheFromOptions(opts) | ||
| for _, ref := range refs { | ||
| route, ok := browserRouteFromRef(ref) | ||
| if cache != nil && ok { | ||
| cache.Store(route) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func browserRouteFromRef(ref browserrouting.Ref) (browserrouting.Route, bool) { | ||
| norm, err := ref.Normalize() | ||
| if err != nil { | ||
| return browserrouting.Route{}, false | ||
| } | ||
| return browserrouting.Route{ | ||
| SessionID: norm.SessionID, | ||
| BaseURL: norm.BaseURL, | ||
| JWT: norm.JWT, | ||
| }, true | ||
| } |
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,113 @@ | ||
| package kernel | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/kernel/kernel-go-sdk/option" | ||
| ) | ||
|
|
||
| func TestBrowserRoutingWarmsCacheAndRoutesAllowlistedSubresources(t *testing.T) { | ||
| var calls []struct { | ||
| Path string | ||
| Auth string | ||
| } | ||
| var srv *httptest.Server | ||
| srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| calls = append(calls, struct { | ||
| Path string | ||
| Auth string | ||
| }{Path: r.URL.Path + "?" + r.URL.RawQuery, Auth: r.Header.Get("Authorization")}) | ||
|
|
||
| w.Header().Set("Content-Type", "application/json") | ||
| switch r.URL.Path { | ||
| case "/browsers": | ||
| _ = json.NewEncoder(w).Encode(map[string]any{ | ||
| "session_id": "sess-1", | ||
| "base_url": srv.URL + "/browser/kernel", | ||
| "cdp_ws_url": "wss://browser-session.test/browser/cdp?jwt=token-abc", | ||
| }) | ||
| default: | ||
| _ = json.NewEncoder(w).Encode(map[string]any{ | ||
| "duration_ms": 1, | ||
| "exit_code": 0, | ||
| "stderr_b64": "", | ||
| "stdout_b64": "", | ||
| }) | ||
| } | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| client := NewClient( | ||
| option.WithBaseURL(srv.URL), | ||
| option.WithAPIKey("sk_test"), | ||
| option.WithHTTPClient(srv.Client()), | ||
| WithBrowserRouting(BrowserRoutingConfig{Enabled: true, Subresources: []string{"process"}}), | ||
| ) | ||
|
|
||
| if _, err := client.Browsers.New(context.Background(), BrowserNewParams{}); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if _, err := client.Browsers.Process.Exec(context.Background(), "sess-1", BrowserProcessExecParams{Command: "echo"}); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
|
|
||
| if route, ok := client.BrowserRouteCache.Load("sess-1"); !ok || route.JWT != "token-abc" { | ||
| t.Fatalf("expected warmed browser route cache, got %#v ok=%v", route, ok) | ||
| } | ||
| if len(calls) != 2 { | ||
| t.Fatalf("expected 2 calls, got %d", len(calls)) | ||
| } | ||
| if calls[1].Path != "/browser/kernel/process/exec?jwt=token-abc" { | ||
| t.Fatalf("expected direct VM path, got %q", calls[1].Path) | ||
| } | ||
| if calls[1].Auth != "" { | ||
| t.Fatalf("expected authorization header removed, got %q", calls[1].Auth) | ||
| } | ||
| } | ||
|
|
||
| func TestBrowserRoutingSkipsSubresourcesOutsideConfiguredAllowlist(t *testing.T) { | ||
| var paths []string | ||
| var srv *httptest.Server | ||
| srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| paths = append(paths, r.URL.Path) | ||
| w.Header().Set("Content-Type", "application/json") | ||
| switch r.URL.Path { | ||
| case "/browsers": | ||
| _ = json.NewEncoder(w).Encode(map[string]any{ | ||
| "session_id": "sess-1", | ||
| "base_url": srv.URL + "/browser/kernel", | ||
| "cdp_ws_url": "wss://browser-session.test/browser/cdp?jwt=token-abc", | ||
| }) | ||
| default: | ||
| _ = json.NewEncoder(w).Encode(map[string]any{ | ||
| "duration_ms": 1, | ||
| "exit_code": 0, | ||
| "stderr_b64": "", | ||
| "stdout_b64": "", | ||
| }) | ||
| } | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| client := NewClient( | ||
| option.WithBaseURL(srv.URL), | ||
| option.WithAPIKey("sk_test"), | ||
| option.WithHTTPClient(srv.Client()), | ||
| WithBrowserRouting(BrowserRoutingConfig{Enabled: true, Subresources: []string{"computer"}}), | ||
| ) | ||
|
|
||
| if _, err := client.Browsers.New(context.Background(), BrowserNewParams{}); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if _, err := client.Browsers.Process.Exec(context.Background(), "sess-1", BrowserProcessExecParams{Command: "echo"}); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
|
|
||
| if got := paths[len(paths)-1]; got != "/browsers/sess-1/process/exec" { | ||
| t.Fatalf("expected control-plane path, got %q", got) | ||
| } | ||
| } |
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,77 @@ | ||
| package kernel | ||
|
|
||
| import ( | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/kernel/kernel-go-sdk/lib/browserrouting" | ||
| "github.com/kernel/kernel-go-sdk/option" | ||
| ) | ||
|
|
||
| func TestBrowserSessionHTTPClientRawCurl(t *testing.T) { | ||
| var sawRaw string | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| if r.URL.Path != "/browser/kernel/curl/raw" { | ||
| http.NotFound(w, r) | ||
| return | ||
| } | ||
| sawRaw = r.URL.RawQuery | ||
| w.Header().Set("Content-Type", "text/plain") | ||
| _, _ = w.Write([]byte("proxied")) | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| c := NewClient( | ||
| option.WithBaseURL("https://api.example/"), | ||
| option.WithAPIKey("sk"), | ||
| option.WithHTTPClient(srv.Client()), | ||
| ) | ||
|
|
||
| storeBrowserRouteCache(c.Options, browserrouting.Ref{ | ||
| SessionID: "sid", | ||
| BaseURL: srv.URL + "/browser/kernel", | ||
| CdpWsURL: "wss://x/browser/cdp?jwt=j1", | ||
| }) | ||
|
|
||
| hc, err := c.Browsers.HTTPClient("sid") | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| req, err := http.NewRequest(http.MethodGet, "https://httpbin.org/get", nil) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| res, err := hc.Do(req) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| defer res.Body.Close() | ||
| body, _ := io.ReadAll(res.Body) | ||
| if string(body) != "proxied" { | ||
| t.Fatalf("body %q", body) | ||
| } | ||
| if sawRaw == "" { | ||
| t.Fatal("expected raw query on curl/raw") | ||
| } | ||
| } | ||
|
|
||
| func TestBrowserSessionHTTPClientRequiresCachedRoute(t *testing.T) { | ||
| c := NewClient( | ||
| option.WithBaseURL("https://api.example/"), | ||
| option.WithAPIKey("sk"), | ||
| ) | ||
|
|
||
| storeBrowserRouteCache(c.Options, browserrouting.Ref{ | ||
| SessionID: "sid", | ||
| BaseURL: "https://browser-session.test/browser/kernel", | ||
| CdpWsURL: "wss://x/browser/cdp?jwt=j1", | ||
| }) | ||
| c.BrowserRouteCache.Delete("sid") | ||
|
|
||
| _, err := c.Browsers.HTTPClient("sid") | ||
| if err == nil { | ||
| t.Fatal("expected cached route lookup failure") | ||
| } | ||
| } |
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.
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.
Config error silently swallowed, dropping custom HTTP client
Medium Severity
When
requestconfig.NewRequestConfigreturns an error, the code silently returns a fallback HTTP client built with anilunderlying (which defaults tohttp.DefaultClient) and anilerror. This swallows the configuration error and silently drops any custom HTTP client the user configured viaoption.WithHTTPClient. Every other call site ofNewRequestConfigin the codebase propagates the error. The user's custom transport, TLS, proxy, and timeout settings would be silently lost with no indication of failure.Reviewed by Cursor Bugbot for commit d594f39. Configure here.