feat(qaops): 接入独立只读问答查询与治理覆盖复检

This commit is contained in:
姚章浩
2026-10-17 09:04:19 +08:00
parent c1d49adb62
commit fd04bf7886
42 changed files with 4479 additions and 5 deletions
+1 -1
View File
@@ -101,7 +101,7 @@ func isAuthEndpoint(method, path string) bool {
func classifyRole(method, path string) string {
// The member roster exposes account identities and roles: admin-only for
// every method, checked before the read shortcut below.
if strings.HasPrefix(path, "/api/v1/users") {
if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") {
return roleAdmin
}
if method == http.MethodGet {
+143
View File
@@ -0,0 +1,143 @@
package httpapi
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"knowledge-governance/internal/dobotaiops"
)
// No raw SQL, source credential, arbitrary tenant or write method crosses this boundary.
type QAOpsReader interface {
ListRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error)
GetRecord(context.Context, string, string) (dobotaiops.Record, error)
Available(context.Context) error
Safety() dobotaiops.SourceSafety
}
func authorizeQAOps(w http.ResponseWriter, r *http.Request) bool {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Pragma", "no-cache")
identity, ok := sessionFrom(r.Context())
if !ok {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "问答运营需要登录后访问"})
return false
}
// Until the employee-data visibility scope is approved, do not widen access
// to all pre-existing viewers/engineers merely because this endpoint is GET.
if identity.Role != roleAdmin {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "尚未配置员工问答可见范围,当前仅管理员可访问"})
return false
}
return true
}
func qaOpsStatus(w http.ResponseWriter, r *http.Request, config Config) {
if !authorizeQAOps(w, r) {
return
}
state := "disabled"
code := "source_not_configured"
warnings := []string{}
if config.QAOpsEnabled {
state = "unavailable"
code = "source_unavailable"
}
if config.QAOpsProblem != "" {
state = "blocked"
code = "source_configuration_invalid"
}
if config.QAOps != nil && config.QAOps.Available(r.Context()) == nil {
state = "connected"
code = ""
safety := config.QAOps.Safety()
if safety.DatabaseTemp {
warnings = append(warnings, "database_temp_enabled")
}
if !safety.SSL {
warnings = append(warnings, "database_transport_unencrypted")
}
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"state": state, "code": code, "warnings": warnings, "read_only": true, "source_version": "2.0", "channel": "dingtalk"}})
}
func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
if !authorizeQAOps(w, r) {
return
}
if config.QAOps == nil || config.QAOpsTenantKey == "" {
qaOpsError(w, dobotaiops.ErrUnavailable)
return
}
values := r.URL.Query()
allowed := map[string]bool{"start": true, "end": true, "keyword": true, "cursor": true, "limit": true}
for key, items := range values {
if !allowed[key] || len(items) != 1 {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
return
}
}
window, err := dobotaiops.NewWindow(config.QAOpsTenantKey, values.Get("start"), values.Get("end"), 90*24*time.Hour, config.Now())
if err != nil {
qaOpsError(w, err)
return
}
limit := 20
if raw := values.Get("limit"); raw != "" {
limit, err = strconv.Atoi(raw)
if err != nil || limit < 1 || limit > 100 {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
return
}
}
page, err := config.QAOps.ListRecords(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword"), Cursor: values.Get("cursor"), Limit: limit})
if err != nil {
qaOpsError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": page})
}
func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) {
if !authorizeQAOps(w, r) {
return
}
if config.QAOps == nil || config.QAOpsTenantKey == "" {
qaOpsError(w, dobotaiops.ErrUnavailable)
return
}
if r.URL.RawQuery != "" {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
return
}
item, err := config.QAOps.GetRecord(r.Context(), config.QAOpsTenantKey, r.PathValue("id"))
if err != nil {
qaOpsError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": item})
}
func qaOpsError(w http.ResponseWriter, err error) {
status := http.StatusServiceUnavailable
code := "source_unavailable"
message := "问答数据源不可用,请检查独立只读连接;原有知识治理功能不受影响"
if errors.Is(err, dobotaiops.ErrInvalidQuery) {
status = http.StatusBadRequest
code = "invalid_query"
message = "查询参数无效:请检查时间范围、关键词长度或重新查询后翻页"
}
if errors.Is(err, dobotaiops.ErrNotReadOnly) {
code = "source_not_read_only"
message = "问答连接权限校验未通过,已阻止读取,请联系管理员"
}
if errors.Is(err, dobotaiops.ErrRecordNotFound) {
status = http.StatusNotFound
code = "record_not_found"
message = "未找到当前授权范围内的问答记录"
}
writeJSON(w, status, map[string]string{"error": message, "code": code})
}
+87
View File
@@ -0,0 +1,87 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/dobotaiops"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type qaOpsSpy struct {
query dobotaiops.RecordQuery
tenant, id string
calls int
err error
}
func (s *qaOpsSpy) ListRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
s.query = q
s.calls++
return dobotaiops.RecordPage{Items: []dobotaiops.Record{}}, s.err
}
func (s *qaOpsSpy) GetRecord(_ context.Context, tenant, id string) (dobotaiops.Record, error) {
s.tenant = tenant
s.id = id
s.calls++
return dobotaiops.Record{}, s.err
}
func (s *qaOpsSpy) Available(context.Context) error { return s.err }
func (s *qaOpsSpy) Safety() dobotaiops.SourceSafety {
return dobotaiops.SourceSafety{DatabaseTemp: true, SSL: false}
}
func TestQAOperationsRequireExplicitSessionAndServerSelectedTenant(t *testing.T) {
spy := &qaOpsSpy{}
auth := newFakeAuthStore()
for token, user := range map[string]string{"admin-qa-fixture": "usr-boss", "viewer-qa-fixture": "usr-eye", "engineer-qa-fixture": "usr-eng"} {
auth.sessions[token] = user
}
handler, err := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsEnabled: true, QAOpsTenantKey: "approved-tenant", Auth: &AuthConfig{Store: auth}})
if err != nil {
t.Fatal(err)
}
base := "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z"
for _, tc := range []struct {
token, path string
status int
}{
{"", base, http.StatusUnauthorized}, {"viewer-qa-fixture", base, http.StatusForbidden}, {"engineer-qa-fixture", base, http.StatusForbidden},
{"admin-qa-fixture", base + "&tenant_key=another-tenant", http.StatusBadRequest},
{"admin-qa-fixture", base + "&limit=0", http.StatusBadRequest},
{"admin-qa-fixture", base + "&keyword=a&keyword=b", http.StatusBadRequest},
{"admin-qa-fixture", base + "&keyword=test", http.StatusOK},
} {
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
if tc.token != "" {
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != tc.status {
t.Fatalf("status=%d want=%d body=%s", response.Code, tc.status, response.Body.String())
}
}
if spy.calls != 1 || spy.query.Window.TenantKey != "approved-tenant" || spy.query.Keyword != "test" {
t.Fatalf("unauthorized/invalid reads reached source: %+v", spy)
}
spy.err = errors.New("sensitive-driver-detail-not-for-browser")
request := httptest.NewRequest(http.MethodGet, base, nil)
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusServiceUnavailable || strings.Contains(response.Body.String(), "sensitive-driver-detail") {
t.Fatalf("source failure leaked or became empty success: %s", response.Body.String())
}
if response.Header().Get("Cache-Control") != "no-store" {
t.Fatal("employee answers must not be cached")
}
unauth, _ := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsTenantKey: "approved-tenant"})
response = httptest.NewRecorder()
unauth.ServeHTTP(response, httptest.NewRequest(http.MethodGet, base, nil))
if response.Code != http.StatusUnauthorized {
t.Fatal("auth-disabled governance must not expose production answers")
}
}
+14
View File
@@ -0,0 +1,14 @@
package httpapi
import (
"net/http"
"testing"
)
func TestQAOperationsRoleGatePrecedesGenericGETShortcut(t *testing.T) {
for _, path := range []string{"/api/v1/qa-ops/status", "/api/v1/qa-ops/records", "/api/v1/qa-ops/records/some-id"} {
if role := classifyRole(http.MethodGet, path); role != roleAdmin {
t.Fatalf("QA employee data route classified as %s, must require admin: %s", role, path)
}
}
}
+28
View File
@@ -0,0 +1,28 @@
package httpapi
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestQAOperationsFailClosedWithoutBreakingGovernance(t *testing.T) {
auth := newFakeAuthStore()
auth.sessions["admin-qa-fixture"] = "usr-boss"
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", nil)
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("unconfigured source must not be an empty list: status=%d body=%s", response.Code, response.Body.String())
}
health := httptest.NewRecorder()
handler.ServeHTTP(health, httptest.NewRequest(http.MethodGet, "/livez", nil))
if health.Code != http.StatusOK {
t.Fatalf("external source must not stop governance liveness: %d", health.Code)
}
}
+13
View File
@@ -101,6 +101,10 @@ type Store interface {
}
type Config struct {
QAOps QAOpsReader
QAOpsTenantKey string
QAOpsEnabled bool
QAOpsProblem string
Store Store
Monitor MonitorProvider
InternalRoutingKnowledgeBaseID string
@@ -167,6 +171,15 @@ func NewHandler(config Config) (http.Handler, error) {
config.NewID = newID
}
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v1/qa-ops/status", func(w http.ResponseWriter, r *http.Request) {
qaOpsStatus(w, r, config)
})
mux.HandleFunc("GET /api/v1/qa-ops/records", func(w http.ResponseWriter, r *http.Request) {
listQAOpsRecords(w, r, config)
})
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}", func(w http.ResponseWriter, r *http.Request) {
getQAOpsRecord(w, r, config)
})
mux.HandleFunc("GET /health", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})