fix(kb): 保存 API Key 时落来源审计
- 修订历史新增 source_address/source_origin:操作人、时间、环境之外, 再记录客户端地址与控制台来源,明文录入事后可追溯。 - 来源只用于取证,不参与放行;最近一跳代理追加的 X-Forwarded-For 才可信, 直连请求不能用伪造链改地址;解析不出就留空,绝不猜值。 - 截断按 UTF-8 边界收口,避免恶意 Origin 让整条保存变成存储错误。 - 迁移 083 只追加列,回滚只删这两列。
This commit is contained in:
@@ -3,7 +3,9 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -86,6 +88,7 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
||||
return
|
||||
}
|
||||
input.SourceAddress, input.SourceOrigin = requestAuditSource(r)
|
||||
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
@@ -114,3 +117,43 @@ func writeKBBindingError(w http.ResponseWriter, err error) {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
|
||||
}
|
||||
}
|
||||
|
||||
// requestAuditSource records the two facts the save audit needs: which console
|
||||
// origin the admin used and the client address behind it. Audit only — nothing
|
||||
// here decides whether a key may be typed or saved.
|
||||
//
|
||||
// The nearest proxy appends its peer to the END of X-Forwarded-For, so that hop
|
||||
// is the trustworthy one; earlier entries are whatever the browser sent. A
|
||||
// forwarded chain is honoured only when the direct peer is private/loopback
|
||||
// (the deployment's own nginx), so a request that reaches the API directly
|
||||
// cannot launder its address through a forged header.
|
||||
func requestAuditSource(r *http.Request) (address, origin string) {
|
||||
peer := r.RemoteAddr
|
||||
if host, _, err := net.SplitHostPort(peer); err == nil {
|
||||
peer = host
|
||||
}
|
||||
ip := net.ParseIP(strings.Trim(peer, "[]"))
|
||||
if ip != nil {
|
||||
address = ip.String()
|
||||
if ip.IsLoopback() || ip.IsPrivate() {
|
||||
hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
|
||||
if last := net.ParseIP(strings.TrimSpace(hops[len(hops)-1])); last != nil {
|
||||
address = last.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if parsed, err := url.Parse(strings.TrimSpace(r.Header.Get("Origin"))); err == nil &&
|
||||
(parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" {
|
||||
origin = parsed.Scheme + "://" + parsed.Host
|
||||
return address, origin
|
||||
}
|
||||
if r.Host != "" {
|
||||
scheme := "http"
|
||||
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
|
||||
scheme = "https"
|
||||
}
|
||||
origin = scheme + "://" + r.Host
|
||||
}
|
||||
return address, origin
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user