You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@james.apache.org by "vttranlina (via GitHub)" <gi...@apache.org> on 2023/05/31 07:54:24 UTC

[GitHub] [james-project] vttranlina commented on a diff in pull request #1573: JAMES-3906 Allow to reload SSL certificates

vttranlina commented on code in PR #1573:
URL: https://github.com/apache/james-project/pull/1573#discussion_r1211220337


##########
server/container/guice/protocols/smtp/src/main/java/org/apache/james/modules/protocols/SmtpGuiceProbe.java:
##########
@@ -64,6 +64,13 @@ public Port getSmtpStartTlsPort() {
         return getPort(AbstractConfigurableAsyncServer::getStartTLSSupported);
     }
 
+    public Port getSmtpSslPort() {
+        return getPort(server -> {
+            System.out.println(server.getServiceType());

Review Comment:
   debug spotted



##########
server/apps/memory-app/src/test/java/org/apache/james/CertificateReloadTest.java:
##########
@@ -0,0 +1,218 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.james;
+
+import static io.restassured.RestAssured.given;
+import static org.apache.james.MemoryJamesServerMain.IN_MEMORY_SERVER_AGGREGATE_MODULE;
+import static org.apache.james.jmap.JMAPTestingConstants.LOCALHOST_IP;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.james.data.UsersRepositoryModuleChooser;
+import org.apache.james.modules.data.MemoryUsersRepositoryModule;
+import org.apache.james.modules.protocols.ImapGuiceProbe;
+import org.apache.james.modules.protocols.SmtpGuiceProbe;
+import org.apache.james.utils.WebAdminGuiceProbe;
+import org.apache.james.webadmin.WebAdminConfiguration;
+import org.apache.james.webadmin.WebAdminUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import com.google.common.collect.ImmutableList;
+
+import io.restassured.RestAssured;
+
+class CertificateReloadTest {
+
+    public static class BlindTrustManager implements X509TrustManager {
+        public X509Certificate[] getAcceptedIssuers() {
+            return null;
+        }
+
+        public void checkClientTrusted(X509Certificate[] chain, String authType) {
+
+        }
+
+        public void checkServerTrusted(X509Certificate[] chain, String authType) {
+
+
+        }
+    }
+
+    private static final List<String> BASE_CONFIGURATION_FILE_NAMES = ImmutableList.of("dnsservice.xml",
+        "dnsservice.xml",
+        "imapserver.xml",
+        "imapserver2.xml",
+        "jwt_publickey",
+        "lmtpserver.xml",
+        "keystore",
+        "mailetcontainer.xml",
+        "mailrepositorystore.xml",
+        "managesieveserver.xml",
+        "pop3server.xml",
+        "smtpserver.xml",
+        "smtpserver2.xml");
+
+    private GuiceJamesServer jamesServer;
+    private TemporaryJamesServer temporaryJamesServer;
+
+    @BeforeEach
+    void beforeEach(@TempDir Path workingPath) {
+        temporaryJamesServer = new TemporaryJamesServer(workingPath.toFile(), BASE_CONFIGURATION_FILE_NAMES);
+
+        jamesServer = temporaryJamesServer.getJamesServer()
+            .combineWith(IN_MEMORY_SERVER_AGGREGATE_MODULE)
+            .combineWith(new UsersRepositoryModuleChooser(new MemoryUsersRepositoryModule())
+                .chooseModules(UsersRepositoryModuleChooser.Implementation.DEFAULT))
+            .overrideWith(binder -> binder.bind(WebAdminConfiguration.class).toInstance(WebAdminConfiguration.TEST_CONFIGURATION));
+
+    }
+
+    @AfterEach
+    void afterEach() {
+        if (jamesServer != null && jamesServer.isStarted()) {
+            jamesServer.stop();
+        }
+    }
+
+    @Test
+    void subjectShouldBeKeptWhenNoRestart() throws Exception {
+        temporaryJamesServer.copyResources("smtpserver2.xml", "smtpserver.xml");
+        jamesServer.start();
+
+        assertThat(getServerCertificate(jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpSslPort().getValue()).getSubjectX500Principal().getName())
+            .isEqualTo("CN=Benoit Tellier,OU=Linagora,O=James,L=Puteaux,ST=Unknown,C=FR");
+    }
+
+    private X509Certificate getServerCertificate(int port) throws NoSuchAlgorithmException, KeyManagementException, IOException {
+        SSLSocket clientConnection = openSSLConnection(port);
+
+        return Arrays.stream(clientConnection.getSession()
+            .getPeerCertificates())
+            .filter(X509Certificate.class::isInstance)
+            .map(X509Certificate.class::cast)
+            .findFirst()
+            .orElseThrow();
+    }
+
+    private SSLSocket openSSLConnection(int port) throws NoSuchAlgorithmException, KeyManagementException, IOException {
+        SSLContext ctx = SSLContext.getInstance("TLS");
+        ctx.init(null, new TrustManager[]{new BlindTrustManager()}, null);
+        SSLSocket clientConnection = (SSLSocket) ctx.getSocketFactory().createSocket(LOCALHOST_IP, port);
+        return clientConnection;
+    }
+
+    @Test
+    void reloadShouldUpdateCertificates() throws Exception {
+        temporaryJamesServer.copyResources("smtpserver2.xml", "smtpserver.xml");
+        jamesServer.start();
+
+        temporaryJamesServer.copyResources("keystore2", "keystore");
+
+        WebAdminGuiceProbe webAdminGuiceProbe = jamesServer.getProbe(WebAdminGuiceProbe.class);
+        RestAssured.requestSpecification = WebAdminUtils.buildRequestSpecification(webAdminGuiceProbe.getWebAdminPort())
+            .build();
+
+        int port = jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpSslPort().getValue();
+        given()
+            .queryParam("reload-certificate")
+            .queryParam("port", port)
+        .when()
+            .post("/servers")
+        .then()
+            .statusCode(204);
+
+        assertThat(getServerCertificate(port).getSubjectX500Principal().getName())
+            .isEqualTo("CN=Testing,OU=Testing,O=Testing,L=Testing,ST=Testing,C=Te");
+    }
+
+    @Test
+    void reloadShouldUpdateCertificatesForImap() throws Exception {
+        temporaryJamesServer.copyResources("imapserver2.xml", "imapserver.xml");
+        jamesServer.start();
+
+        temporaryJamesServer.copyResources("keystore2", "keystore");
+
+        WebAdminGuiceProbe webAdminGuiceProbe = jamesServer.getProbe(WebAdminGuiceProbe.class);
+        RestAssured.requestSpecification = WebAdminUtils.buildRequestSpecification(webAdminGuiceProbe.getWebAdminPort())
+            .build();
+
+        int port = jamesServer.getProbe(ImapGuiceProbe.class).getImapSSLPort();
+        given()
+            .queryParam("reload-certificate")
+            .queryParam("port", port)
+        .when()
+            .post("/servers")
+        .then()
+            .statusCode(204);
+
+        assertThat(getServerCertificate(port).getSubjectX500Principal().getName())
+            .isEqualTo("CN=Testing,OU=Testing,O=Testing,L=Testing,ST=Testing,C=Te");
+    }
+
+    @Test
+    void reloadShouldNotAbortExistingConnections() throws Exception {
+        temporaryJamesServer.copyResources("smtpserver2.xml", "smtpserver.xml");
+        jamesServer.start();
+        int port = jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpSslPort().getValue();
+        SSLSocket channel = openSSLConnection(port);
+
+        temporaryJamesServer.copyResources("keystore2", "keystore");
+
+        WebAdminGuiceProbe webAdminGuiceProbe = jamesServer.getProbe(WebAdminGuiceProbe.class);
+        RestAssured.requestSpecification = WebAdminUtils.buildRequestSpecification(webAdminGuiceProbe.getWebAdminPort())
+            .build();
+
+        given()
+            .queryParam("reload-certificate")
+            .queryParam("port", jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpSslPort().getValue())
+        .when()
+            .post("/servers")
+        .then()
+            .statusCode(204);
+
+        System.out.println(readBytes(channel));

Review Comment:
   debug spotted



##########
server/protocols/webadmin/webadmin-protocols/src/main/java/org/apache/james/protocols/webadmin/ProtocolServerRoutes.java:
##########
@@ -0,0 +1,91 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.james.protocols.webadmin;
+
+import java.util.Optional;
+import java.util.Set;
+
+import javax.inject.Inject;
+
+import org.apache.james.protocols.lib.netty.CertificateReloadable;
+import org.apache.james.util.Port;
+import org.apache.james.webadmin.Routes;
+import org.apache.james.webadmin.utils.ErrorResponder;
+import org.apache.james.webadmin.utils.Responses;
+import org.eclipse.jetty.http.HttpStatus;
+
+import com.github.fge.lambdas.Throwing;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+
+import spark.Request;
+import spark.Service;
+
+public class ProtocolServerRoutes implements Routes {
+    public static final String SERVERS = "servers";
+
+    private final Set<CertificateReloadable.Factory> servers;
+
+    @Inject
+    public ProtocolServerRoutes(Set<CertificateReloadable.Factory> servers) {
+        this.servers = servers;
+    }
+
+    @Override
+    public String getBasePath() {
+        return SERVERS;
+    }
+
+    @Override
+    public void define(Service service) {
+        service.post(SERVERS, (request, response) -> {
+            Preconditions.checkArgument(request.queryParams().contains("reload-certificate"),
+                "'reload-certificate' query parameter shall be specified");
+
+            if (noServerEnabled()) {
+                return ErrorResponder.builder()
+                    .statusCode(HttpStatus.BAD_REQUEST_400)
+                    .type(ErrorResponder.ErrorType.NOT_FOUND)
+                    .message("No servers configured, nothing to reload")
+                    .haltError();
+            }
+
+            servers.stream()
+                .flatMap(CertificateReloadable.Factory::certificatesReloadable)
+                .filter(filters(request))
+                .forEach(Throwing.consumer(CertificateReloadable::reloadSSLCertificate));
+
+            return Responses.returnNoContent(response);
+        });
+    }
+
+    private Predicate<CertificateReloadable> filters(Request request) {
+        Optional<Port> port = Optional.ofNullable(request.queryParams("port")).map(Integer::parseUnsignedInt).map(Port::of);

Review Comment:
   it will be better when moving the port extractor outside the loop



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org