Строгая проверка mTLS для каждой API-реплики

This commit is contained in:
EgorAnti
2026-11-26 20:02:45 +03:00
parent 953c1986aa
commit 3c412926e5
5 changed files with 72 additions and 27 deletions
@@ -9,33 +9,50 @@ import java.security.cert.X509Certificate;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class TrustedClientCertificateFilterTest {
private final TrustedClientCertificateFilter filter =
new TrustedClientCertificateFilter("spiffe://hla-lab7/lb");
private static final String ALLOWED_URI = "spiffe://hla-lab7/lb";
@Test
void rejectsWrongUriEvenWhenTlsAlreadyTrustedTheCertificate() throws Exception {
MockHttpServletResponse response = invoke("spiffe://hla-lab7/worker");
void rejectsRequestWithoutClientCertificate() throws Exception {
MockHttpServletResponse response = apply(null);
assertEquals(403, response.getStatus());
assertEquals("no-store", response.getHeader("Cache-Control"));
assertEquals("application/json", response.getContentType());
}
@Test
void rejectsTrustedCertificateWithWrongUriSan() throws Exception {
MockHttpServletResponse response = apply(certificate("spiffe://hla-lab7/worker"));
assertEquals(403, response.getStatus());
}
@Test
void acceptsExactLoadBalancerUri() throws Exception {
MockHttpServletResponse response = invoke("spiffe://hla-lab7/lb");
void acceptsOnlyTheConfiguredUriSan() throws Exception {
MockHttpServletResponse response = apply(certificate(ALLOWED_URI));
assertEquals(200, response.getStatus());
assertNull(response.getErrorMessage());
}
private MockHttpServletResponse invoke(String uri) throws Exception {
X509Certificate certificate = mock(X509Certificate.class);
when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, uri)));
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/health/ready");
request.setAttribute("jakarta.servlet.request.X509Certificate",
new X509Certificate[]{certificate});
private MockHttpServletResponse apply(X509Certificate certificate) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
if (certificate != null) {
request.setAttribute("jakarta.servlet.request.X509Certificate",
new X509Certificate[]{certificate});
}
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
new TrustedClientCertificateFilter(ALLOWED_URI)
.doFilter(request, response, new MockFilterChain());
return response;
}
private X509Certificate certificate(String uriSan) throws Exception {
X509Certificate certificate = mock(X509Certificate.class);
when(certificate.getSubjectAlternativeNames()).thenReturn(
List.of(List.of(6, uriSan)));
return certificate;
}
}