Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ npm run build
- [代码阅读路线](docs/05-code-reading-roadmap.md)
- [HTTP API 契约](docs/06-api-contract.md)
- [前端 API 接入清单](docs/09-frontend-api-integration.md)
- [Nexus 工单接入验收](docs/17-nexus-ticket-acceptance.md)
- [Redis 接入计划](docs/10-redis-integration-plan.md)
- [Playwright 与 Flyway 验证](docs/11-playwright-flyway-verification.md)
- [Docker 与配置分层指南](docs/12-docker-configuration-guide.md)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,24 @@ public Result<TicketResponse> get(@PathVariable @Positive Long id) {
public Result<IPage<TicketResponse>> page(@Valid @ModelAttribute TicketPageQuery query) {
return Result.success(ticketService.pageTickets(query).convert(TicketConverter::toResponse));
}
@GetMapping("/external-queue")
@PreAuthorize("hasAuthority('ticket:claim') and hasAnyAuthority('ticket:read', 'ticket:read:department')")
public Result<IPage<TicketResponse>> externalQueue(
@RequestParam(defaultValue = "1") @Positive int pageNum,
@RequestParam(defaultValue = "10") @Positive @jakarta.validation.constraints.Max(50) int pageSize,
@RequestParam(defaultValue = "false") boolean mine) {
return Result.success(ticketService.pageExternalQueue(pageNum, pageSize, mine).convert(TicketConverter::toResponse));
}

@PostMapping("/{id}/claim")
@PreAuthorize("hasAuthority('ticket:claim') and hasAnyAuthority('ticket:read', 'ticket:read:department')")
public Result<TicketResponse> claim(@PathVariable @Positive Long id, @Valid @RequestBody ClaimRequest request) {
return Result.success(TicketConverter.toResponse(ticketService.claimExternalTicket(id, request.version())));
}

public record ClaimRequest(@jakarta.validation.constraints.NotNull
@jakarta.validation.constraints.PositiveOrZero Integer version) {}

/**
* 将工单分派或重新分派给目标部门和可选处理人。
*
Expand Down
1 change: 1 addition & 0 deletions demo/src/main/java/com/example/demo/entity/Ticket.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public class Ticket {

private Long handlingDepartmentId;

@TableField(updateStrategy = FieldStrategy.ALWAYS)
private Long currentAssigneeId;

private LocalDateTime firstResponseAt;
Expand Down
2 changes: 2 additions & 0 deletions demo/src/main/java/com/example/demo/entity/UserAccount.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ public class UserAccount {
/** ACTIVE、LOCKED、DISABLED。 */
private String status;

private String accountKind;

/** 仅在认证成功后更新。 */
private LocalDateTime lastLoginAt;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.example.demo.integration;

import jakarta.validation.Validator;
import jakarta.validation.constraints.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant;
import java.util.Set;
import java.util.UUID;

@RestController
@RequestMapping("/integration/v1/tickets")
class ExternalTicketController {
private static final Set<String> FIELDS = Set.of("schemaVersion", "eventId", "externalTicketId",
"title", "description", "submittedAt", "applicationId");

private final ExternalTicketService service;
private final ObjectMapper json;
private final Validator validator;

ExternalTicketController(ExternalTicketService service, ObjectMapper json, Validator validator) {
this.service = service;
this.json = json;
this.validator = validator;
}

@PostMapping
ResponseEntity<Ack> ingest(@AuthenticationPrincipal TicketIntegration integration, @RequestBody JsonNode body,
@RequestParam MultiValueMap<String, String> query) {
if (!body.isObject() || !query.isEmpty()) return ResponseEntity.badRequest().build();
var fields = body.fieldNames();
while (fields.hasNext()) {
if (!FIELDS.contains(fields.next())) return ResponseEntity.badRequest().build();
}
Request request;
try {
request = json.treeToValue(body, Request.class);
} catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException invalid) {
return ResponseEntity.badRequest().build();
}
if (!validator.validate(request).isEmpty()) return ResponseEntity.badRequest().build();
var result = service.importTicket(integration, request);
return ResponseEntity.status(result.created() ? HttpStatus.CREATED : HttpStatus.OK).body(result.ack());
}

@ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class)
ResponseEntity<Void> invalidJson() {
return ResponseEntity.badRequest().build();
}

@com.fasterxml.jackson.annotation.JsonPropertyOrder({"schemaVersion", "eventId", "externalTicketId",
"title", "description", "submittedAt", "applicationId"})
record Request(@Min(1) @Max(1) int schemaVersion, @NotNull UUID eventId, @NotNull UUID externalTicketId,
@NotBlank @Size(max = 200) String title,
@NotBlank @Size(max = 8000) String description,
@NotNull Instant submittedAt, @Positive Long applicationId) {}

record Ack(UUID eventId, UUID externalTicketId, String flowOpsTicketId, String ticketNo) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package com.example.demo.integration;

import com.example.demo.common.BusinessException;
import com.example.demo.dto.ticket.TicketCreateRequest;
import com.example.demo.service.TicketService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import java.security.MessageDigest;
import java.util.Objects;

@Service
class ExternalTicketService {
private final JdbcTemplate jdbc;
private final TicketService tickets;
private final ObjectMapper json;
private final TransactionTemplate transaction;

ExternalTicketService(JdbcTemplate jdbc, TicketService tickets, ObjectMapper json,
PlatformTransactionManager transactions) {
this.jdbc = jdbc;
this.tickets = tickets;
this.json = json;
transaction = new TransactionTemplate(transactions);
transaction.setIsolationLevel(org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED);
}

Result importTicket(TicketIntegration integration, ExternalTicketController.Request request) {
byte[] digest = digest(request);
try {
return Objects.requireNonNull(transaction.execute(status -> {
Result prior = lookup(integration, request, digest);
if (prior != null) return prior;

jdbc.update("""
INSERT INTO external_ticket_link
(tenant_id, integration_id, external_ticket_id, event_id, request_digest)
VALUES (?, ?, ?, ?, ?)
""", integration.tenantId(), integration.id(), request.externalTicketId().toString(),
request.eventId().toString(), digest);

var input = new TicketCreateRequest();
input.setTitle(request.title());
input.setDescription(request.description());
input.setHandlingDepartmentId(integration.departmentId());
input.setPriority(integration.priority());
input.setTicketType("CUSTOMER_ISSUE");
var ticket = tickets.createExternalTicket(integration.tenantId(), integration.actorId(), input);
int linked = jdbc.update("""
UPDATE external_ticket_link SET ticket_id = ?
WHERE tenant_id = ? AND integration_id = ? AND external_ticket_id = ?
""", ticket.getId(), integration.tenantId(), integration.id(), request.externalTicketId().toString());
if (linked != 1) throw new IllegalStateException("外部工单关联写入失败");
return new Result(true, ack(request, ticket.getId(), ticket.getTicketNo()));
}));
} catch (DuplicateKeyException conflict) {
Result prior = lookup(integration, request, digest);
if (prior != null) return prior;
throw conflict;
} catch (BusinessException failure) {
if (failure.getCode() == 30002) {
throw new BusinessException(50001, "FlowOps 工单创建发生并发冲突,请重试");
}
throw failure;
}
}

private Result lookup(TicketIntegration integration, ExternalTicketController.Request request, byte[] digest) {
return jdbc.query("""
SELECT l.external_ticket_id, l.event_id, l.request_digest, l.ticket_id, t.ticket_no
FROM external_ticket_link l JOIN ticket t ON t.id = l.ticket_id AND t.tenant_id = l.tenant_id
WHERE l.tenant_id = ? AND l.integration_id = ?
AND (l.external_ticket_id = ? OR l.event_id = ?)
""", rs -> {
if (!rs.next()) return null;
if (!request.externalTicketId().toString().equals(rs.getString("external_ticket_id"))
|| !request.eventId().toString().equals(rs.getString("event_id"))
|| !MessageDigest.isEqual(digest, rs.getBytes("request_digest"))) {
throw new BusinessException(30015, "外部工单标识与既有事件冲突");
}
return new Result(false, ack(request, rs.getLong("ticket_id"), rs.getString("ticket_no")));
}, integration.tenantId(), integration.id(), request.externalTicketId().toString(), request.eventId().toString());
}

private byte[] digest(ExternalTicketController.Request request) {
try {
return TicketIntegrationSecurity.sha256(json.writeValueAsBytes(request));
} catch (com.fasterxml.jackson.core.JsonProcessingException error) {
throw new IllegalStateException("外部工单摘要生成失败", error);
}
}

private static ExternalTicketController.Ack ack(ExternalTicketController.Request request, long id, String number) {
return new ExternalTicketController.Ack(request.eventId(), request.externalTicketId(), Long.toString(id), number);
}

record Result(boolean created, ExternalTicketController.Ack ack) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package com.example.demo.integration;

record TicketIntegration(String id, long tenantId, long departmentId, long actorId, String priority) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package com.example.demo.integration;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.regex.Pattern;

@Configuration
class TicketIntegrationSecurity {
private static final String INGEST = "integration:ticket:ingest";
private static final Pattern CREDENTIAL = Pattern.compile("Bearer ([A-Za-z0-9_-]{1,64})\\.([A-Za-z0-9_-]{43})");

@Bean @Order(1)
SecurityFilterChain ticketIntegrationChain(HttpSecurity http, JdbcTemplate jdbc) throws Exception {
return http.securityMatcher("/integration/v1/**")
.csrf(AbstractHttpConfigurer::disable)
.requestCache(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(errors -> errors.authenticationEntryPoint((req, res, ex) -> res.setStatus(401)))
.authorizeHttpRequests(auth -> auth.requestMatchers(HttpMethod.POST, "/integration/v1/tickets")
.hasAuthority(INGEST).anyRequest().denyAll())
.addFilterBefore(new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
authenticate(jdbc, request.getHeader("Authorization"));
chain.doFilter(request, response);
}
}, AnonymousAuthenticationFilter.class)
.build();
}

private static void authenticate(JdbcTemplate jdbc, String header) {
if (header == null || header.length() > 115) return;
var match = CREDENTIAL.matcher(header);
if (!match.matches()) return;
byte[] suppliedDigest = sha256(match.group(2).getBytes(StandardCharsets.US_ASCII));
jdbc.query("""
SELECT i.id, i.tenant_id, i.department_id, i.actor_id, i.priority, k.secret_digest
FROM ticket_integration_key k JOIN ticket_integration i ON i.id = k.integration_id
JOIN tenant t ON t.id = i.tenant_id
WHERE k.key_id = ? AND k.enabled = TRUE AND i.enabled = TRUE AND t.status = 'ACTIVE'
""", rs -> {
if (rs.next() && MessageDigest.isEqual(suppliedDigest, rs.getBytes("secret_digest"))) {
var principal = new TicketIntegration(rs.getString("id"), rs.getLong("tenant_id"),
rs.getLong("department_id"), rs.getLong("actor_id"), rs.getString("priority"));
var context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(UsernamePasswordAuthenticationToken.authenticated(principal, null,
List.of(new SimpleGrantedAuthority(INGEST))));
SecurityContextHolder.setContext(context);
}
return null;
}, match.group(1));
}

static byte[] sha256(byte[] bytes) {
try {
return MessageDigest.getInstance("SHA-256").digest(bytes);
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException(impossible);
}
}
}
22 changes: 21 additions & 1 deletion demo/src/main/java/com/example/demo/mapper/TicketMapper.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.Ticket;
import org.apache.ibatis.annotations.Mapper;
@Mapper public interface TicketMapper extends BaseMapper<Ticket> { }
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface TicketMapper extends BaseMapper<Ticket> {
@Select("SELECT EXISTS(SELECT 1 FROM external_ticket_link WHERE tenant_id = #{tenant} AND ticket_id = #{ticket})")
boolean isExternal(@Param("tenant") long tenantId, @Param("ticket") long ticketId);

@Select("""
SELECT COUNT(DISTINCT CASE WHEN p.permission_code IN ('ticket:read', 'ticket:read:department')
THEN 'read' ELSE 'claim' END) = 2
FROM user_role ur
JOIN role r ON r.id = ur.role_id AND r.tenant_id = ur.tenant_id AND r.status = 'ACTIVE'
JOIN role_permission rp ON rp.role_id = r.id AND rp.tenant_id = r.tenant_id
JOIN permission p ON p.id = rp.permission_id AND p.status = 'ACTIVE'
WHERE ur.tenant_id = #{tenant} AND ur.user_id = #{user}
AND p.permission_code IN ('ticket:claim', 'ticket:read', 'ticket:read:department')
""")
boolean canClaim(@Param("tenant") long tenantId, @Param("user") long userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
public interface TicketService extends IService<Ticket> {
/** @param request 创建数据。@return 新建工单。 */
Ticket createTicket(TicketCreateRequest request);
Ticket createExternalTicket(Long tenantId, Long actorId, TicketCreateRequest request);
Page<Ticket> pageExternalQueue(int pageNum, int pageSize, boolean mine);
Ticket claimExternalTicket(Long ticketId, Integer version);
/** @param tenantId 租户 ID。@param ticketId 工单 ID。@return 指定租户中的工单。 */
Ticket getTicket(Long tenantId, Long ticketId);
/** @param query 分页及筛选条件。@return 当前用户范围内的工单分页结果。 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public LoginResponse login(LoginRequest request) {
UserAccount user = userAccountMapper.selectOne(Wrappers.lambdaQuery(UserAccount.class)
.eq(UserAccount::getTenantId, tenant.getId())
.eq(UserAccount::getUsername, username));
if (user == null || !"ACTIVE".equals(user.getStatus())
if (user == null || !"ACTIVE".equals(user.getStatus()) || "MACHINE".equals(user.getAccountKind())
|| !passwordEncoder.matches(request.password(), user.getPasswordHash())) {
throw invalidCredentials();
}
Expand Down
Loading
Loading