fix(phase-6.1): CR 消项——分页锚点、分片鉴权、中断归属
- 任务中心 keyset 锚点取 offset-1(上一页最后一行),修复第 2 页首行永久丢失
- /api/files/chunk/** 纳入必须凭据的写端点,并按解码路径再判一次堵住百分号编码绕过
- /api/tasks/{id}/interrupted 增加归属闸:普通账号只能打断自己名下任务,
内部令牌/管理角色保持原语义;品牌任务经 BrandTaskHeartbeatSpi.findOwnerUserId 比对
- 新增 TaskInterruptOwnershipTest 3 例,守卫测试扩到 6 例
This commit is contained in:
@@ -141,6 +141,9 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
/** 必须解析得出身份才放行的确切写路径(S0-7/AC-8),不受 {@code user-tool-guard-enabled} 豁免。 */
|
||||
private static final String[] CREDENTIALED_WRITE_PATHS = {"/api/files/upload"};
|
||||
|
||||
/** 分片通道前缀:init/part/status/complete/abort 与整包上传同一归属语义,不许留匿名口。 */
|
||||
private static final String FILES_CHUNK_PATH_PREFIX = "/api/files/chunk";
|
||||
|
||||
/** 打断任务这条动作:只收 {@code /api/tasks/{id}/interrupted},不动同前缀的 pull-pending/heartbeat。 */
|
||||
private static final String TASK_PATH_PREFIX = "/api/tasks/";
|
||||
private static final String TASK_INTERRUPTED_SUFFIX = "/interrupted";
|
||||
@@ -355,15 +358,57 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
*/
|
||||
static boolean isCredentialRequiredWriteEndpoint(String uri) {
|
||||
String path = uri == null ? "" : uri;
|
||||
if (matchesCredentialedWrite(path)) {
|
||||
return true;
|
||||
}
|
||||
// getRequestURI() 保留百分号编码,而容器按解码后的路径路由:
|
||||
// /api/files/%75pload 会落回同一条写动作 ⇒ 再按解码路径判一次,堵住编码绕过。
|
||||
String decoded = decodePath(path);
|
||||
return !decoded.equals(path) && matchesCredentialedWrite(decoded);
|
||||
}
|
||||
|
||||
private static boolean matchesCredentialedWrite(String path) {
|
||||
for (String exact : CREDENTIALED_WRITE_PATHS) {
|
||||
if (path.equals(exact)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// 分片通道(AC-17)是新的写面:匿名 init/part/complete 能占临时盘,
|
||||
// complete 还能把匿名数据转存进公开桶,必须与 /api/files/upload 同口径。
|
||||
if (path.equals(FILES_CHUNK_PATH_PREFIX) || path.startsWith(FILES_CHUNK_PATH_PREFIX + "/")) {
|
||||
return true;
|
||||
}
|
||||
return path.startsWith(TASK_PATH_PREFIX) && path.endsWith(TASK_INTERRUPTED_SUFFIX)
|
||||
&& path.length() > TASK_PATH_PREFIX.length() + TASK_INTERRUPTED_SUFFIX.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* 手写百分号解码:只为匹配 ASCII 写端点,畸形编码原样保留(交给容器 400)。
|
||||
* 不用 {@code UriUtils.decode}——它遇到坏序列抛异常,会在守卫里多长一枚 catch。
|
||||
*/
|
||||
private static String decodePath(String path) {
|
||||
if (path == null || path.indexOf('%') < 0) {
|
||||
return path == null ? "" : path;
|
||||
}
|
||||
StringBuilder out = new StringBuilder(path.length());
|
||||
int i = 0;
|
||||
while (i < path.length()) {
|
||||
char c = path.charAt(i);
|
||||
if (c == '%' && i + 2 < path.length()) {
|
||||
int hi = Character.digit(path.charAt(i + 1), 16);
|
||||
int lo = Character.digit(path.charAt(i + 2), 16);
|
||||
if (hi >= 0 && lo >= 0) {
|
||||
out.append((char) ((hi << 4) + lo));
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.append(c);
|
||||
i++;
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** 未强制要求凭据的用户态前缀:只要带了 user_id 参数,归属就得和令牌身份对齐。 */
|
||||
private boolean needsOwnershipBinding(HttpServletRequest request, String uri) {
|
||||
if (!isUserToolPrefix(uri)) {
|
||||
|
||||
+6
@@ -88,6 +88,12 @@ public class BrandCrawlTaskHeartbeatSpi implements BrandTaskHeartbeatSpi {
|
||||
return TaskHeartbeatVo.notAlive(MODULE_BRAND, status, "task is not running");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long findOwnerUserId(Long taskId) {
|
||||
BrandCrawlTaskEntity task = selectTask(taskId);
|
||||
return task == null ? null : task.getUserId();
|
||||
}
|
||||
|
||||
private BrandCrawlTaskEntity selectTask(Long taskId) {
|
||||
LambdaQueryWrapper<BrandCrawlTaskEntity> brandQuery = new LambdaQueryWrapper<BrandCrawlTaskEntity>()
|
||||
.eq(BrandCrawlTaskEntity::getId, taskId)
|
||||
|
||||
+15
-2
@@ -1,6 +1,8 @@
|
||||
package com.nanri.aiimage.modules.task.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
|
||||
import com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo;
|
||||
import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
|
||||
@@ -8,6 +10,7 @@ import com.nanri.aiimage.modules.task.service.TaskHeartbeatService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
@@ -24,6 +27,7 @@ public class TaskHeartbeatController {
|
||||
|
||||
private final TaskHeartbeatService taskHeartbeatService;
|
||||
private final TaskHeartbeatPositionService taskHeartbeatPositionService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@PostMapping("/{taskId}/heartbeat")
|
||||
@Operation(
|
||||
@@ -46,8 +50,17 @@ public class TaskHeartbeatController {
|
||||
public ApiResponse<TaskHeartbeatVo> interrupted(
|
||||
@Parameter(description = "任务 ID", required = true, example = "200")
|
||||
@PathVariable Long taskId,
|
||||
@RequestBody(required = false) TaskHeartbeatRequest request) {
|
||||
@RequestBody(required = false) TaskHeartbeatRequest request,
|
||||
HttpServletRequest httpRequest) {
|
||||
String reason = request == null ? null : request.getPhase();
|
||||
return ApiResponse.success(taskHeartbeatService.markInterrupted(taskId, reason));
|
||||
// 内部令牌(4.0.66 桌面端)与管理角色按原语义放行;普通登录账号只能打断自己名下的任务。
|
||||
Long requesterUid = null;
|
||||
if (!adminAuthSupport.isTrustedInternalToken(httpRequest)) {
|
||||
AdminUserEntity identity = adminAuthSupport.requireUser(httpRequest);
|
||||
if (!adminAuthSupport.mayActForOtherUsers(identity)) {
|
||||
requesterUid = identity.getId();
|
||||
}
|
||||
}
|
||||
return ApiResponse.success(taskHeartbeatService.markInterrupted(taskId, reason, requesterUid));
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
@@ -144,6 +145,17 @@ public class TaskHeartbeatService {
|
||||
* file_task RUNNING → FAILED;brand_crawl_tasks running → cancelled;其余状态不动(幂等)。
|
||||
*/
|
||||
public TaskHeartbeatVo markInterrupted(Long taskId, String reason) {
|
||||
return markInterrupted(taskId, reason, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带请求方归属的中断上报。
|
||||
*
|
||||
* <p>{@code requesterUid} 非空 = 普通登录账号(非管理角色),只能打断自己名下的任务;
|
||||
* 空 = 内部令牌或管理角色,按原语义放行。AC-8 只把门槛从匿名抬到"任意登录账号",
|
||||
* 不补这一层就等于任何用户遍历 taskId 都能把别人的在跑任务置 FAILED。</p>
|
||||
*/
|
||||
public TaskHeartbeatVo markInterrupted(Long taskId, String reason, Long requesterUid) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
log.warn("[task-interrupted] ignored invalid taskId={}", taskId);
|
||||
return TaskHeartbeatVo.notAlive(null, null, "invalid taskId");
|
||||
@@ -153,6 +165,7 @@ public class TaskHeartbeatService {
|
||||
: "客户端异常中断: " + reason.trim();
|
||||
FileTaskEntity fileTask = selectFullFileTask(taskId);
|
||||
if (fileTask != null) {
|
||||
assertInterruptOwnership("file", taskId, fileTask.getUserId(), requesterUid);
|
||||
String status = fileTask.getStatus();
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, taskId)
|
||||
@@ -178,6 +191,7 @@ public class TaskHeartbeatService {
|
||||
syncTerminalState(fileTask, status, fileTask.getErrorMessage());
|
||||
return TaskHeartbeatVo.notAlive(fileTask.getModuleType(), status, "task is not running");
|
||||
}
|
||||
assertInterruptOwnership("brand", taskId, brandTaskHeartbeatSpi.findOwnerUserId(taskId), requesterUid);
|
||||
TaskHeartbeatVo brandResult = brandTaskHeartbeatSpi.markInterrupted(taskId, safeReason);
|
||||
if (brandResult != null) {
|
||||
return brandResult;
|
||||
@@ -186,6 +200,16 @@ public class TaskHeartbeatService {
|
||||
return TaskHeartbeatVo.notAlive(null, null, "task not found");
|
||||
}
|
||||
|
||||
/** 归属闸:只有普通登录账号(requesterUid 非空)且任务有明确归属时才比对。 */
|
||||
private void assertInterruptOwnership(String kind, Long taskId, Long ownerUserId, Long requesterUid) {
|
||||
if (requesterUid == null || ownerUserId == null || requesterUid.equals(ownerUserId)) {
|
||||
return;
|
||||
}
|
||||
log.warn("[task-interrupted] rejected foreign {} task taskId={} requesterUid={} ownerUid={}",
|
||||
kind, taskId, requesterUid, ownerUserId);
|
||||
throw new BusinessException(403, "无权操作该任务");
|
||||
}
|
||||
|
||||
private TaskHeartbeatVo touchFileTaskIfRunning(Long taskId, TaskHeartbeatRequest request) {
|
||||
FileTaskEntity task = selectFileTask(taskId);
|
||||
if (task == null) {
|
||||
|
||||
+9
@@ -22,4 +22,13 @@ public interface BrandTaskHeartbeatSpi {
|
||||
* 客户端重启中断:running/pending → cancelled(条件更新),返回心跳结果;任务不存在返回 null。
|
||||
*/
|
||||
TaskHeartbeatVo markInterrupted(Long taskId, String reason);
|
||||
|
||||
/**
|
||||
* 任务归属用户 id(中断上报的越权闸用);任务不存在返回 null。
|
||||
*
|
||||
* <p>默认 null 表示"查不到归属",调用方只在有明确归属时才拒绝跨用户打断。</p>
|
||||
*/
|
||||
default Long findOwnerUserId(Long taskId) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -137,8 +137,10 @@ public class TaskCenterQueryService {
|
||||
LocalDateTime afterCreatedAt = null;
|
||||
Long afterId = null;
|
||||
if (offset > 0) {
|
||||
// 锚点必须是「上一页最后一行」(offset-1)。取 offset 那一行等于拿本页首行当游标,
|
||||
// 而页查询按 (createdAt,id) 严格小于游标取下一页 ⇒ 第 2 页首行永远不出现。
|
||||
TaskCenterTaskRow anchor = queryMapper.selectTaskPageAnchor(userIds, query.getModuleType(),
|
||||
statuses, query.getShop(), startTime, endTime, offset);
|
||||
statuses, query.getShop(), startTime, endTime, offset - 1);
|
||||
if (anchor == null || anchor.getCreatedAt() == null || anchor.getId() == null) {
|
||||
// 页码落在窗口之外:与旧实现取到空行同样返回空页,不拿 null 游标去要第一页
|
||||
return TaskCenterTaskPageVo.empty(page, pageSize);
|
||||
|
||||
Reference in New Issue
Block a user