feat(reconciliation): 实现导入对账后端
为什么:T6a 需要一张批次/差异表、全量只读扫描、R1-R8 判定和 finding 级处置;现有解析监控只转述台账状态,无法回答库内是否一致。 做什么:迁移 000084(upload_md5、runs/findings/actions、共享 removal_candidates 视图);WeKnora 字段与 1000/页扫描;runtime 只读客户端(0400 Key、503 降级);扫描/矩阵/动作/定时/僵死回收;9 条接口与 RBAC;overview 队列与删两张常量卡。 边界:只对测试库;对账零写请求;R1/R2 单条确认;R6 复用 /removal;R2 只管理员;生产链路未改。 验证:make verify 全绿(17 项);新增矩阵/扫描 R1-R8/零写/失败整批/动作/运行时/密钥权限测试。
This commit is contained in:
@@ -429,8 +429,11 @@ func validPathSegment(value string) bool {
|
||||
return strings.TrimSpace(value) != "" && !strings.ContainsAny(value, "/?#\\\x00")
|
||||
}
|
||||
|
||||
// validPage accepts the upstream maximum (1000). Listings that need a smaller
|
||||
// window still pass it explicitly; upload recovery keeps its own 100/page
|
||||
// budget instead of inheriting the reconciliation scan size.
|
||||
func validPage(page, pageSize int) bool {
|
||||
return page > 0 && pageSize > 0 && pageSize <= 100
|
||||
return page > 0 && pageSize > 0 && pageSize <= 1000
|
||||
}
|
||||
|
||||
func (c *Client) endpoint(path string) string {
|
||||
@@ -487,3 +490,14 @@ func (c *Client) decodeBody(resp *http.Response, target any) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// StatusCode returns the HTTP status carried by err, or 0.
|
||||
func StatusCode(err error) int {
|
||||
var httpErr *HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
return httpErr.StatusCode
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func IsNotFound(err error) bool { return StatusCode(err) == http.StatusNotFound }
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
package weknora
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RuntimeClient is the platform-level, read-only SystemAdmin client. It is a
|
||||
// separate key from the tenant API key on purpose: capability
|
||||
// system_runtime_read belongs to the test instance, not to one tenant.
|
||||
type RuntimeClientConfig struct {
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Timeout time.Duration
|
||||
MaxResponseBytes int64
|
||||
AllowDockerHTTP bool
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
type RuntimeClient struct {
|
||||
baseURL *url.URL
|
||||
apiKey string
|
||||
httpClient *http.Client
|
||||
maxResponseBytes int64
|
||||
}
|
||||
|
||||
func NewRuntimeClient(config RuntimeClientConfig) (*RuntimeClient, error) {
|
||||
baseURL, err := url.Parse(strings.TrimSpace(config.BaseURL))
|
||||
if err != nil || baseURL.Scheme == "" || baseURL.Host == "" || baseURL.User != nil ||
|
||||
baseURL.RawQuery != "" || baseURL.Fragment != "" {
|
||||
return nil, errors.New("invalid WeKnora runtime base URL")
|
||||
}
|
||||
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
|
||||
return nil, errors.New("WeKnora runtime base URL must use HTTPS")
|
||||
}
|
||||
if strings.TrimSpace(config.APIKey) == "" {
|
||||
return nil, errors.New("WeKnora runtime API key is required")
|
||||
}
|
||||
if config.Timeout <= 0 {
|
||||
return nil, errors.New("WeKnora runtime HTTP timeout must be positive")
|
||||
}
|
||||
if config.MaxResponseBytes <= 0 {
|
||||
config.MaxResponseBytes = defaultMaxResponseBytes
|
||||
}
|
||||
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
|
||||
return &RuntimeClient{
|
||||
baseURL: baseURL,
|
||||
apiKey: config.APIKey,
|
||||
httpClient: &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
},
|
||||
maxResponseBytes: config.MaxResponseBytes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type RuntimeQueues struct {
|
||||
Available bool `json:"available"`
|
||||
QueuesError bool `json:"queues_error"`
|
||||
WorkersError bool `json:"workers_error"`
|
||||
Queues []RuntimeQueue `json:"queues"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
}
|
||||
|
||||
type RuntimeQueue struct {
|
||||
Name string `json:"name"`
|
||||
Pool string `json:"pool"`
|
||||
Pending int `json:"pending"`
|
||||
Active int `json:"active"`
|
||||
Scheduled int `json:"scheduled"`
|
||||
Retry int `json:"retry"`
|
||||
Archived int `json:"archived"`
|
||||
Processed int `json:"processed"`
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
|
||||
type RuntimeDocumentProgress struct {
|
||||
Document RuntimeDocument `json:"document"`
|
||||
Failures []RuntimeFailure `json:"failures"`
|
||||
HasMoreFailures bool `json:"has_more_failures"`
|
||||
}
|
||||
|
||||
type RuntimeDocument struct {
|
||||
ID string `json:"id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Title string `json:"title"`
|
||||
ParseStatus string `json:"parse_status"`
|
||||
IngestionStatus string `json:"ingestion_status"`
|
||||
WikiStatus string `json:"wiki_status"`
|
||||
Stages []RuntimeStage `json:"stages"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RuntimeStage struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
type RuntimeFailure struct {
|
||||
TaskType string `json:"task_type"`
|
||||
FailCount int `json:"fail_count"`
|
||||
FailedAt time.Time `json:"failed_at"`
|
||||
LastError string `json:"last_error"`
|
||||
}
|
||||
|
||||
func (c *RuntimeClient) Queues(ctx context.Context) (RuntimeQueues, error) {
|
||||
var response RuntimeQueues
|
||||
if err := c.get(ctx, "/api/v1/system/admin/runtime/queues", &response); err != nil {
|
||||
return RuntimeQueues{}, err
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (c *RuntimeClient) DocumentProgress(ctx context.Context, knowledgeID string) (RuntimeDocumentProgress, error) {
|
||||
if !validPathSegment(knowledgeID) || len(knowledgeID) > 64 {
|
||||
return RuntimeDocumentProgress{}, errors.New("invalid knowledge ID")
|
||||
}
|
||||
var envelope struct {
|
||||
Success bool `json:"success"`
|
||||
Data RuntimeDocumentProgress `json:"data"`
|
||||
}
|
||||
if err := c.get(ctx, "/api/v1/system/admin/runtime/documents/"+knowledgeID, &envelope); err != nil {
|
||||
return RuntimeDocumentProgress{}, err
|
||||
}
|
||||
if !envelope.Success {
|
||||
return RuntimeDocumentProgress{}, errors.New("WeKnora returned an unsuccessful document progress response")
|
||||
}
|
||||
return envelope.Data, nil
|
||||
}
|
||||
|
||||
func (c *RuntimeClient) get(ctx context.Context, path string, target any) error {
|
||||
endpoint := *c.baseURL
|
||||
endpoint.Path = strings.TrimRight(c.baseURL.Path, "/") + path
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
|
||||
if err != nil {
|
||||
return errors.New("create WeKnora runtime request")
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("X-API-Key", c.apiKey)
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send WeKnora runtime request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return &HTTPError{StatusCode: resp.StatusCode}
|
||||
}
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
|
||||
if err != nil {
|
||||
return errors.New("read WeKnora runtime response")
|
||||
}
|
||||
if int64(len(payload)) > c.maxResponseBytes {
|
||||
return errors.New("WeKnora runtime response exceeds size limit")
|
||||
}
|
||||
if err := json.Unmarshal(payload, target); err != nil {
|
||||
return errors.New("decode WeKnora runtime response")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -47,3 +47,42 @@ func ReadAPIKeyFile(path string) (string, error) {
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ReadRuntimeKeyFile reads the platform-level read-only key. Q7 fixes the
|
||||
// contract at mode 0400: unlike tenant keys (0600), this key must not be
|
||||
// readable by the process owner's group and never leaves the API process.
|
||||
func ReadRuntimeKeyFile(path string) (string, error) {
|
||||
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open runtime key file: %w", err)
|
||||
}
|
||||
file := os.NewFile(uintptr(fd), "weknora-runtime-key")
|
||||
if file == nil {
|
||||
_ = syscall.Close(fd)
|
||||
return "", errors.New("open runtime key file: invalid file descriptor")
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("inspect runtime key file: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", errors.New("runtime key file must be a regular file")
|
||||
}
|
||||
if info.Mode().Perm() != 0o400 {
|
||||
return "", errors.New("runtime key file permissions must be 0400")
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(file, maxAPIKeyFileBytes+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read runtime key file: %w", err)
|
||||
}
|
||||
if len(body) > maxAPIKeyFileBytes {
|
||||
return "", errors.New("runtime key file is too large")
|
||||
}
|
||||
key := strings.TrimSpace(string(body))
|
||||
if key == "" {
|
||||
return "", errors.New("runtime key file is empty")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
@@ -53,3 +53,20 @@ func TestReadAPIKeyFileRejectsUnsafeInputsWithoutLeakingContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadRuntimeKeyFileRequires0400(t *testing.T) {
|
||||
path := t.TempDir() + "/runtime-key"
|
||||
if err := os.WriteFile(path, []byte("runtime-secret\n"), 0o400); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, err := ReadRuntimeKeyFile(path)
|
||||
if err != nil || key != "runtime-secret" {
|
||||
t.Fatalf("key=%q err=%v", key, err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ReadRuntimeKeyFile(path); err == nil {
|
||||
t.Fatal("0600 runtime key must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,17 @@ type UploadRequest struct {
|
||||
|
||||
type Knowledge struct {
|
||||
ID string `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Title string `json:"title"`
|
||||
Source string `json:"source"`
|
||||
Channel string `json:"channel"`
|
||||
ParseStatus string `json:"parse_status"`
|
||||
StallState string `json:"stall_state"`
|
||||
EnableStatus string `json:"enable_status"`
|
||||
FileName string `json:"file_name"`
|
||||
FileType string `json:"file_type"`
|
||||
FolderPath string `json:"folder_path"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
FileHash string `json:"file_hash"`
|
||||
Metadata map[string]any `json:"metadata"`
|
||||
|
||||
Reference in New Issue
Block a user