javadockersshjunittestcontainers

Publish private key of testcontainer


I setup some Java integration tests with testcontainers and atomz/sftp docker container for Jsch, both running on the same machine.

I store the generated key pair in the test/resource path of my maven project. The keypair isn't used anywhere else as on my local docker container and is only used for testing.

This is the code fragment where the private keys are used:

private static final GenericContainer<?> sftpContainer = new GenericContainer<>("atmoz/sftp:alpine")
        .withCopyFileToContainer(
                MountableFile.forClasspathResource("ssh/ssh_host_rsa_key"),
                "/etc/ssh/ssh_host_rsa_key"
        )
        .withCopyFileToContainer(
                MountableFile.forClasspathResource("ssh/ssh_host_ed25519_key"),
                "/etc/ssh/ssh_host_ed25519_key")
        .withExposedPorts(22)
        .withCommand("foo:pass:::upload");

Is it safe to add the keypair to git and push it to github? Or are there drawbacks to this method? Are there better solutions?

Thank you in advance.


Solution

  • I now wrote the following code to generate keys for each test run:

    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.KeyPair;
    
    import java.io.File;
    import java.io.IOException;
    
    /**
     * Class to generate test RSA KeyPairs
     */
    public class KeyPairGenerator {
        
        private static final File privateKeyFile = new File("./src/test/resources/ssh_host_rsa_key");
        private static final File publicKeyFile = new File("./src/test/resources/ssh_host_rsa_key.pub");
    
        public File getPrivateKeyFile() {
            return privateKeyFile;
        }
    
        public File getPublicKeyFile() {
            return publicKeyFile;
        }
    
        /**
         * Generate RSA KeyPair
         */
        public void generate() throws IOException, JSchException {
            // Generate RSA keyPair
            JSch jSch = new JSch();
            KeyPair keyPair = KeyPair.genKeyPair(jSch, KeyPair.RSA, 4096);
    
            // Write Key files to file
            keyPair.writePrivateKey(privateKeyFile.getPath());
            keyPair.writePublicKey(publicKeyFile.getPath(), "sftp@docker");
            
            
        }
    }
    

    The key pair will be deleted after all tests ran.