@Override
    protected Optional<ErrorResponse> filter(DiscFilterRequest req) {
        var certs = req.getClientCertificateChain();
        log.fine(() -> "Certificate chain contains %d elements".formatted(certs.size()));
        if (certs.isEmpty()) {
            log.fine("Missing client certificate");
            return Optional.of(new ErrorResponse(Response.Status.UNAUTHORIZED, "Unauthorized"));
        }
        if (legacyMode) {
            log.fine("Legacy mode validation complete");
            ClientPrincipal.attachToRequest(req, Set.of(), Set.of(READ, WRITE));
            return Optional.empty();
        }
        var permission = Permission.getRequiredPermission(req).orElse(null);
        if (permission == null) return Optional.of(new ErrorResponse(Response.Status.FORBIDDEN, "Forbidden"));
        var clientCert = certs.get(0);
        var clientIds = new TreeSet<String>();
        var permissions = new TreeSet<Permission>();
        for (Client c : allowedClients) {
            if (!c.permissions().contains(permission)) continue;
            if (!c.certificates().contains(clientCert)) continue;
            clientIds.add(c.id());
            permissions.addAll(c.permissions());
        }
        if (clientIds.isEmpty()) return Optional.of(new ErrorResponse(Response.Status.FORBIDDEN, "Forbidden"));
        ClientPrincipal.attachToRequest(req, clientIds, permissions);
        return Optional.empty();
    }
@Test
    void accepts_any_trusted_client_certificate_in_legacy_mode() {
        var req = FilterTestUtils.newRequestBuilder().withClientCertificate(LEGACY_CLIENT_CERT).build();
        var responseHandler = new MockResponseHandler();
        newFilterWithLegacyMode().filter(req, responseHandler);
        assertNull(responseHandler.getResponse());
        assertEquals(new ClientPrincipal(Set.of(), Set.of(READ, WRITE)), req.getUserPrincipal());
    }