fix(desktop): pair the Lite browser against the local API listener (#3677)
* fix(desktop): pair the Lite browser against the local API listener The Wails page origin cannot become the extension WebSocket, and a page-controlled host must not be able to redirect that pairing link. * fix(desktop): check the proxy test response body close golangci-lint errcheck rejects an unchecked Body.Close in the new desktop proxy tests. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>main
parent
9fc08c2079
commit
65d8a34ead
|
|
@ -340,7 +340,7 @@ func main() {
|
|||
|
||||
// Wait for the backend URL to be set
|
||||
targetURL, _ := url.Parse(app.backendURL)
|
||||
proxy := httputil.NewSingleHostReverseProxy(targetURL)
|
||||
proxy := desktopAPIProxy(targetURL)
|
||||
|
||||
// Start Wails application
|
||||
// We use a Reverse Proxy to seamlessly proxy Wails' frontend to our Go backend
|
||||
|
|
@ -443,6 +443,26 @@ func resolveDesktopDataPath(rawPath, defaultRelativePath, appSupportDir string)
|
|||
return filepath.Join(appSupportDir, filepath.Clean(trimmed))
|
||||
}
|
||||
|
||||
// desktopAPIProxy forwards the webview to the loopback Gin server. Pairing
|
||||
// needs the API listener as Host so the link cannot be aimed at another
|
||||
// machine. Other routes keep the page Host (wails.localhost), which OIDC
|
||||
// callbacks and embed origin checks still compare against.
|
||||
func desktopAPIProxy(target *url.URL) *httputil.ReverseProxy {
|
||||
return &httputil.ReverseProxy{
|
||||
Rewrite: func(r *httputil.ProxyRequest) {
|
||||
r.SetURL(target)
|
||||
r.SetXForwarded()
|
||||
if !isBrowserPairingRequest(r.In) {
|
||||
r.Out.Host = r.In.Host
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func isBrowserPairingRequest(req *http.Request) bool {
|
||||
return req != nil && req.URL != nil && req.Method == http.MethodPost && req.URL.Path == "/api/v1/me/browser"
|
||||
}
|
||||
|
||||
// desktopBackendListenAddr returns the TCP address for the embedded Gin server (Wails desktop).
|
||||
// Binds 127.0.0.1 by default, or 0.0.0.0 when http_bind_public is set in desktop-prefs.json.
|
||||
func desktopBackendListenAddr() string {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,61 @@
|
|||
//go:build !bindings
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDesktopAPIProxyRewritesWailsHostToLoopback(t *testing.T) {
|
||||
var got string
|
||||
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got = r.Host
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer backend.Close()
|
||||
|
||||
target, err := url.Parse(backend.URL)
|
||||
require.NoError(t, err)
|
||||
front := httptest.NewServer(desktopAPIProxy(target))
|
||||
defer front.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, front.URL+"/api/v1/me/browser", nil)
|
||||
require.NoError(t, err)
|
||||
req.Host = "wails.localhost"
|
||||
resp, err := front.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
require.NoError(t, resp.Body.Close())
|
||||
require.Equal(t, http.StatusNoContent, resp.StatusCode)
|
||||
require.Equal(t, target.Host, got)
|
||||
}
|
||||
|
||||
func TestDesktopAPIProxyKeepsHostForOtherRoutes(t *testing.T) {
|
||||
var got string
|
||||
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got = r.Host
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer backend.Close()
|
||||
|
||||
target, err := url.Parse(backend.URL)
|
||||
require.NoError(t, err)
|
||||
front := httptest.NewServer(desktopAPIProxy(target))
|
||||
defer front.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, front.URL+"/api/v1/auth/oidc/start", nil)
|
||||
require.NoError(t, err)
|
||||
req.Host = "wails.localhost"
|
||||
resp, err := front.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
require.NoError(t, resp.Body.Close())
|
||||
require.Equal(t, http.StatusNoContent, resp.StatusCode)
|
||||
require.Equal(t, "wails.localhost", got)
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { pairingPageOrigin, preferredDesktopAPIBase } from './browserPairingOrigin.ts'
|
||||
|
||||
test('pairingPageOrigin keeps an http or https page', () => {
|
||||
assert.equal(pairingPageOrigin('https://weknora.example'), 'https://weknora.example')
|
||||
assert.equal(pairingPageOrigin('http://127.0.0.1:8080'), 'http://127.0.0.1:8080')
|
||||
})
|
||||
|
||||
test('pairingPageOrigin uses the desktop API host when the page is the Wails shell', () => {
|
||||
assert.equal(
|
||||
pairingPageOrigin('wails://wails.localhost', 'http://127.0.0.1:53124/api/v1'),
|
||||
'http://127.0.0.1:53124',
|
||||
)
|
||||
})
|
||||
|
||||
test('pairingPageOrigin leaves a non-http page alone when no API base is known', () => {
|
||||
assert.equal(pairingPageOrigin('wails://wails.localhost', ''), 'wails://wails.localhost')
|
||||
})
|
||||
|
||||
test('pairingPageOrigin ignores a non-loopback API base for the Wails shell', () => {
|
||||
assert.equal(
|
||||
pairingPageOrigin('wails://wails.localhost', 'https://evil.example/api/v1'),
|
||||
'wails://wails.localhost',
|
||||
)
|
||||
})
|
||||
|
||||
test('preferredDesktopAPIBase uses the native binding before the page global', () => {
|
||||
assert.equal(
|
||||
preferredDesktopAPIBase('http://127.0.0.1:53124/api/v1', 'https://evil.example/api/v1'),
|
||||
'http://127.0.0.1:53124/api/v1',
|
||||
)
|
||||
assert.equal(preferredDesktopAPIBase('', 'http://127.0.0.1:53124/api/v1'), 'http://127.0.0.1:53124/api/v1')
|
||||
})
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
const loopbackHosts = new Set(['localhost', '127.0.0.1', '::1'])
|
||||
|
||||
function isLoopbackHostname(hostname: string): boolean {
|
||||
return loopbackHosts.has(hostname.replace(/^\[|\]$/g, '').toLowerCase())
|
||||
}
|
||||
|
||||
// Native GetAPIBaseURL is the desktop listener. The page global is only a
|
||||
// fallback, because any script in the Lite window can overwrite it.
|
||||
export function preferredDesktopAPIBase(nativeBase?: string | null, injectedBase?: string | null): string {
|
||||
const native = (nativeBase ?? '').trim()
|
||||
if (native) return native
|
||||
return (injectedBase ?? '').trim()
|
||||
}
|
||||
|
||||
// The pairing link is a WebSocket the Chrome extension dials. A normal site
|
||||
// uses the page origin so a proxy port is preserved. The Lite window is
|
||||
// wails://wails.localhost, which cannot become ws/wss, so a loopback desktop
|
||||
// API base supplies the origin instead.
|
||||
export function pairingPageOrigin(pageOrigin: string, apiBase?: string): string {
|
||||
try {
|
||||
const page = new URL(pageOrigin)
|
||||
if (page.protocol === 'http:' || page.protocol === 'https:') {
|
||||
return page.origin
|
||||
}
|
||||
} catch {
|
||||
/* custom schemes and empty origins fall through */
|
||||
}
|
||||
const base = (apiBase || '').trim()
|
||||
if (!base) {
|
||||
return pageOrigin
|
||||
}
|
||||
try {
|
||||
const api = new URL(base)
|
||||
if ((api.protocol !== 'http:' && api.protocol !== 'https:') || !isLoopbackHostname(api.hostname)) {
|
||||
return pageOrigin
|
||||
}
|
||||
return api.origin
|
||||
} catch {
|
||||
return pageOrigin
|
||||
}
|
||||
}
|
||||
|
|
@ -168,6 +168,7 @@
|
|||
import { computed, onMounted, onBeforeUnmount, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { get, post, getDown } from '@/utils/request'
|
||||
import { pairingPageOrigin, preferredDesktopAPIBase } from '@/utils/browserPairingOrigin'
|
||||
import { useBrowserConnectionStore } from '@/stores/browserConnection'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
import browserLogo from '@/assets/browserskill/logo.png'
|
||||
|
|
@ -206,6 +207,22 @@ const capabilities = [
|
|||
]
|
||||
const formatDate = (value: string) => new Date(value).toLocaleString(locale.value, { dateStyle: 'short', timeStyle: 'short' })
|
||||
function clearPairing() { pairing.value = ''; copied.value = false; copyFallback.value = false; clearTimeout(expiry) }
|
||||
async function desktopApiBase(): Promise<string> {
|
||||
const win = window as Window & {
|
||||
__WEKNORA_API_BASE__?: string
|
||||
go?: { main?: { App?: { GetAPIBaseURL?: () => Promise<string> | string } } }
|
||||
}
|
||||
let native = ''
|
||||
const fn = win.go?.main?.App?.GetAPIBaseURL
|
||||
if (typeof fn === 'function') {
|
||||
try {
|
||||
native = String(await Promise.resolve(fn()) || '')
|
||||
} catch {
|
||||
native = ''
|
||||
}
|
||||
}
|
||||
return preferredDesktopAPIBase(native, win.__WEKNORA_API_BASE__)
|
||||
}
|
||||
async function refresh() {
|
||||
try {
|
||||
if (!busy.value && !document.hidden) {
|
||||
|
|
@ -225,7 +242,8 @@ async function pair() {
|
|||
busy.value = true; error.value = ''; revision++
|
||||
try {
|
||||
if (!pairing.value || Date.now() >= pairExpires) {
|
||||
const result = await post<{ data: { pairing_link: string } }>(endpoint, { action: 'pair', origin: window.location.origin }, { timeout: 15000, signal: controller.signal })
|
||||
const origin = pairingPageOrigin(window.location.origin, await desktopApiBase())
|
||||
const result = await post<{ data: { pairing_link: string } }>(endpoint, { action: 'pair', origin }, { timeout: 15000, signal: controller.signal })
|
||||
if (!alive) return
|
||||
pairing.value = result.data.pairing_link; pairExpires = Date.now() + 5 * 60 * 1000
|
||||
clearTimeout(expiry); expiry = setTimeout(clearPairing, 5 * 60 * 1000)
|
||||
|
|
|
|||
|
|
@ -2,7 +2,11 @@ package session
|
|||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/browserskill"
|
||||
|
|
@ -10,6 +14,115 @@ import (
|
|||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// pairingOrigin chooses the WebSocket host the extension will dial.
|
||||
// A loopback API listener always wins, so a Lite page cannot point the
|
||||
// extension at another host. A public page origin is kept only when its
|
||||
// hostname is the request host; the port still comes from that page so a
|
||||
// reverse proxy can preserve the external port.
|
||||
func pairingOrigin(r *http.Request, page string) string {
|
||||
host := ""
|
||||
if r != nil {
|
||||
host = r.Host
|
||||
}
|
||||
if isLoopbackHostname(requestHostname(host)) {
|
||||
if origin, ok := loopbackPairingOrigin(host); ok {
|
||||
return origin
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if origin, ok := pageOriginMatchingHost(page, host); ok {
|
||||
return origin
|
||||
}
|
||||
if isHTTPOrigin(page) {
|
||||
if origin := requestHTTPOrigin(r); origin != "" {
|
||||
return origin
|
||||
}
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
func requestHostname(host string) string {
|
||||
if parsed, _, err := net.SplitHostPort(host); err == nil {
|
||||
return parsed
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func isLoopbackHostname(hostname string) bool {
|
||||
switch strings.ToLower(hostname) {
|
||||
case "localhost", "127.0.0.1", "::1":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func loopbackPairingOrigin(host string) (string, bool) {
|
||||
host = strings.TrimSpace(host)
|
||||
if host == "" || strings.ContainsAny(host, " \t\r\n/@\\") {
|
||||
return "", false
|
||||
}
|
||||
hostname, port := host, ""
|
||||
if parsed, parsedPort, err := net.SplitHostPort(host); err == nil {
|
||||
hostname, port = parsed, parsedPort
|
||||
}
|
||||
if port != "" {
|
||||
n, err := strconv.Atoi(port)
|
||||
if err != nil || n < 1 || n > 65535 || strconv.Itoa(n) != port {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
switch strings.ToLower(hostname) {
|
||||
case "localhost", "127.0.0.1":
|
||||
if port == "" {
|
||||
return "http://" + hostname, true
|
||||
}
|
||||
return "http://" + hostname + ":" + port, true
|
||||
case "::1":
|
||||
if port == "" {
|
||||
return "http://[::1]", true
|
||||
}
|
||||
return "http://[::1]:" + port, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func pageOriginMatchingHost(page, requestHost string) (string, bool) {
|
||||
u, err := url.Parse(page)
|
||||
if err != nil || u.User != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
|
||||
return "", false
|
||||
}
|
||||
reqName := requestHostname(requestHost)
|
||||
if reqName == "" || !strings.EqualFold(u.Hostname(), reqName) {
|
||||
return "", false
|
||||
}
|
||||
return u.Scheme + "://" + u.Host, true
|
||||
}
|
||||
|
||||
func isHTTPOrigin(page string) bool {
|
||||
u, err := url.Parse(page)
|
||||
return err == nil && u.Host != "" && (u.Scheme == "http" || u.Scheme == "https")
|
||||
}
|
||||
|
||||
func requestHTTPOrigin(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
host := strings.TrimSpace(r.Host)
|
||||
if host == "" || strings.ContainsAny(host, " \t\r\n/@\\") {
|
||||
return ""
|
||||
}
|
||||
if _, err := url.ParseRequestURI("http://" + host + "/"); err != nil {
|
||||
return ""
|
||||
}
|
||||
scheme := "http"
|
||||
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
|
||||
scheme = "https"
|
||||
}
|
||||
return scheme + "://" + host
|
||||
}
|
||||
|
||||
func browserSkillScope(ctx context.Context) browserskill.Scope {
|
||||
tenant, _ := types.TenantIDFromContext(ctx)
|
||||
user, _ := types.UserIDFromContext(ctx)
|
||||
|
|
@ -120,7 +233,7 @@ func (h *Handler) BrowserSkillAccount(c *gin.Context) {
|
|||
}
|
||||
switch input.Action {
|
||||
case "pair":
|
||||
link, err := h.browserSkill.Pair(ctx, scope, input.Origin)
|
||||
link, err := h.browserSkill.Pair(ctx, scope, pairingOrigin(c.Request, input.Origin))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||
return
|
||||
|
|
|
|||
|
|
@ -33,6 +33,31 @@ func TestBrowserAccountStatusDoesNotRequireConversation(t *testing.T) {
|
|||
require.False(t, payload.Data.Connected)
|
||||
}
|
||||
|
||||
func TestPairingOriginUsesLoopbackListenerForWailsPage(t *testing.T) {
|
||||
req := httptest.NewRequest("POST", "http://127.0.0.1:53124/api/v1/me/browser", nil)
|
||||
req.Host = "127.0.0.1:53124"
|
||||
require.Equal(t, "http://127.0.0.1:53124", pairingOrigin(req, "wails://wails.localhost"))
|
||||
|
||||
req.Host = "[::1]:8080"
|
||||
require.Equal(t, "http://[::1]:8080", pairingOrigin(req, "wails://wails.localhost"))
|
||||
|
||||
req.Host = "weknora.example"
|
||||
require.Equal(t, "wails://wails.localhost", pairingOrigin(req, "wails://wails.localhost"))
|
||||
require.Equal(t, "https://weknora.example", pairingOrigin(req, "https://weknora.example"))
|
||||
require.Equal(t, "https://weknora.example:8443", pairingOrigin(req, "https://weknora.example:8443"))
|
||||
}
|
||||
|
||||
func TestPairingOriginIgnoresForeignHostOnLoopback(t *testing.T) {
|
||||
req := httptest.NewRequest("POST", "http://127.0.0.1:53124/api/v1/me/browser", nil)
|
||||
req.Host = "127.0.0.1:53124"
|
||||
require.Equal(t, "http://127.0.0.1:53124", pairingOrigin(req, "https://evil.example"))
|
||||
require.Equal(t, "http://127.0.0.1:53124", pairingOrigin(req, "http://127.0.0.1:9"))
|
||||
|
||||
req.Host = "weknora.example"
|
||||
require.NotEqual(t, "https://evil.example", pairingOrigin(req, "https://evil.example"))
|
||||
require.Equal(t, "http://weknora.example", pairingOrigin(req, "https://evil.example"))
|
||||
}
|
||||
|
||||
func TestBrowserAccountRequiresUser(t *testing.T) {
|
||||
h := &Handler{browserSkill: browserskill.NewManager()}
|
||||
response := httptest.NewRecorder()
|
||||
|
|
|
|||
Loading…
Reference in New Issue