This commit is contained in:
2026-09-29 18:47:37 +08:00
parent 2c60a29e0f
commit c2927ab9a6
291 changed files with 4008 additions and 6298 deletions
@@ -0,0 +1,45 @@
package com.baiyue.common.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;
import static org.assertj.core.api.Assertions.*;
class HttpSessionStateVerifierTest {
@Test void acceptsOnlyExplicitSuccessAndNeverForwardsBearer() throws Exception {
var body = new AtomicReference<>("{\"code\":\"200\",\"data\":true}");
var auth = new AtomicReference<String>();
var internal = new AtomicReference<String>();
var input = new AtomicReference<String>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/validate", exchange -> {
auth.set(exchange.getRequestHeaders().getFirst("Authorization"));
internal.set(exchange.getRequestHeaders().getFirst("X-Internal-Service-Token"));
input.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
byte[] bytes = body.get().getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, bytes.length); exchange.getResponseBody().write(bytes); exchange.close();
});
server.start();
try {
var verifier = new HttpSessionStateVerifier("http://127.0.0.1:" + server.getAddress().getPort() + "/validate", "internal-only", new ObjectMapper());
verifier.verify("session", 42L);
assertThat(auth.get()).isNull(); assertThat(internal.get()).isEqualTo("internal-only");
assertThat(new ObjectMapper().readTree(input.get()).path("userId").longValue()).isEqualTo(42);
for (String rejected : new String[]{"{}", "{\"code\":200,\"data\":true}", "{\"code\":\"200\",\"data\":false}",
"{\"code\":\"A0403\",\"data\":true}", "{\"code\":\"200\",\"data\":\"true\"}", "not-json"}) {
body.set(rejected);
assertThatThrownBy(() -> verifier.verify("session", 42L)).isInstanceOf(IllegalArgumentException.class);
}
} finally { server.stop(0); }
}
@Test void unavailableAuthorityFailsClosed() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
int port = server.getAddress().getPort(); server.start(); server.stop(0);
var verifier = new HttpSessionStateVerifier("http://127.0.0.1:" + port + "/validate", "internal", new ObjectMapper());
assertThatThrownBy(() -> verifier.verify("session", 42L)).isInstanceOf(IllegalArgumentException.class);
}
}