kongdeqiang
2026-10-12 ccf1a44c001e233c158bd168dc2d0d96721af929
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package com.custom.webui.controller;
 
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.custom.webui.config.props.RagProperties;
import com.custom.webui.dto.req.RagBindCategoryRequest;
import com.custom.webui.dto.req.RagBindRequest;
import com.custom.webui.dto.req.RagSearchRequest;
import com.custom.webui.dto.resp.RagChunk;
import com.custom.webui.dto.resp.Result;
import com.custom.webui.entity.ChatCollection;
import com.custom.webui.entity.RagCollection;
import com.custom.webui.exception.BusinessException;
import com.custom.webui.entity.ChatCategory;
import com.custom.webui.mapper.ChatCategoryMapper;
import com.custom.webui.mapper.ChatCollectionMapper;
import com.custom.webui.mapper.RagCollectionMapper;
import com.custom.webui.security.CurrentUser;
import com.custom.webui.service.CategoryService;
import com.custom.webui.service.ChatService;
import com.custom.webui.service.FileService;
import com.custom.webui.service.RagProxyService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * RAG 代理接口:把浏览器的 RAG 请求转发给 Python 微服务。
 *
 * <p><b>为什么不让前端直连 Python 服务</b>:
 * <ul>
 *   <li>Python 服务无需实现 JWT 校验,代码更简单(它只信任来自后端的调用)</li>
 *   <li>Python 服务可以只监听内网 / 127.0.0.1,不暴露给浏览器</li>
 *   <li>鉴权、限流、缓存、降级都集中在这一层,便于统一治理</li>
 * </ul>
 */
@Slf4j
@RestController
@RequestMapping("/api/rag")
@RequiredArgsConstructor
public class RagProxyController {
 
    private final RagProxyService ragProxyService;
    private final RagCollectionMapper ragCollectionMapper;
    private final ChatCollectionMapper chatCollectionMapper;
    private final ChatService chatService;
    private final RagProperties ragProperties;
    private final FileService fileService;
    private final CategoryService categoryService;
    private final ChatCategoryMapper chatCategoryMapper;
 
    /**
     * 向量检索。
     *
     * <p>权限校验:只允许检索属于当前用户的集合。
     * 若不校验,攻击者可以传入任意集合名读取他人知识库内容 ——
     * 这是 RAG 系统最典型的越权漏洞。
     */
    @PostMapping("/search")
    public Result<List<RagChunk>> search(@Valid @RequestBody RagSearchRequest request) {
        Long userId = CurrentUser.requireUserId();
 
        List<String> allowed = accessibleCollections(userId);
 
        List<String> target;
        if (request.getCollectionNames() != null && !request.getCollectionNames().isEmpty()) {
            // 指定了集合:与可访问范围求交集,越权的静默剔除
            target = request.getCollectionNames().stream().filter(allowed::contains).toList();
        } else if (request.getChatId() != null) {
            // 未指定集合但给了会话 id:用该会话自己绑定的知识库(含整类展开)。
            // 比退化成「用户全部知识库」更符合直觉 —— 用户绑了什么就只检索什么。
            target = collectionsBoundToChat(request.getChatId(), userId).stream()
                    .filter(allowed::contains).toList();
        } else {
            target = allowed;
        }
 
        if (target.isEmpty()) {
            // 没有可用知识库时不算错误,返回空结果即可,前端提示「未命中」更友好
            log.debug("用户 {} 在会话 {} 上没有可检索的集合", userId, request.getChatId());
            return Result.success(List.of());
        }
 
        log.debug("RAG 检索范围: 会话={} 集合数={} 来源={}", request.getChatId(), target.size(),
                request.getCollectionNames() != null && !request.getCollectionNames().isEmpty()
                        ? "请求指定" : request.getChatId() != null ? "会话绑定" : "用户全部");
 
        int topK = request.getTopK() != null ? request.getTopK() : ragProperties.getDefaultTopK();
        return Result.success(ragProxyService.search(request.getQuery(), target, topK));
    }
 
    /** 把知识库集合绑定到会话,聊天时才会参与检索 */
    @PostMapping("/bind")
    @Transactional(rollbackFor = Exception.class)
    public Result<List<String>> bind(@Valid @RequestBody RagBindRequest request) {
        Long userId = CurrentUser.requireUserId();
        chatService.requireOwnedChat(userId, request.getChatId());
 
        List<String> allowed = accessibleCollections(userId);
 
        // 只保留当前确实可访问的集合,其余**静默剔除**并记日志。
        //
        // 早期实现是对不可访问的集合直接抛 403,但那样会造成一个无法自行
        // 恢复的死结:绑定是全量覆盖语义,前端的 boundCollections 里只要
        // 残留一个已失效的集合名(文档被删了、被管理员取消了全局标记等),
        // 之后每一次绑定都会把它一并提交 → 每次都 403 → 而这条坏绑定
        // 永远不会被清掉。用户看到的是「无权选择知识库集合」,
        // 但真实原因与权限无关,纯粹是引用了已不存在的集合,极难自行排查。
        //
        // 改为「过滤 + 告知」:真正越权的集合不会生效(安全边界不变),
        // 同时返回实际绑定的列表,让前端得以自我修复。
        List<String> accepted = new ArrayList<>();
        List<String> rejected = new ArrayList<>();
        for (String collection : request.getCollectionNames()) {
            if (collection == null || collection.isBlank()) {
                continue;
            }
            if (allowed.contains(collection)) {
                if (!accepted.contains(collection)) {
                    accepted.add(collection);
                }
            } else {
                rejected.add(collection);
            }
        }
        if (!rejected.isEmpty()) {
            log.warn("会话 {} 绑定请求中有 {} 个集合不可访问,已忽略: {}(通常是文档被删除,"
                            + "或管理员取消了全局标记;这不是权限错误)",
                    request.getChatId(), rejected.size(), rejected);
        }
 
        // 全量覆盖语义:accepted 就是该会话最终要挂载的集合列表
        chatCollectionMapper.delete(
                Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, request.getChatId()));
        for (String collection : accepted) {
            ChatCollection entity = new ChatCollection();
            entity.setChatId(request.getChatId());
            entity.setCollectionName(collection);
            entity.setCreatedAt(LocalDateTime.now());
            chatCollectionMapper.insert(entity);
        }
 
        log.info("会话 {} 绑定知识库 {} 个: {}(忽略 {} 个)", request.getChatId(),
                accepted.size(), accepted, rejected.size());
        return Result.success(accepted);
    }
 
    /** 查询会话已绑定的知识库集合 */
    @GetMapping("/bind/{chatId}")
    public Result<List<String>> listBindings(@PathVariable Long chatId) {
        chatService.requireOwnedChat(CurrentUser.requireUserId(), chatId);
        List<String> collections = chatCollectionMapper.selectList(
                        Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
                .stream().map(ChatCollection::getCollectionName).toList();
        return Result.success(collections);
    }
 
    /**
     * 整类绑定:把一个知识库分类挂到会话上。
     *
     * <p>与 {@code /bind} 的区别:这里存的是**分类 id**,检索时才展开成集合。
     * 好处是之后往分类里新增文档,已有会话自动能检索到 ——
     * 若在绑定时就把集合名写死,新文档永远进不了这个会话。
     *
     * @param bind true 绑定,false 解绑
     */
    @PostMapping("/bind-category")
    @Transactional(rollbackFor = Exception.class)
    public Result<List<Long>> bindCategory(@Valid @RequestBody RagBindCategoryRequest request) {
        Long userId = CurrentUser.requireUserId();
        chatService.requireOwnedChat(userId, request.getChatId());
 
        // 可见性校验放在 CategoryService 里(自己的 + 全局的),
        // 越权分类会被拒绝
        if (Boolean.TRUE.equals(request.getBind())) {
            categoryService.requireVisibleForUser(userId, request.getCategoryId());
            Long exists = chatCategoryMapper.selectCount(
                    Wrappers.<ChatCategory>lambdaQuery()
                            .eq(ChatCategory::getChatId, request.getChatId())
                            .eq(ChatCategory::getCategoryId, request.getCategoryId()));
            if (exists == null || exists == 0) {
                ChatCategory entity = new ChatCategory();
                entity.setChatId(request.getChatId());
                entity.setCategoryId(request.getCategoryId());
                entity.setCreatedAt(LocalDateTime.now());
                chatCategoryMapper.insert(entity);
            }
        } else {
            chatCategoryMapper.delete(
                    Wrappers.<ChatCategory>lambdaQuery()
                            .eq(ChatCategory::getChatId, request.getChatId())
                            .eq(ChatCategory::getCategoryId, request.getCategoryId()));
        }
 
        List<Long> bound = chatCategoryMapper.selectList(
                        Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, request.getChatId()))
                .stream().map(ChatCategory::getCategoryId).toList();
        log.info("会话 {} {} 分类 {},当前绑定分类: {}",
                request.getChatId(), Boolean.TRUE.equals(request.getBind()) ? "绑定" : "解绑",
                request.getCategoryId(), bound);
        return Result.success(bound);
    }
 
    /** 查询会话已绑定的分类 id 列表 */
    @GetMapping("/bind-category/{chatId}")
    public Result<List<Long>> listCategoryBindings(@PathVariable Long chatId) {
        chatService.requireOwnedChat(CurrentUser.requireUserId(), chatId);
        return Result.success(chatCategoryMapper.selectList(
                        Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, chatId))
                .stream().map(ChatCategory::getCategoryId).toList());
    }
 
    /** 解除会话的全部知识库绑定(含整类绑定) */
    @DeleteMapping("/bind/{chatId}")
    public Result<Void> unbind(@PathVariable Long chatId) {
        chatService.requireOwnedChat(CurrentUser.requireUserId(), chatId);
        chatCollectionMapper.delete(
                Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId));
        chatCategoryMapper.delete(
                Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, chatId));
        return Result.success();
    }
 
    /**
     * RAG 服务健康状态,供前端在设置页展示「知识库服务:正常/不可用」。
     */
    @GetMapping("/health")
    public Result<Map<String, Object>> health() {
        Map<String, Object> status = new HashMap<>();
        status.put("enabled", ragProperties.isEnabled());
        status.put("baseUrl", ragProperties.getBaseUrl());
        status.put("available", ragProxyService.isHealthy());
        status.put("ownedCollections", accessibleCollections(CurrentUser.requireUserId()));
        return Result.success(status);
    }
 
    /**
     * 取某会话已绑定的集合:单篇绑定 ∪ 整类绑定展开。
     *
     * <p>与 {@code MessageServiceImpl.buildContext()} 里的展开逻辑保持一致 ——
     * 那边是聊天主链路,这里是检索接口,两处必须用同一套规则,
     * 否则会出现「聊天能检索到、手动检索检索不到」这种诡异现象。
     */
    private List<String> collectionsBoundToChat(Long chatId, Long userId) {
        chatService.requireOwnedChat(userId, chatId);
 
        List<String> result = new ArrayList<>(chatCollectionMapper.selectList(
                        Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
                .stream().map(ChatCollection::getCollectionName).toList());
 
        List<Long> categoryIds = chatCategoryMapper.selectList(
                        Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, chatId))
                .stream().map(ChatCategory::getCategoryId).toList();
        if (!categoryIds.isEmpty()) {
            for (Long categoryId : categoryIds) {
                for (String name : categoryService.collectionsOfCategory(userId, categoryId)) {
                    if (!result.contains(name)) {
                        result.add(name);
                    }
                }
            }
        }
        return result;
    }
 
    /**
     * 当前用户**可检索**的全部集合名 = 自己入库的 + 全部已入库的全局知识库。
     *
     * <p>这是知识库权限的唯一判定入口:检索、绑定、健康检查都走它,
     * 保证「全局文件人人可用、私有文件互不可见」。
     * 具体实现放在 FileService,避免权限逻辑散落在多个 Controller 里。
     */
    private List<String> accessibleCollections(Long userId) {
        return fileService.accessibleCollections(userId);
    }
}