fix(kb-bindings): allow key entry on private HTTP consoles
build / build (push) Successful in 2m26s

- Accept the private-console transport with an exact Origin/Host match; the http console is not a secure context, so Chrome sends no Sec-Fetch-Site and that requirement made every real write 400.
- Reject bracketed non-IPv6 host spellings, including ported forms, instead of normalising them to loopback.
- Show the plaintext-warning copy or the disabled state from a tri-state capability field; old APIs keep the legacy message.
- Document WEKNORA_ALLOW_PRIVATE_HTTP in .env.example and the operations runbook.
This commit is contained in:
狐友 GXXP & Miku
2026-11-24 10:29:33 +08:00
committed by 姚章浩
parent 660320d646
commit 8c84c9c601
13 changed files with 470 additions and 22 deletions
+7 -1
View File
@@ -34,7 +34,13 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
for _, view := range views {
storageReady = storageReady || view.StorageReady
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}})
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"environments": views,
"storage_ready": storageReady,
// The page cannot test the server's transport rule from the browser URL
// alone (a TLS proxy and an untrusted proxy look identical there).
"secret_entry_allowed": consoleSecretEntryAllowed(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP),
}})
}
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
+93
View File
@@ -128,3 +128,96 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
}
}
}
func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
for _, tc := range []struct {
name string
host string
allow bool
want bool
}{
{name: "private console with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private console without toggle", host: "172.29.151.11:28188", want: false},
{name: "loopback console", host: "127.0.0.1:8080", want: true},
} {
t.Run(tc.name, func(t *testing.T) {
config := kbBindingHandler(t, store)
config.WeKnoraAllowPrivateHTTP = tc.allow
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
request.Host = tc.host
response := httptest.NewRecorder()
config.handleKBBindings(response, request)
if response.Code != http.StatusOK {
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
}
var payload struct {
Data struct {
SecretEntryAllowed bool `json:"secret_entry_allowed"`
} `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.SecretEntryAllowed != tc.want {
t.Fatalf("secret_entry_allowed = %v, want %v", payload.Data.SecretEntryAllowed, tc.want)
}
})
}
}
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) {
const (
privateHost = "172.29.151.11:28188"
origin = "http://172.29.151.11:28188"
)
store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
}
body := `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
save := func(config *Config) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPut, "http://"+privateHost+"/api/v1/kb-bindings/test", bytes.NewBufferString(body))
request.Host = privateHost
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingSave(response, request)
return response
}
catalog := func(config *Config) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPost, "http://"+privateHost+"/api/v1/kb-bindings/test/catalog",
bytes.NewBufferString(`{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`))
request.Host = privateHost
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
return response
}
enabled := kbBindingHandler(t, store)
enabled.WeKnoraAllowPrivateHTTP = true
if response := save(enabled); response.Code != http.StatusOK {
t.Fatalf("save with toggle status=%d body=%s", response.Code, response.Body.String())
}
if store.lastSave.APIKey != "typed-key" {
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
}
if response := catalog(enabled); response.Code != http.StatusOK {
t.Fatalf("catalog with toggle status=%d body=%s", response.Code, response.Body.String())
}
disabled := kbBindingHandler(t, store)
if response := save(disabled); response.Code != http.StatusBadRequest {
t.Fatalf("save without toggle status=%d body=%s", response.Code, response.Body.String())
}
if response := catalog(disabled); response.Code != http.StatusBadRequest {
t.Fatalf("catalog without toggle status=%d body=%s", response.Code, response.Body.String())
}
}
+71 -14
View File
@@ -16,14 +16,7 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
if r.TLS != nil {
return true
}
host := r.Host
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
host = parsedHost
}
if strings.EqualFold(host, "localhost") {
return true
}
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
if loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
@@ -36,12 +29,14 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
// fetch from the operator console itself when it is served over plain http on a
// private address. That is the only non-TLS shape this deployment needs, and it
// still requires an exact Origin/Host match.
// still requires an exact Origin/Host match. It deliberately does not require
// Sec-Fetch-Site: Chrome only sends Sec-Fetch-* from secure contexts, so an
// http console on a private address never carries that header.
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if secretTransportAllowed(r, trustTLSProxy) {
return true
}
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
if !allowPrivateHTTP {
return false
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
@@ -53,8 +48,70 @@ func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, all
return false
}
host := parsed.Hostname()
if ip := net.ParseIP(host); ip != nil {
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
}
return strings.EqualFold(host, "localhost")
return privateAddressHost(host)
}
// consoleSecretEntryAllowed mirrors the transports the write gates accept, but
// it cannot simply call secretTransportAllowed: that gate guards a write and
// therefore insists on a same-origin Origin header, which a GET navigation
// never sends. Trusting X-Forwarded-Proto alone on a read is safe because
// browsers cannot set it and the deployment already declares the proxy
// trusted; a forged header still cannot make the write gate accept anything.
func consoleSecretEntryAllowed(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if r.TLS != nil || loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" {
return true
}
return allowPrivateHTTP && privateAddressHost(r.Host)
}
// requestHostname strips the optional port and IPv6 brackets. Brackets come
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
// ported forms are not address spellings the server or a browser ever emits,
// so they stay untouched and keep failing the address checks.
func requestHostname(host string) string {
host = strings.TrimSpace(host)
if strings.HasPrefix(host, "[") {
end := strings.Index(host, "]")
if end <= 0 {
return host
}
ip := net.ParseIP(host[1:end])
if ip == nil || ip.To4() != nil {
return host
}
if rest := host[end+1:]; rest != "" && (rest[0] != ':' || rest == ":" || strings.Trim(rest[1:], "0123456789") != "") {
return host
}
return ip.String()
}
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
return parsedHost
}
return host
}
// loopbackHost is the address-only part of the secret transport rule: a
// request from this machine never crosses a network.
func loopbackHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
// privateAddressHost accepts loopback and private addresses. Names other than
// localhost are rejected because the deployment toggle is about addresses,
// not about trusting whatever DNS resolves to.
func privateAddressHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && (ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast())
}
+112
View File
@@ -0,0 +1,112 @@
package httpapi
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
)
func TestConsoleSecretEntryAllowedMatrix(t *testing.T) {
cases := []struct {
name string
host string
tls bool
xfp string
trust bool
allow bool
want bool
}{
{name: "direct TLS", host: "console.example", tls: true, want: true},
{name: "loopback name", host: "localhost:8080", want: true},
{name: "loopback v4", host: "127.0.0.1:8080", want: true},
{name: "loopback v6 with port", host: "[::1]:8080", want: true},
{name: "loopback v6 without port", host: "[::1]", want: true},
// Bracketed non-IPv6 hosts are not address spellings; they must not
// borrow loopback trust from the bracket stripper.
{name: "bracketed v4 is not loopback", host: "[127.0.0.1]", want: false},
{name: "bracketed localhost is not loopback", host: "[localhost]", want: false},
{name: "bracketed v4 with toggle is not private", host: "[127.0.0.1]", allow: true, want: false},
{name: "private address with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private address without toggle", host: "172.29.151.11:28188", want: false},
{name: "link-local with toggle", host: "169.254.10.7:8080", allow: true, want: true},
{name: "public address with toggle", host: "203.0.113.10:8080", allow: true, want: false},
{name: "public name with toggle", host: "console.example", allow: true, want: false},
{name: "trusted proxy https", host: "console.example", xfp: "https", trust: true, want: true},
{name: "untrusted proxy https", host: "console.example", xfp: "https", want: false},
{name: "trusted proxy reports http", host: "console.example", xfp: "http", trust: true, want: false},
// A forged header must not beat the address rule when the proxy is not trusted.
{name: "untrusted proxy on private host", host: "172.29.151.11:28188", xfp: "https", want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://placeholder/api/v1/kb-bindings", nil)
request.Host = tc.host
if tc.tls {
request.TLS = &tls.ConnectionState{}
}
if tc.xfp != "" {
request.Header.Set("X-Forwarded-Proto", tc.xfp)
}
if got := consoleSecretEntryAllowed(request, tc.trust, tc.allow); got != tc.want {
t.Fatalf("consoleSecretEntryAllowed = %v, want %v", got, tc.want)
}
})
}
}
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = "[::1]"
if !secretTransportAllowed(request, false) {
t.Fatal("bare [::1] Host was rejected as a loopback transport")
}
request.Host = "console.example"
if secretTransportAllowed(request, false) {
t.Fatal("public name without TLS was accepted")
}
}
// Plain-http consoles are not secure contexts, so Chrome never sends
// Sec-Fetch-* with their fetches. A matching Origin is the whole contract.
func TestSecretTransportPrivateConsoleNeedsOriginNotSecFetch(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test/catalog", nil)
request.Host = "192.168.50.134:18093"
request.Header.Set("Origin", "http://192.168.50.134:18093")
if !secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("same-origin private console without Sec-Fetch-Site was rejected")
}
request.Header.Set("Origin", "http://evil.example")
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("cross-origin request was accepted as a private console")
}
request.Header.Set("Origin", "http://192.168.50.134:18093")
if secretTransportAllowedForPrivateConsole(request, false, false) {
t.Fatal("private console was accepted with the deployment toggle off")
}
}
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", "http://"+host)
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatalf("Host %q was accepted as a private console", host)
}
}
}
func TestSecretTransportRejectsMalformedIPv6Suffixes(t *testing.T) {
for _, host := range []string{"[::1]junk", "[::1]:", "[::1]:abc"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
}
}