Browse Source
按文档实现鉴权第一段: - auth/EdayunTokenClient:POST /oauth/token,body 用 client_id / client_secret (下划线风格照文档),无业务请求头 - http/EdayunRequestFactory:构造 token 请求;另备了业务请求构造(token / appKey / timestamp / sign 四个头)与 sign() = MD5(body + "." + appSecret) - adapter/EdayunAdapter.token(ctx):走 TokenManager 缓存,按 appKey + clientId 维度 - 工厂构造函数接收 TokenStore / LockProvider / Clock,与信仓同构 **文档只给了 code 取值(200/500/503/504),没给响应体结构**,所以做了兼容: 优先 data.access_token + data.expires_in,其次 data.expiry(绝对时刻), 再其次顶层 token;都没有则失败并带出截断的原始报文,不猜。 有效期同样三级兜底,最后按 2 小时(常量里标了「待联调确认」)。 错误分级: - 500 明确失败,不重试 - 503 网关无效 / 504 超时,标记 retryable - HTTP 非 2xx 单独处理,5xx(除 504)可重试 测试 12 个:请求形状、三种响应形态、无 token、500 不可重试、 503/504 可重试、缺 code、非 2xx、凭据缺失不发请求、MD5 签名(独立实现对照)、 空 body 签名。 全量 533 个测试通过。 Co-Authored-By: Claude <noreply@anthropic.com>master
9 changed files with 749 additions and 6 deletions
@ -0,0 +1,198 @@
@@ -0,0 +1,198 @@
|
||||
package common.ecommerce.edayun.auth; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.dto.EdayunTokenDtos; |
||||
import common.ecommerce.edayun.http.EdayunRequestFactory; |
||||
import common.ecommerce.http.HttpRequest; |
||||
import common.ecommerce.http.HttpResponse; |
||||
import common.ecommerce.http.JsonCodec; |
||||
import common.ecommerce.http.HttpTransport; |
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import common.ecommerce.shared.spi.AccessToken; |
||||
import common.ecommerce.warehouse.error.WarehouseException; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Instant; |
||||
|
||||
/** |
||||
* 易达云获取 token({@code POST /oauth/token})。 |
||||
* |
||||
* <p>凭据用 OMS 授权账号:{@link common.ecommerce.shared.spi.ChannelSecret#clientId()} |
||||
* / {@link common.ecommerce.shared.spi.ChannelSecret#clientSecret()}。 |
||||
* appKey 不参与这一步(它是业务请求头的字段)。</p> |
||||
* |
||||
* <p><b>待联调确认</b>:文档只给了 {@code code} 的取值(200 / 500 / 503 / 504), |
||||
* 没给响应体结构。所以这里同时兼容三种常见形态:</p> |
||||
* <ul> |
||||
* <li>{@code data.access_token} + {@code data.expires_in}(OAuth 标准)</li> |
||||
* <li>{@code data.expiry}(绝对时刻)</li> |
||||
* <li>{@code token} 直接放顶层</li> |
||||
* </ul> |
||||
* <p>都取不到时按 500 处理并带出原始报文(截断)。</p> |
||||
*/ |
||||
public final class EdayunTokenClient { |
||||
|
||||
private static final String OP_FETCH = "token.fetch"; |
||||
|
||||
private final HttpTransport transport; |
||||
private final JsonCodec json; |
||||
private final EdayunRequestFactory requestFactory; |
||||
private final Clock clock; |
||||
|
||||
public EdayunTokenClient(HttpTransport transport, JsonCodec json, Clock clock) { |
||||
this.transport = transport; |
||||
this.json = json; |
||||
this.clock = clock; |
||||
this.requestFactory = new EdayunRequestFactory(json); |
||||
} |
||||
|
||||
/** |
||||
* 换取令牌。 |
||||
* |
||||
* @param baseUrl 本次调用的基址 |
||||
* @param clientId OMS 授权用户名 |
||||
* @param clientSecret OMS 授权密码 |
||||
*/ |
||||
public AccessToken fetch(String baseUrl, String clientId, String clientSecret) { |
||||
HttpRequest req = requestFactory.token(baseUrl, clientId, clientSecret, OP_FETCH); |
||||
HttpResponse resp = transport.execute(req); |
||||
requireHttpOk(resp); |
||||
|
||||
String body = resp.body(); |
||||
EdayunTokenDtos.TokenResponse parsed; |
||||
try { |
||||
parsed = json.fromJson(body, EdayunTokenDtos.TokenResponse.class); |
||||
} catch (RuntimeException e) { |
||||
throw validation("edayun token response is not json", body); |
||||
} |
||||
requireBusinessOk(parsed, body); |
||||
|
||||
String token = tokenOf(parsed, body); |
||||
return AccessToken.builder() |
||||
.value(token) |
||||
.expiresAt(expiresAtOf(parsed)) |
||||
.build(); |
||||
} |
||||
|
||||
/** HTTP 层:非 2xx 直接失败。 */ |
||||
private void requireHttpOk(HttpResponse resp) { |
||||
int status = resp.statusCode(); |
||||
if (status >= 200 && status < 300) { |
||||
return; |
||||
} |
||||
throw toException(status, resp.body()); |
||||
} |
||||
|
||||
private WarehouseException toException(int status, String body) { |
||||
boolean retryable = status >= 500 && status != 504; |
||||
return WarehouseException.builder() |
||||
.message("edayun token request failed: http " + status |
||||
+ ", body=" + truncate(body)) |
||||
.operation(OP_FETCH) |
||||
.provider(EdayunConstants.ADAPTER_ID) |
||||
.platformCode(String.valueOf(status)) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(retryable) |
||||
.build(); |
||||
} |
||||
|
||||
/** |
||||
* 业务码:200 成功;500 失败;503 网关无效;504 超时。 |
||||
* |
||||
* <p>503 通常是网关问题、504 是超时,都值得重试;500 是明确失败,不重试。</p> |
||||
*/ |
||||
private void requireBusinessOk(EdayunTokenDtos.TokenResponse parsed, String body) { |
||||
if (parsed == null) { |
||||
throw validation("edayun token response is empty", body); |
||||
} |
||||
Integer code = parsed.code; |
||||
if (code == null) { |
||||
throw validation("edayun token response has no code", body); |
||||
} |
||||
if (code == EdayunConstants.CODE_SUCCESS) { |
||||
return; |
||||
} |
||||
throw WarehouseException.builder() |
||||
.message("edayun token business error: code=" + code |
||||
+ ", message=" + parsed.message) |
||||
.operation(OP_FETCH) |
||||
.provider(EdayunConstants.ADAPTER_ID) |
||||
.platformCode(String.valueOf(code)) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(code == EdayunConstants.CODE_GATEWAY_INVALID |
||||
|| code == EdayunConstants.CODE_TIMEOUT) |
||||
.build(); |
||||
} |
||||
|
||||
/** 三种形态都试一遍;都取不到就失败,不猜。 */ |
||||
private String tokenOf(EdayunTokenDtos.TokenResponse parsed, String body) { |
||||
if (parsed.data != null && hasText(parsed.data.accessToken)) { |
||||
return parsed.data.accessToken.trim(); |
||||
} |
||||
// 顶层 token(部分网关会把 data 拍平)
|
||||
String topLevel = json.stringAt(body, "token"); |
||||
if (hasText(topLevel)) { |
||||
return topLevel.trim(); |
||||
} |
||||
throw validation("edayun token response has no access token" |
||||
+ " (looked for data.access_token and token)", body); |
||||
} |
||||
|
||||
/** |
||||
* 过期时刻。 |
||||
* |
||||
* <p>优先 {@code data.expires_in}(相对秒),其次 {@code data.expiry}(绝对), |
||||
* 都没有就按 {@link EdayunConstants#DEFAULT_TOKEN_TTL_SECONDS} 兜底并标注待确认。</p> |
||||
*/ |
||||
private Instant expiresAtOf(EdayunTokenDtos.TokenResponse parsed) { |
||||
Instant now = Instant.now(clock); |
||||
EdayunTokenDtos.TokenResponse.TokenData data = parsed.data; |
||||
if (data != null && data.expiresIn != null && data.expiresIn > 0) { |
||||
return now.plusSeconds(data.expiresIn); |
||||
} |
||||
if (data != null && hasText(data.expiry)) { |
||||
Instant absolute = parseAbsolute(data.expiry.trim()); |
||||
if (absolute != null) { |
||||
return absolute; |
||||
} |
||||
} |
||||
return now.plusSeconds(EdayunConstants.DEFAULT_TOKEN_TTL_SECONDS); |
||||
} |
||||
|
||||
/** 绝对时刻:兼容 ISO-8601 与毫秒 / 秒数字。 */ |
||||
private static Instant parseAbsolute(String raw) { |
||||
try { |
||||
return Instant.parse(raw); |
||||
} catch (RuntimeException ignored) { |
||||
// 继续试数字
|
||||
} |
||||
try { |
||||
long n = Long.parseLong(raw); |
||||
// 10 位按秒、13 位按毫秒
|
||||
return raw.length() <= 10 ? Instant.ofEpochSecond(n) : Instant.ofEpochMilli(n); |
||||
} catch (RuntimeException ignored) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
private static ValidationException validation(String message, String body) { |
||||
return new ValidationException(WarehouseException.builder() |
||||
.message(message) |
||||
.operation(OP_FETCH) |
||||
.provider(EdayunConstants.ADAPTER_ID) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(false)); |
||||
} |
||||
|
||||
private static boolean hasText(String v) { |
||||
return v != null && !v.trim().isEmpty(); |
||||
} |
||||
|
||||
/** 响应可能含 token 与密码,异常里只留很短一段。 */ |
||||
private static String truncate(String body) { |
||||
if (body == null) { |
||||
return null; |
||||
} |
||||
return body.length() <= 300 ? body : body.substring(0, 300) + "..."; |
||||
} |
||||
} |
||||
@ -0,0 +1,67 @@
@@ -0,0 +1,67 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty; |
||||
|
||||
/** |
||||
* 易达云报文结构:获取 token({@code POST /oauth/token})。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构; |
||||
* 与其它接口共用的结构各自复制一份,避免跨接口耦合。</p> |
||||
*/ |
||||
public final class EdayunTokenDtos { |
||||
|
||||
private EdayunTokenDtos() { |
||||
} |
||||
|
||||
/** |
||||
* 获取 token 请求体。 |
||||
* |
||||
* <p>字段名是下划线风格,与易达云其它接口的驼峰不同,照文档原样保留。</p> |
||||
* |
||||
* <p><b>注意</b>:{@code client_id} / {@code client_secret} 是<b>易达云 OMS 系统的 |
||||
* 授权账号</b>,不是 appKey / appSecret。appKey 走请求头。</p> |
||||
*/ |
||||
public static final class TokenRequest { |
||||
|
||||
/** 用户名(oms 系统授权)。 */ |
||||
@JsonProperty("client_id") |
||||
public String clientId; |
||||
/** 密码(oms 系统授权)。 */ |
||||
@JsonProperty("client_secret") |
||||
public String clientSecret; |
||||
} |
||||
|
||||
/** |
||||
* 获取 token 响应。 |
||||
* |
||||
* <p><b>待联调确认</b>:文档只给了 {@code code} 的取值约定 |
||||
* (200 成功 / 500 失败 / 503 网关无效 / 504 超时),<b>没有给响应体结构</b>。 |
||||
* 这里按常见形态预留了 {@code data.access_token} / {@code expires_in} / |
||||
* {@code expiry},实际字段名以真机返回为准。</p> |
||||
*/ |
||||
public static final class TokenResponse { |
||||
|
||||
/** 200 成功 / 500 失败 / 503 网关无效 / 504 超时。 */ |
||||
public Integer code; |
||||
public String message; |
||||
|
||||
/** 业务载荷;字段名待确认。 */ |
||||
public TokenData data; |
||||
|
||||
/** token 载荷。 */ |
||||
public static final class TokenData { |
||||
/** access token。 */ |
||||
@JsonProperty("access_token") |
||||
public String accessToken; |
||||
/** 有效期(秒)。 */ |
||||
@JsonProperty("expires_in") |
||||
public Long expiresIn; |
||||
/** 绝对过期时刻;单位与格式待确认。 */ |
||||
@JsonProperty("expiry") |
||||
public String expiry; |
||||
/** 刷新令牌;易达云是否提供待确认。 */ |
||||
@JsonProperty("refresh_token") |
||||
public String refreshToken; |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,140 @@
@@ -0,0 +1,140 @@
|
||||
package common.ecommerce.edayun.http; |
||||
|
||||
import common.ecommerce.http.HttpRequest; |
||||
import common.ecommerce.http.JsonCodec; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.dto.EdayunTokenDtos; |
||||
|
||||
import java.net.URLEncoder; |
||||
import java.nio.charset.StandardCharsets; |
||||
import java.security.MessageDigest; |
||||
import java.util.LinkedHashMap; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* 构造易达云请求。 |
||||
* |
||||
* <p>鉴权分两段:</p> |
||||
* <ol> |
||||
* <li>先 {@code POST /oauth/token} 换 token(用 OMS 授权账号 client_id / client_secret)</li> |
||||
* <li>业务请求把 token 放请求头 {@code token},并带 {@code appKey} / {@code timestamp} / {@code sign}</li> |
||||
* </ol> |
||||
* |
||||
* <p>凭据映射(复用 {@link ChannelSecret}):</p> |
||||
* <table> |
||||
* <tr><th>易达云</th><th>ChannelSecret</th></tr> |
||||
* <tr><td>appKey(请求头)</td><td>{@link ChannelSecret#appKey()}</td></tr> |
||||
* <tr><td>appSecret(签名用)</td><td>{@link ChannelSecret#appSecret()}</td></tr> |
||||
* <tr><td>client_id</td><td>{@link ChannelSecret#clientId()}</td></tr> |
||||
* <tr><td>client_secret</td><td>{@link ChannelSecret#clientSecret()}</td></tr> |
||||
* </table> |
||||
*/ |
||||
public final class EdayunRequestFactory { |
||||
|
||||
private final JsonCodec json; |
||||
|
||||
public EdayunRequestFactory(JsonCodec json) { |
||||
this.json = json; |
||||
} |
||||
|
||||
/** |
||||
* 获取 token:{@code POST /oauth/token}。 |
||||
* |
||||
* <p>文档要求<b>不需要 header 参数</b>(除了 Content-Type)。</p> |
||||
* |
||||
* @param clientId 易达云 OMS 授权用户名 |
||||
* @param clientSecret 易达云 OMS 授权密码 |
||||
*/ |
||||
public HttpRequest token(String baseUrl, String clientId, String clientSecret, String operation) { |
||||
EdayunTokenDtos.TokenRequest body = new EdayunTokenDtos.TokenRequest(); |
||||
body.clientId = requireText(clientId, "edayun requires ChannelSecret.clientId()"); |
||||
body.clientSecret = requireText(clientSecret, "edayun requires ChannelSecret.clientSecret()"); |
||||
|
||||
return HttpRequest.builder() |
||||
.method("POST") |
||||
.url(join(baseUrl, EdayunConstants.PATH_TOKEN)) |
||||
.contentType(EdayunConstants.CONTENT_TYPE_JSON) |
||||
.body(json.toJson(body)) |
||||
.operation(operation) |
||||
.build(); |
||||
} |
||||
|
||||
/** |
||||
* 业务请求:带 token / appKey / timestamp / sign 四个头。 |
||||
* |
||||
* <p>{@code sign = MD5(body + "." + appSecret)},小写十六进制。 |
||||
* 测试环境传 {@code openApiAdminSecret} 可免签,但生产必须算。</p> |
||||
* |
||||
* @param token {@code /oauth/token} 拿到的 token |
||||
* @param appKey {@code ChannelSecret.appKey()} |
||||
* @param appSecret {@code ChannelSecret.appSecret()} |
||||
* @param timestamp 毫秒时间戳;5 分钟内有效 |
||||
* @param bodyJson 请求体(GET 时为空串) |
||||
*/ |
||||
public HttpRequest business(String baseUrl, String path, String method, |
||||
String token, String appKey, String appSecret, |
||||
long timestamp, String bodyJson, String operation) { |
||||
Map<String, String> headers = new LinkedHashMap<String, String>(); |
||||
headers.put(EdayunConstants.HEADER_TOKEN, requireText(token, "edayun requires a token")); |
||||
headers.put(EdayunConstants.HEADER_APP_KEY, requireText(appKey, |
||||
"edayun requires ChannelSecret.appKey()")); |
||||
headers.put(EdayunConstants.HEADER_TIMESTAMP, String.valueOf(timestamp)); |
||||
headers.put(EdayunConstants.HEADER_SIGN, sign(bodyJson, appSecret)); |
||||
|
||||
HttpRequest.Builder builder = HttpRequest.builder() |
||||
.method(method) |
||||
.url(join(baseUrl, path)) |
||||
.headers(headers) |
||||
.operation(operation); |
||||
if (bodyJson != null && !bodyJson.isEmpty()) { |
||||
builder.contentType(EdayunConstants.CONTENT_TYPE_JSON).body(bodyJson); |
||||
} |
||||
return builder.build(); |
||||
} |
||||
|
||||
/** |
||||
* 签名:{@code MD5(body + "." + appSecret)},小写十六进制。 |
||||
* |
||||
* <p>注意是 <b>body 原文</b>参与签名——所以业务方法要把「即将发出的那个字符串」 |
||||
* 传进来,不能传反序列化后再序列化的结果(字段顺序变了签名就对不上)。</p> |
||||
*/ |
||||
public static String sign(String bodyJson, String appSecret) { |
||||
String secret = requireText(appSecret, "edayun requires ChannelSecret.appSecret()"); |
||||
String raw = (bodyJson == null ? "" : bodyJson) + "." + secret; |
||||
try { |
||||
MessageDigest md = MessageDigest.getInstance("MD5"); |
||||
byte[] digest = md.digest(raw.getBytes(StandardCharsets.UTF_8)); |
||||
StringBuilder sb = new StringBuilder(digest.length * 2); |
||||
for (byte b : digest) { |
||||
sb.append(Character.forDigit((b >> 4) & 0xF, 16)); |
||||
sb.append(Character.forDigit(b & 0xF, 16)); |
||||
} |
||||
return sb.toString(); |
||||
} catch (java.security.NoSuchAlgorithmException e) { |
||||
throw new IllegalStateException("MD5 not available", e); |
||||
} |
||||
} |
||||
|
||||
private static String join(String baseUrl, String path) { |
||||
String base = requireText(baseUrl, "edayun requires an endpoint base url"); |
||||
return base.endsWith("/") ? base + (path.startsWith("/") ? path.substring(1) : path) |
||||
: base + (path.startsWith("/") ? path : "/" + path); |
||||
} |
||||
|
||||
private static String requireText(String value, String message) { |
||||
if (value == null || value.trim().isEmpty()) { |
||||
throw new IllegalArgumentException(message); |
||||
} |
||||
return value.trim(); |
||||
} |
||||
|
||||
/** 供将来带 query 参数的接口使用。 */ |
||||
static String encode(String v) { |
||||
try { |
||||
return URLEncoder.encode(v, "UTF-8"); |
||||
} catch (java.io.UnsupportedEncodingException e) { |
||||
throw new IllegalStateException(e); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,196 @@
@@ -0,0 +1,196 @@
|
||||
package common.ecommerce.edayun.auth; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.http.EdayunRequestFactory; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import common.ecommerce.shared.spi.AccessToken; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.error.WarehouseException; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Instant; |
||||
import java.time.ZoneOffset; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 易达云获取 token({@code POST /oauth/token})。 |
||||
* |
||||
* <p>文档只给了 {@code code} 的取值,没给响应体结构,所以这里把三种常见形态 |
||||
* (OAuth 标准 / 绝对时刻 / 顶层 token)都固化成测试,等真机确认后再删多余的分支。</p> |
||||
*/ |
||||
class EdayunTokenClientTest { |
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-12T00:00:00Z"), ZoneOffset.UTC); |
||||
private static final String BASE = "https://api.edayun.test"; |
||||
|
||||
private static EdayunTokenClient client(RecordingTransport transport) { |
||||
return new EdayunTokenClient(transport, new JacksonJsonCodec(), CLOCK); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 请求
|
||||
|
||||
@Test |
||||
void sendsDocumentedRequest() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":{\"access_token\":\"T1\",\"expires_in\":7200}}")); |
||||
|
||||
client(transport).fetch(BASE, "dl-test", "123456"); |
||||
|
||||
String body = transport.lastDataRequest().body(); |
||||
assertEquals("POST", transport.lastDataRequest().method()); |
||||
assertEquals(BASE + "/oauth/token", transport.lastDataRequest().url()); |
||||
// 字段名是下划线风格,照文档原样
|
||||
assertTrue(body.contains("\"client_id\":\"dl-test\""), body); |
||||
assertTrue(body.contains("\"client_secret\":\"123456\""), body); |
||||
// 文档明确:这一步不需要业务头
|
||||
assertTrue(transport.lastDataRequest().headers().isEmpty() |
||||
|| !transport.lastDataRequest().headers().containsKey("token")); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 响应形态
|
||||
|
||||
@Test |
||||
void acceptsOauthStandardShape() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":{\"access_token\":\"T1\",\"expires_in\":7200}}")); |
||||
|
||||
AccessToken token = client(transport).fetch(BASE, "u", "p"); |
||||
|
||||
assertEquals("T1", token.value()); |
||||
assertEquals(Instant.parse("2026-11-12T02:00:00Z"), token.expiresAt()); |
||||
} |
||||
|
||||
@Test |
||||
void acceptsAbsoluteExpiry() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":{\"access_token\":\"T2\"," |
||||
+ "\"expiry\":\"2026-11-12T03:00:00Z\"}}")); |
||||
|
||||
AccessToken token = client(transport).fetch(BASE, "u", "p"); |
||||
|
||||
assertEquals("T2", token.value()); |
||||
assertEquals(Instant.parse("2026-11-12T03:00:00Z"), token.expiresAt()); |
||||
} |
||||
|
||||
@Test |
||||
void acceptsTopLevelToken() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"token\":\"T3\"}")); |
||||
|
||||
AccessToken token = client(transport).fetch(BASE, "u", "p"); |
||||
|
||||
assertEquals("T3", token.value()); |
||||
// 没有有效期信息时按兜底 TTL
|
||||
assertEquals(Instant.parse("2026-11-12T02:00:00Z"), token.expiresAt()); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 失败路径
|
||||
|
||||
@Test |
||||
void noTokenInResponseIsRejected() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":{\"foo\":\"bar\"}}")); |
||||
|
||||
ValidationException ex = assertThrows(ValidationException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p")); |
||||
assertTrue(ex.getMessage().contains("no access token"), ex.getMessage()); |
||||
} |
||||
|
||||
/** 500 是明确失败,不重试。 */ |
||||
@Test |
||||
void business500IsNotRetryable() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":500,\"message\":\"bad credentials\"}")); |
||||
|
||||
WarehouseException ex = assertThrows(WarehouseException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p")); |
||||
assertTrue(ex.getMessage().contains("code=500"), ex.getMessage()); |
||||
assertEquals(Boolean.FALSE, ex.retryable()); |
||||
} |
||||
|
||||
/** 503 / 504 是网关与超时,值得重试。 */ |
||||
@Test |
||||
void gatewayAndTimeoutAreRetryable() { |
||||
for (String code : new String[] {"503", "504"}) { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":" + code + ",\"message\":\"gw\"}")); |
||||
WarehouseException ex = assertThrows(WarehouseException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p"), code); |
||||
assertEquals(Boolean.TRUE, ex.retryable(), code); |
||||
} |
||||
} |
||||
|
||||
@Test |
||||
void missingCodeIsRejected() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok("{\"message\":\"ok\"}")); |
||||
|
||||
assertThrows(ValidationException.class, () -> client(transport).fetch(BASE, "u", "p")); |
||||
} |
||||
|
||||
@Test |
||||
void non2xxIsRejected() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.status(401, "{}")); |
||||
|
||||
WarehouseException ex = assertThrows(WarehouseException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p")); |
||||
assertTrue(ex.getMessage().contains("http 401"), ex.getMessage()); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 凭据校验
|
||||
|
||||
@Test |
||||
void missingCredentialsFailFast() { |
||||
RecordingTransport transport = RecordingTransport.create(); |
||||
|
||||
assertThrows(IllegalArgumentException.class, |
||||
() -> client(transport).fetch(BASE, " ", "p")); |
||||
assertThrows(IllegalArgumentException.class, |
||||
() -> client(transport).fetch(BASE, "u", null)); |
||||
assertTrue(transport.recorded().isEmpty(), "凭据缺失不应发出请求"); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 签名
|
||||
|
||||
@Test |
||||
void signIsMd5OfBodyDotSecret() { |
||||
// MD5("{\"a\":1}.secret") 的已知值,用独立实现校验
|
||||
String expected = md5Hex("{\"a\":1}.secret"); |
||||
assertEquals(expected, EdayunRequestFactory.sign("{\"a\":1}", "secret")); |
||||
} |
||||
|
||||
@Test |
||||
void emptyBodyStillSigns() { |
||||
assertEquals(md5Hex(".secret"), EdayunRequestFactory.sign(null, "secret")); |
||||
assertEquals(md5Hex(".secret"), EdayunRequestFactory.sign("", "secret")); |
||||
} |
||||
|
||||
private static String md5Hex(String s) { |
||||
try { |
||||
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); |
||||
byte[] d = md.digest(s.getBytes(java.nio.charset.StandardCharsets.UTF_8)); |
||||
StringBuilder sb = new StringBuilder(); |
||||
for (byte b : d) { |
||||
sb.append(Character.forDigit((b >> 4) & 0xF, 16)); |
||||
sb.append(Character.forDigit(b & 0xF, 16)); |
||||
} |
||||
return sb.toString(); |
||||
} catch (Exception e) { |
||||
throw new IllegalStateException(e); |
||||
} |
||||
} |
||||
} |
||||
Loading…
Reference in new issue