feat: add tenant-scoped audit query API
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/audit"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
||||
)
|
||||
|
||||
const listAuditTurnsSQL = `SELECT
|
||||
t.id,t.created_at,t.channel,t.status,
|
||||
COALESCE(c.conversation_type,''),COALESCE(c.title,''),
|
||||
COALESCE(a.external_actor_id,''),COALESCE(rm.actor_name_snapshot,''),
|
||||
LEFT(t.question,200),LEFT(t.answer,200),
|
||||
CASE WHEN jsonb_typeof(t.references_json)='array' THEN jsonb_array_length(t.references_json) ELSE 0 END,
|
||||
COALESCE(am.status,''),COALESCE(am.delivery_method,'')
|
||||
FROM turns t
|
||||
LEFT JOIN messages rm ON rm.id=t.request_message_id AND rm.tenant_key=t.tenant_key AND rm.channel=t.channel
|
||||
LEFT JOIN messages am ON am.id=t.answer_message_id AND am.tenant_key=t.tenant_key AND am.channel=t.channel
|
||||
LEFT JOIN channel_conversations c ON c.id=rm.conversation_id AND c.tenant_key=t.tenant_key AND c.channel=t.channel
|
||||
LEFT JOIN channel_actors a ON a.id=rm.actor_id AND a.tenant_key=t.tenant_key AND a.channel=t.channel
|
||||
WHERE t.tenant_key=$1
|
||||
AND ($2='' OR t.channel=$2)
|
||||
AND ($3='' OR t.status=$3)
|
||||
AND ($4::timestamptz IS NULL OR (t.created_at,t.id)<($4,$5))
|
||||
ORDER BY t.created_at DESC,t.id DESC
|
||||
LIMIT $6`
|
||||
|
||||
const getAuditTurnSQL = `SELECT
|
||||
t.id,t.created_at,t.channel,t.status,
|
||||
COALESCE(c.conversation_type,''),COALESCE(c.title,''),
|
||||
COALESCE(a.external_actor_id,''),COALESCE(rm.actor_name_snapshot,''),
|
||||
t.question,t.answer,t.references_json,t.media_json,
|
||||
COALESCE(rm.id,''),COALESCE(rm.direction,''),COALESCE(rm.role,''),COALESCE(rm.message_type,''),COALESCE(rm.status,''),COALESCE(rm.actor_name_snapshot,''),rm.created_at,
|
||||
COALESCE(am.id,''),COALESCE(am.direction,''),COALESCE(am.role,''),COALESCE(am.message_type,''),COALESCE(am.status,''),am.created_at,am.delivered_at,COALESCE(am.delivery_method,''),COALESCE(am.failure_code,'')
|
||||
FROM turns t
|
||||
LEFT JOIN messages rm ON rm.id=t.request_message_id AND rm.tenant_key=t.tenant_key AND rm.channel=t.channel
|
||||
LEFT JOIN messages am ON am.id=t.answer_message_id AND am.tenant_key=t.tenant_key AND am.channel=t.channel
|
||||
LEFT JOIN channel_conversations c ON c.id=rm.conversation_id AND c.tenant_key=t.tenant_key AND c.channel=t.channel
|
||||
LEFT JOIN channel_actors a ON a.id=rm.actor_id AND a.tenant_key=t.tenant_key AND a.channel=t.channel
|
||||
WHERE t.tenant_key=$1 AND t.id=$2`
|
||||
|
||||
func (s *Store) ListTurns(ctx context.Context, tenantKey string, query audit.ListQuery) ([]audit.TurnSummary, error) {
|
||||
var before any
|
||||
if query.BeforeCreatedAt != nil {
|
||||
before = *query.BeforeCreatedAt
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, listAuditTurnsSQL, tenantKey, query.Channel, string(query.Status), before, query.BeforeID, query.Limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list audit turns: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]audit.TurnSummary, 0)
|
||||
for rows.Next() {
|
||||
var item audit.TurnSummary
|
||||
var status string
|
||||
if err := rows.Scan(
|
||||
&item.ID, &item.CreatedAt, &item.Channel, &status,
|
||||
&item.ConversationType, &item.ConversationTitle,
|
||||
&item.ActorExternalID, &item.ActorDisplayName,
|
||||
&item.QuestionSummary, &item.AnswerSummary, &item.ReferenceCount,
|
||||
&item.AnswerDeliveryStatus, &item.AnswerDeliveryMethod,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan audit turn summary: %w", err)
|
||||
}
|
||||
item.Status = audit.TurnStatus(status)
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate audit turns: %w", err)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetTurn(ctx context.Context, tenantKey, turnID string) (audit.TurnDetail, error) {
|
||||
var detail audit.TurnDetail
|
||||
var status string
|
||||
var referencesJSON, mediaJSON []byte
|
||||
var request audit.MessageMeta
|
||||
var answer audit.MessageMeta
|
||||
var requestCreated, answerCreated, deliveredAt *time.Time
|
||||
err := s.pool.QueryRow(ctx, getAuditTurnSQL, tenantKey, turnID).Scan(
|
||||
&detail.ID, &detail.CreatedAt, &detail.Channel, &status,
|
||||
&detail.ConversationType, &detail.ConversationTitle,
|
||||
&detail.ActorExternalID, &detail.ActorDisplayName,
|
||||
&detail.Question, &detail.Answer, &referencesJSON, &mediaJSON,
|
||||
&request.ID, &request.Direction, &request.Role, &request.MessageType, &request.Status, &request.ActorName, &requestCreated,
|
||||
&answer.ID, &answer.Direction, &answer.Role, &answer.MessageType, &answer.Status, &answerCreated, &deliveredAt, &answer.DeliveryMethod, &answer.FailureCode,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return audit.TurnDetail{}, audit.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return audit.TurnDetail{}, fmt.Errorf("get audit turn: %w", err)
|
||||
}
|
||||
detail.Status = audit.TurnStatus(status)
|
||||
|
||||
var references []core.Reference
|
||||
if len(referencesJSON) > 0 {
|
||||
if err := json.Unmarshal(referencesJSON, &references); err != nil {
|
||||
return audit.TurnDetail{}, fmt.Errorf("decode audit references: %w", err)
|
||||
}
|
||||
}
|
||||
detail.References = safeAuditReferences(references)
|
||||
detail.ReferenceCount = len(detail.References)
|
||||
|
||||
var media []core.MediaAudit
|
||||
if len(mediaJSON) > 0 {
|
||||
if err := json.Unmarshal(mediaJSON, &media); err != nil {
|
||||
return audit.TurnDetail{}, fmt.Errorf("decode audit media: %w", err)
|
||||
}
|
||||
}
|
||||
detail.Media = safeAuditMedia(media)
|
||||
|
||||
if request.ID != "" {
|
||||
if requestCreated != nil {
|
||||
request.CreatedAt = *requestCreated
|
||||
}
|
||||
detail.RequestMessage = &request
|
||||
}
|
||||
if answer.ID != "" {
|
||||
if answerCreated != nil {
|
||||
answer.CreatedAt = *answerCreated
|
||||
}
|
||||
answer.DeliveredAt = deliveredAt
|
||||
detail.AnswerMessage = &answer
|
||||
detail.AnswerDeliveryStatus = answer.Status
|
||||
detail.AnswerDeliveryMethod = answer.DeliveryMethod
|
||||
}
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
func safeAuditReferences(references []core.Reference) []audit.SafeReference {
|
||||
if len(references) == 0 {
|
||||
return nil
|
||||
}
|
||||
safe := make([]audit.SafeReference, 0, len(references))
|
||||
for _, reference := range references {
|
||||
safe = append(safe, audit.SafeReference{
|
||||
ID: reference.ID, KnowledgeID: reference.KnowledgeID,
|
||||
KnowledgeTitle: reference.KnowledgeTitle, Score: reference.Score,
|
||||
})
|
||||
}
|
||||
return safe
|
||||
}
|
||||
|
||||
func safeAuditMedia(media []core.MediaAudit) []audit.SafeMedia {
|
||||
if len(media) == 0 {
|
||||
return nil
|
||||
}
|
||||
safe := make([]audit.SafeMedia, 0, len(media))
|
||||
for _, item := range media {
|
||||
safe = append(safe, audit.SafeMedia{
|
||||
Type: item.Type, MIMEType: item.MIMEType, SizeBytes: item.SizeBytes,
|
||||
Width: item.Width, Height: item.Height,
|
||||
})
|
||||
}
|
||||
return safe
|
||||
}
|
||||
|
||||
var _ audit.TurnRepository = (*Store)(nil)
|
||||
@@ -0,0 +1,75 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
||||
)
|
||||
|
||||
func TestAuditListSQLTenantSafeAndKeyset(t *testing.T) {
|
||||
sql := strings.ToUpper(listAuditTurnsSQL)
|
||||
for _, want := range []string{
|
||||
"FROM TURNS T", "T.TENANT_KEY=$1", "RM.TENANT_KEY=T.TENANT_KEY", "RM.CHANNEL=T.CHANNEL",
|
||||
"AM.TENANT_KEY=T.TENANT_KEY", "AM.CHANNEL=T.CHANNEL",
|
||||
"C.TENANT_KEY=T.TENANT_KEY", "C.CHANNEL=T.CHANNEL",
|
||||
"A.TENANT_KEY=T.TENANT_KEY", "A.CHANNEL=T.CHANNEL",
|
||||
"(T.CREATED_AT,T.ID)<($4,$5)", "ORDER BY T.CREATED_AT DESC,T.ID DESC", "LIMIT $6",
|
||||
} {
|
||||
if !strings.Contains(sql, want) {
|
||||
t.Errorf("list audit SQL missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditListSQLHandlesHistoricalJSONNullReferences(t *testing.T) {
|
||||
sql := strings.ToUpper(listAuditTurnsSQL)
|
||||
if !strings.Contains(sql, "CASE WHEN JSONB_TYPEOF(T.REFERENCES_JSON)='ARRAY'") ||
|
||||
!strings.Contains(sql, "THEN JSONB_ARRAY_LENGTH(T.REFERENCES_JSON) ELSE 0 END") {
|
||||
t.Fatal("list audit SQL must not call jsonb_array_length on historical JSON null/scalars")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditDetailSQLTenantSafeAndExcludesForbiddenData(t *testing.T) {
|
||||
sql := strings.ToUpper(getAuditTurnSQL)
|
||||
for _, want := range []string{
|
||||
"T.TENANT_KEY=$1", "T.ID=$2", "RM.TENANT_KEY=T.TENANT_KEY", "AM.TENANT_KEY=T.TENANT_KEY",
|
||||
"C.TENANT_KEY=T.TENANT_KEY", "A.TENANT_KEY=T.TENANT_KEY",
|
||||
} {
|
||||
if !strings.Contains(sql, want) {
|
||||
t.Errorf("detail audit SQL missing %q", want)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{"ERROR_MESSAGE", "WEKNORA_SESSION_ID", "WEKNORA_REQUEST_ID", "PROVIDER_MESSAGE_ID", "SAFE_METADATA_JSON"} {
|
||||
if strings.Contains(sql, forbidden) {
|
||||
t.Errorf("detail audit SQL must not select forbidden %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeAuditReferencesDropContentAndRaw(t *testing.T) {
|
||||
references := []core.Reference{{
|
||||
ID: "ref-1", KnowledgeID: "kb-1", KnowledgeTitle: "Manual", Score: 0.9,
|
||||
Content: "private chunk body", Raw: json.RawMessage(`{"private":"payload"}`),
|
||||
}}
|
||||
safe := safeAuditReferences(references)
|
||||
if len(safe) != 1 || safe[0].ID != "ref-1" || safe[0].KnowledgeID != "kb-1" || safe[0].KnowledgeTitle != "Manual" || safe[0].Score != 0.9 {
|
||||
t.Fatalf("safe references=%+v", safe)
|
||||
}
|
||||
raw, err := json.Marshal(safe)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := string(raw)
|
||||
if strings.Contains(body, "private chunk") || strings.Contains(body, "payload") || strings.Contains(strings.ToLower(body), "content") || strings.Contains(strings.ToLower(body), "raw") {
|
||||
t.Fatalf("safe references leaked forbidden data: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeAuditMediaCopiesMetadataOnly(t *testing.T) {
|
||||
media := safeAuditMedia([]core.MediaAudit{{Type: "image", MIMEType: "image/png", SizeBytes: 42, Width: 10, Height: 20}})
|
||||
if len(media) != 1 || media[0].Type != "image" || media[0].MIMEType != "image/png" || media[0].SizeBytes != 42 || media[0].Width != 10 || media[0].Height != 20 {
|
||||
t.Fatalf("safe media=%+v", media)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user