Browse Source

feat(huawei): 华为Health Kit订阅回调端点 POST /healthkit/notifications(连通性测试返回204, 可选Secret验签HMAC-SHA256+Base64, 真实通知仅记日志待后续业务处理) + TDD 8例

Xiaogang Liao 2 days ago
parent
commit
667be0fe94

+ 74 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/huawei/HealthKitNotificationController.java

@@ -0,0 +1,74 @@
+package com.etotem.cfc.controller.huawei;
+
+import com.etotem.cfc.service.huawei.HuaweiSubscriberSignature;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.Map;
+
+/**
+ * 华为 Health Kit 订阅通知回调端点(spec 2026-11-23)。
+ *
+ * <p>路径固定为 {@code /healthkit/notifications}(华为要求全小写结尾),不在 {@code /api/} 前缀下,
+ * 故不经过 JWT 拦截(华为服务器无法携带我方 token)。连通性测试 Huawei 发
+ * {@code CONNECTION_VERIFY_EVENT$VERIFY} 通知,本端点返回 204 即视为连通成功。</p>
+ *
+ * <p>验签策略(可选):配置了 subscriber Secret 时校验 {@code x-notification-signature}
+ *(HMAC-SHA256 + Base64),验签失败返回 404;未配置 Secret 时跳过验签(便于先跑通连通性)。</p>
+ *
+ * <p>本次只回 204 + 记日志,真实通知的业务处理(按 openId 拉取数据)后续排期。</p>
+ */
+@Slf4j
+@RestController
+public class HealthKitNotificationController {
+
+    /** 华为开发者联盟订阅者卡片的 Base64 Secret;为空则跳过验签。 */
+    @Value("${huawei.health.subscriber-secret:}")
+    private String subscriberSecret;
+
+    @PostMapping("/healthkit/notifications")
+    public ResponseEntity<Void> notifications(
+            @RequestBody(required = false) Map<String, Object> body,
+            @RequestHeader(value = "x-notification-signature", required = false) String signature) {
+        String openId = body == null ? null : str(body.get("openId"));
+        String eventType = body == null ? null : str(body.get("eventType"));
+        String eventTime = body == null ? null : str(body.get("eventTime"));
+
+        boolean accepted = shouldAccept(subscriberSecret, signature, openId, eventType, eventTime);
+        if (!accepted) {
+            log.warn("[healthkit] 订阅通知验签失败, 拒绝: eventType={}, openId={}", eventType, openId);
+            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
+        }
+
+        if (isConnectionVerify(eventType)) {
+            log.info("[healthkit] 连通性测试通知通过: eventType={}, openId={}", eventType, openId);
+        } else {
+            // 业务处理(按 openId 定位成员并拉取数据)后续排期;本次仅记录
+            log.info("[healthkit] 收到订阅通知(待业务处理): eventType={}, openId={}, eventTime={}, metaData={}",
+                    eventType, openId, eventTime, body == null ? null : body.get("metaData"));
+        }
+        return ResponseEntity.noContent().build(); // 204
+    }
+
+    /**
+     * 是否接受该通知:未配置 Secret→跳过验签放行;配置了→验签通过才放行。
+     * 静态便于单测(不依赖 Spring 上下文)。
+     */
+    public static boolean shouldAccept(String secret, String signature,
+                                       String openId, String eventType, String eventTime) {
+        if (secret == null || secret.trim().isEmpty()) return true;
+        return HuaweiSubscriberSignature.verify(secret, openId, eventType, eventTime, signature);
+    }
+
+    /** 是否为连通性测试事件。 */
+    public static boolean isConnectionVerify(String eventType) {
+        return "CONNECTION_VERIFY_EVENT$VERIFY".equals(eventType);
+    }
+
+    private static String str(Object o) {
+        return o == null ? null : String.valueOf(o);
+    }
+}

+ 52 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/huawei/HuaweiSubscriberSignature.java

@@ -0,0 +1,52 @@
+package com.etotem.cfc.service.huawei;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * 华为 Health Kit 订阅通知验签工具。
+ *
+ * <p>签名规则(华为官方文档):x-notification-signature = Base64( HMAC-SHA256( Base64Decode(secret),
+ * openId + "_" + eventType + "_" + eventTime ) )。Secret 来自华为开发者联盟订阅者卡片,
+ * 为 Base64 字符串,需先解码为原始密钥字节。</p>
+ */
+public final class HuaweiSubscriberSignature {
+
+    private HuaweiSubscriberSignature() {
+    }
+
+    /** 用 Base64 编码的 secret 对事件要素签名,返回 Base64 摘要。 */
+    public static String sign(String secretBase64, String openId, String eventType, String eventTime) {
+        if (secretBase64 == null || secretBase64.trim().isEmpty()
+                || openId == null || eventType == null || eventTime == null) {
+            return null;
+        }
+        try {
+            byte[] key = Base64.getDecoder().decode(secretBase64.trim());
+            String data = openId + "_" + eventType + "_" + eventTime;
+            Mac mac = Mac.getInstance("HmacSHA256");
+            mac.init(new SecretKeySpec(key, "HmacSHA256"));
+            byte[] signed = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
+            return Base64.getEncoder().encodeToString(signed);
+        } catch (Exception e) {
+            throw new IllegalStateException("华为订阅通知验签失败", e);
+        }
+    }
+
+    /** 校验签名是否正确(恒定时间比较, secret 为空时返回 false)。 */
+    public static boolean verify(String secretBase64, String openId, String eventType,
+                                 String eventTime, String signature) {
+        if (secretBase64 == null || secretBase64.trim().isEmpty() || signature == null) return false;
+        String expected = sign(secretBase64, openId, eventType, eventTime);
+        return expected != null && constantTimeEquals(expected, signature);
+    }
+
+    private static boolean constantTimeEquals(String a, String b) {
+        if (a.length() != b.length()) return false;
+        int diff = 0;
+        for (int i = 0; i < a.length(); i++) diff |= a.charAt(i) ^ b.charAt(i);
+        return diff == 0;
+    }
+}

+ 48 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/HealthKitNotificationTest.java

@@ -0,0 +1,48 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.controller.huawei.HealthKitNotificationController;
+import com.etotem.cfc.service.huawei.HuaweiSubscriberSignature;
+import org.junit.jupiter.api.Test;
+
+import java.util.Base64;
+import java.nio.charset.StandardCharsets;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * TDD 契约:健康盒订阅通知接入(spec:连通性测试返回204;可选验签)。
+ */
+class HealthKitNotificationTest {
+
+    @Test
+    void no_secret_configured_accepts_any_notification() {
+        // 未配置 Secret → 跳过验签,放行(保证连通性测试能过)
+        assertTrue(HealthKitNotificationController.shouldAccept(null, "any-signature", "open", "E", "1"),
+                "未配 Secret 时应放行");
+        assertTrue(HealthKitNotificationController.shouldAccept("   ", "any-signature", "open", "E", "1"),
+                "Secret 为空白时应放行");
+    }
+
+    @Test
+    void secret_configured_valid_signature_accepted() {
+        String secretB64 = Base64.getEncoder().encodeToString("huawei-sub-secret".getBytes(StandardCharsets.UTF_8));
+        String sig = HuaweiSubscriberSignature.sign(secretB64, "open123", "CONNECTION_VERIFY_EVENT$VERIFY", "1607514090688");
+        assertTrue(HealthKitNotificationController.shouldAccept(secretB64, sig, "open123", "CONNECTION_VERIFY_EVENT$VERIFY", "1607514090688"),
+                "配了 Secret 且签名正确应放行");
+    }
+
+    @Test
+    void secret_configured_invalid_signature_rejected() {
+        String secretB64 = Base64.getEncoder().encodeToString("huawei-sub-secret".getBytes(StandardCharsets.UTF_8));
+        assertFalse(HealthKitNotificationController.shouldAccept(secretB64, "wrong", "open123", "E", "1"),
+                "配了 Secret 但签名错误应拒绝(返回404)");
+        assertFalse(HealthKitNotificationController.shouldAccept(secretB64, null, "open123", "E", "1"),
+                "配了 Secret 但缺签名头应拒绝");
+    }
+
+    @Test
+    void connection_verify_event_is_recognized() {
+        assertTrue(HealthKitNotificationController.isConnectionVerify("CONNECTION_VERIFY_EVENT$VERIFY"));
+        assertFalse(HealthKitNotificationController.isConnectionVerify("ACTIVITY_RECORD_EVENT$UPDATE"));
+    }
+}

+ 62 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/HuaweiSubscriberSignatureTest.java

@@ -0,0 +1,62 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.service.huawei.HuaweiSubscriberSignature;
+import org.junit.jupiter.api.Test;
+
+import java.util.Base64;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.charset.StandardCharsets;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * TDD 契约:华为订阅通知验签(spec Health Kit:HMAC-SHA256(secret, openId_eventType_eventTime),
+ * secret 先 Base64 解码,结果再 Base64 编码)。
+ */
+class HuaweiSubscriberSignatureTest {
+
+    @Test
+    void verify_matches_huawei_sample_algorithm() throws Exception {
+        String secretB64 = Base64.getEncoder().encodeToString("my-huawei-secret".getBytes(StandardCharsets.UTF_8));
+        String openId = "MDFAMTAxNTI0MzcxQGQ";
+        String eventType = "CONNECTION_VERIFY_EVENT$VERIFY";
+        String eventTime = "1607514090688";
+
+        String expected = huaweiReference(secretB64, openId, eventType, eventTime);
+        String actual = HuaweiSubscriberSignature.sign(secretB64, openId, eventType, eventTime);
+
+        assertEquals(expected, actual, "签名算法必须与华为样例一致(Base64解码secret→HmacSHA256→Base64输出)");
+    }
+
+    @Test
+    void verify_valid_signature_returns_true() throws Exception {
+        String secretB64 = Base64.getEncoder().encodeToString("s3cret".getBytes(StandardCharsets.UTF_8));
+        String sig = HuaweiSubscriberSignature.sign(secretB64, "open123", "ACTIVITY_RECORD_EVENT$UPDATE", "999");
+        assertTrue(HuaweiSubscriberSignature.verify(secretB64, "open123", "ACTIVITY_RECORD_EVENT$UPDATE", "999", sig));
+    }
+
+    @Test
+    void verify_wrong_signature_returns_false() throws Exception {
+        String secretB64 = Base64.getEncoder().encodeToString("s3cret".getBytes(StandardCharsets.UTF_8));
+        assertFalse(HuaweiSubscriberSignature.verify(secretB64, "open123", "E", "999", "bogus-signature"));
+    }
+
+    @Test
+    void verify_with_blank_secret_returns_false() {
+        // 空 secret 不参与验签,verify 应返回 false(由调用方决定是否跳过验签)
+        assertFalse(HuaweiSubscriberSignature.verify("", "open", "E", "1", "anything"));
+        assertFalse(HuaweiSubscriberSignature.verify(null, "open", "E", "1", "anything"));
+    }
+
+    /** 华为官方样例算法逐字复刻,作为对照 */
+    private String huaweiReference(String secretB64, String openId, String eventType, String eventTime) throws Exception {
+        StringBuilder str = new StringBuilder();
+        str.append(openId).append("_").append(eventType).append("_").append(eventTime);
+        byte[] bytes = Base64.getDecoder().decode(secretB64);
+        Mac mac = Mac.getInstance("HmacSHA256");
+        mac.init(new SecretKeySpec(bytes, "HmacSHA256"));
+        byte[] signed = mac.doFinal(str.toString().getBytes("utf-8"));
+        return Base64.getEncoder().encodeToString(signed);
+    }
+}