package httpapi import ( "net" "net/http" "net/url" "strings" ) // secretTransportAllowed is the strict rule for QA AI model keys: a real TLS // connection, a loopback request, or a same-origin HTTPS request that a trusted // reverse proxy forwarded. The browser's origin scheme must agree, so a // plain-HTTP page behind a misconfigured proxy cannot submit a key even if it // spoofs X-Forwarded-Proto. Knowledge base keys deliberately do not use it. func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool { if r.TLS != nil { return true } if loopbackHost(r.Host) { return true } if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" { origin, err := url.Parse(r.Header.Get("Origin")) return err == nil && origin.Scheme == "https" } return false } // 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() }