ApiSignTestBase.java 8.5 KB
package com.youjia.sign;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youjia.framework.sign.ApiSignProperties;
import com.youjia.framework.sign.RsaSignUtils;
import com.youjia.framework.sign.SignCanonicalBuilder;
import com.youjia.framework.sign.SignConstants;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.UUID;

/**
 * 接口签名测试基类:模拟「前端」角色完成请求加签与响应验签。
 *
 * <p>与真实前端的唯一区别是:客户端私钥直接读取服务端开发环境生成的
 * {@code keys/client_private.pem}(生产应由前端自行生成、只把公钥给后端);
 * 服务端公钥则和前端一样,通过免签接口 {@code GET /system/sign/public-key} 获取。</p>
 *
 * <p>子类通过 {@code @TestPropertySource} 覆盖 {@code youjia.api-sign.mode}
 * 即可分别验证 STRICT / LENIENT 两种模式。</p>
 *
 * <p>本组用例只关注「签名」本身,因此关闭登录鉴权 {@code youjia.auth.enabled=false},
 * 避免被测业务接口被 10002 拦截;鉴权链路另见 {@code com.youjia.auth.AuthLoginTest}。</p>
 */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("dev")
@TestPropertySource(properties = "youjia.auth.enabled=false")
abstract class ApiSignTestBase {

    /** 默认应用标识,需与配置 youjia.api-sign.app-ids 中的一项一致 */
    protected static final String APP_ID = "youjia-web";

    /** 演示用被测接口:菜单树查询 */
    protected static final String MENU_TREE_PATH = "/system/menu/tree";

    @LocalServerPort
    protected int port;

    @Autowired
    protected TestRestTemplate restTemplate;

    @Autowired
    protected ApiSignProperties signProperties;

    protected final ObjectMapper objectMapper = new ObjectMapper();

    /** 客户端私钥:请求方向加签用(对应前端本地保存的私钥) */
    protected PrivateKey clientPrivateKey;

    /** 服务端公钥:响应方向验签用(由免签接口下发) */
    protected PublicKey serverPublicKey;

    @BeforeEach
    void initKeys() throws Exception {
        Path clientPrivatePath = Paths.get(signProperties.getKeyDirectory(), SignConstants.FILE_CLIENT_PRIVATE);
        clientPrivateKey = RsaSignUtils.parsePrivateKey(Files.readString(clientPrivatePath, StandardCharsets.UTF_8));

        ResponseEntity<byte[]> publicKeyResp =
                restTemplate.exchange("/system/sign/public-key", HttpMethod.GET, HttpEntity.EMPTY, byte[].class);
        JsonNode data = objectMapper.readTree(publicKeyResp.getBody()).path("data");
        serverPublicKey = RsaSignUtils.parsePublicKey(data.path("publicKeyPem").asText());
    }

    /* ==================================================================
     * 请求加签
     * ================================================================== */

    /**
     * 生成一套完整的签名请求头(时间戳取当前时间、nonce 随机)。
     *
     * @param method      GET / POST
     * @param path        请求路径(不含 query)
     * @param query       原始 query 串,可为 null
     * @param contentType 媒体类型,GET 无请求体时传 null
     * @param body        请求体原文,无请求体时传 null
     */
    protected HttpHeaders sign(String method, String path, String query, String contentType, String body) {
        return sign(method, path, query, contentType, body,
                System.currentTimeMillis(), newNonce(), APP_ID);
    }

    /**
     * 生成签名请求头(可自定义时间戳 / nonce / 应用标识,用于构造过期、重放等异常场景)。
     */
    protected HttpHeaders sign(String method, String path, String query, String contentType, String body,
                               long timestamp, String nonce, String appId) {
        String canonical = SignCanonicalBuilder.buildRequestCanonical(
                method.toUpperCase(),
                path,
                SignCanonicalBuilder.sortQuery(query),
                contentType == null ? "" : contentType,
                String.valueOf(timestamp),
                nonce,
                appId,
                body == null ? "" : body);

        HttpHeaders headers = new HttpHeaders();
        headers.set(SignConstants.HEADER_APP_ID, appId);
        headers.set(SignConstants.HEADER_TIMESTAMP, String.valueOf(timestamp));
        headers.set(SignConstants.HEADER_NONCE, nonce);
        headers.set(SignConstants.HEADER_SIGN,
                RsaSignUtils.sign(canonical, clientPrivateKey, signProperties.getAlgorithm()));
        headers.set(SignConstants.HEADER_SIGN_ALGORITHM, signProperties.getAlgorithm());
        if (contentType != null && !contentType.isBlank()) {
            headers.setContentType(MediaType.parseMediaType(contentType));
        }
        return headers;
    }

    protected static String newNonce() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /* ==================================================================
     * 发起请求
     * ================================================================== */

    /** 发起请求并返回原始响应(保留响应体原文,供验签使用) */
    protected ApiResponse call(String method, String path, String query, String body, HttpHeaders headers) {
        String url = path + (query == null || query.isBlank() ? "" : "?" + query);
        HttpEntity<String> entity = new HttpEntity<>(body, headers);
        ResponseEntity<byte[]> response =
                restTemplate.exchange(url, HttpMethod.valueOf(method.toUpperCase()), entity, byte[].class);
        return new ApiResponse(response.getStatusCode().value(),
                response.getBody() == null ? "" : new String(response.getBody(), StandardCharsets.UTF_8),
                response.getHeaders());
    }

    /* ==================================================================
     * 响应验签
     * ================================================================== */

    /**
     * 校验响应签名:原文 = {@code X-Sign-Timestamp \n X-Sign-Nonce \n 响应体原文 \n},
     * 签名值取自响应头 {@code X-Sign},公钥为服务端公钥。
     *
     * @param response 原始响应
     * @param body     参与验签的响应体(正常传 response.body(),篡改场景传被改过的文本)
     */
    protected boolean verifyResponse(ApiResponse response, String body) {
        String sign = response.header(SignConstants.HEADER_SIGN);
        String timestamp = response.header(SignConstants.HEADER_SIGN_TIMESTAMP);
        String nonce = response.header(SignConstants.HEADER_SIGN_NONCE);
        if (sign == null || timestamp == null || nonce == null) {
            return false;
        }
        String canonical = SignCanonicalBuilder.buildResponseCanonical(Long.parseLong(timestamp), nonce, body);
        return RsaSignUtils.verify(canonical, sign, serverPublicKey, signProperties.getAlgorithm());
    }

    /** 解析统一响应体中的业务状态码 */
    protected int codeOf(ApiResponse response) {
        try {
            JsonNode node = objectMapper.readTree(response.body());
            return node.path("code").asInt();
        } catch (Exception e) {
            return -1;
        }
    }

    /** 解析统一响应体中的 data 节点 */
    protected JsonNode dataOf(ApiResponse response) {
        try {
            return objectMapper.readTree(response.body()).path("data");
        } catch (Exception e) {
            return objectMapper.createArrayNode();
        }
    }

    /** 原始响应:HTTP 状态码 + 响应体原文 + 响应头 */
    protected record ApiResponse(int status, String body, HttpHeaders headers) {

        String header(String name) {
            return headers.getFirst(name);
        }
    }
}