chore: Run spotless

This commit is contained in:
Magnus Leßmann (@MarkL4YG) 2024-11-17 20:20:58 +01:00
parent ae6c7232c4
commit caefe964b1
8 changed files with 146 additions and 57 deletions

View file

@ -1,7 +1,6 @@
package de.mlessmann.certassist; package de.mlessmann.certassist;
import org.slf4j.Logger; import static org.slf4j.LoggerFactory.getLogger;
import org.springframework.lang.NonNull;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
@ -9,8 +8,8 @@ import java.nio.file.FileVisitor;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger; import org.springframework.lang.NonNull;
public class DeleteRecursiveFileVisitor implements FileVisitor<Path> { public class DeleteRecursiveFileVisitor implements FileVisitor<Path> {

View file

@ -1,20 +1,18 @@
package de.mlessmann.certassist; package de.mlessmann.certassist;
import de.mlessmann.certassist.except.UnresolvableCLIDependency; import static org.slf4j.LoggerFactory.getLogger;
import lombok.Setter;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import de.mlessmann.certassist.except.UnresolvableCLIDependency;
import java.io.File; import java.io.File;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import org.apache.commons.lang3.SystemUtils;
import static org.slf4j.LoggerFactory.getLogger; import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service @Service
public class ExecutableResolver { public class ExecutableResolver {
@ -53,7 +51,10 @@ public class ExecutableResolver {
} }
} }
LOGGER.error("Could not find executable '{}' in PATH. Make sure that it exists on the of the directory and is executable.", executableName); LOGGER.error(
"Could not find executable '{}' in PATH. Make sure that it exists on the of the directory and is executable.",
executableName
);
return Optional.empty(); return Optional.empty();
} }

View file

@ -9,7 +9,12 @@ public class UnresolvableCLIDependency extends Exception {
private final String propertyName; private final String propertyName;
public UnresolvableCLIDependency(String executableName, String propertyName) { public UnresolvableCLIDependency(String executableName, String propertyName) {
super("Could not resolve executable for '%s'. (Use property '%s' to point the application directly to the executable.)".formatted(executableName, propertyName)); super(
"Could not resolve executable for '%s'. (Use property '%s' to point the application directly to the executable.)".formatted(
executableName,
propertyName
)
);
this.executableName = executableName; this.executableName = executableName;
this.propertyName = propertyName; this.propertyName = propertyName;
} }

View file

@ -1,10 +1,9 @@
package de.mlessmann.certassist.openssl; package de.mlessmann.certassist.openssl;
import java.util.UUID;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
import java.util.UUID;
@Data @Data
@Builder @Builder
public class CertificateRequest { public class CertificateRequest {
@ -15,26 +14,32 @@ public class CertificateRequest {
private RequestType type; private RequestType type;
private String commonName; private String commonName;
private String trustingAuthority; private String trustingAuthority;
@Builder.Default @Builder.Default
private int requestedKeyLength = 4096; private int requestedKeyLength = 4096;
@Builder.Default @Builder.Default
private int requestedValidityDays = 365; private int requestedValidityDays = 365;
private CertificateSubject subject; private CertificateSubject subject;
private CertificateRequestExtension extension; private CertificateRequestExtension extension;
public enum RequestType { public enum RequestType {
ROOT_AUTHORITY, ROOT_AUTHORITY,
STANDALONE_CERTIFICATE, STANDALONE_CERTIFICATE,
NORMAL_CERTIFICATE NORMAL_CERTIFICATE,
} }
public static class CertificateRequestBuilder { public static class CertificateRequestBuilder {
public CertificateRequestBuilder subject(CertificateSubject.CertificateSubjectBuilder builder) { public CertificateRequestBuilder subject(CertificateSubject.CertificateSubjectBuilder builder) {
this.subject = builder.build(); this.subject = builder.build();
return this; return this;
} }
public CertificateRequestBuilder extension(CertificateRequestExtension.CertificateRequestExtensionBuilder builder) { public CertificateRequestBuilder extension(
CertificateRequestExtension.CertificateRequestExtensionBuilder builder
) {
this.extension = builder.build(); this.extension = builder.build();
return this; return this;
} }

View file

@ -1,10 +1,9 @@
package de.mlessmann.certassist.openssl; package de.mlessmann.certassist.openssl;
import java.util.List;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import java.util.List;
@Getter @Getter
@Builder @Builder
public class CertificateRequestExtension { public class CertificateRequestExtension {
@ -12,6 +11,7 @@ public class CertificateRequestExtension {
private List<String> alternativeNames; private List<String> alternativeNames;
public static class CertificateRequestExtensionBuilder { public static class CertificateRequestExtensionBuilder {
public CertificateRequestExtensionBuilder alternativeNames(String... altNames) { public CertificateRequestExtensionBuilder alternativeNames(String... altNames) {
this.alternativeNames = List.of(altNames); this.alternativeNames = List.of(altNames);
return this; return this;

View file

@ -1,8 +1,18 @@
package de.mlessmann.certassist.openssl; package de.mlessmann.certassist.openssl;
import static org.slf4j.LoggerFactory.getLogger;
import de.mlessmann.certassist.ExecutableResolver; import de.mlessmann.certassist.ExecutableResolver;
import de.mlessmann.certassist.except.CommandLineOperationException; import de.mlessmann.certassist.except.CommandLineOperationException;
import de.mlessmann.certassist.except.UnresolvableCLIDependency; import de.mlessmann.certassist.except.UnresolvableCLIDependency;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -12,23 +22,14 @@ import org.zeroturnaround.exec.ProcessExecutor;
import org.zeroturnaround.exec.StartedProcess; import org.zeroturnaround.exec.StartedProcess;
import org.zeroturnaround.exec.stream.slf4j.Slf4jStream; import org.zeroturnaround.exec.stream.slf4j.Slf4jStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import static org.slf4j.LoggerFactory.getLogger;
@Service @Service
public class OpenSSLCertificateCreator { public class OpenSSLCertificateCreator {
public static final String OPENSSL_CERT_SUBJECT_TEMPLATE = "/C=ISO-COUNTRY/ST=STATE/L=LOCALITY/O=ORGANIZATION/CN=COMMON-NAME"; public static final String OPENSSL_CERT_SUBJECT_TEMPLATE =
"/C=ISO-COUNTRY/ST=STATE/L=LOCALITY/O=ORGANIZATION/CN=COMMON-NAME";
private static final Logger LOGGER = getLogger(OpenSSLCertificateCreator.class); private static final Logger LOGGER = getLogger(OpenSSLCertificateCreator.class);
private static final String CSR_EXT_TEMPLATE = """ private static final String CSR_EXT_TEMPLATE =
"""
authorityKeyIdentifier=keyid,issuer authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
@ -45,7 +46,12 @@ public class OpenSSLCertificateCreator {
} }
private static String buildSubjectArg(CertificateRequest request) { private static String buildSubjectArg(CertificateRequest request) {
String certSubject = OPENSSL_CERT_SUBJECT_TEMPLATE.replace("ISO-COUNTRY", request.getSubject().getCountry()).replace("STATE", request.getSubject().getState()).replace("LOCALITY", request.getSubject().getLocality()).replace("ORGANIZATION", request.getSubject().getOrganization()).replace("COMMON-NAME", request.getCommonName()); String certSubject = OPENSSL_CERT_SUBJECT_TEMPLATE
.replace("ISO-COUNTRY", request.getSubject().getCountry())
.replace("STATE", request.getSubject().getState())
.replace("LOCALITY", request.getSubject().getLocality())
.replace("ORGANIZATION", request.getSubject().getOrganization())
.replace("COMMON-NAME", request.getCommonName());
if (StringUtils.isNotBlank(request.getSubject().getOrganizationalUnit())) { if (StringUtils.isNotBlank(request.getSubject().getOrganizationalUnit())) {
certSubject += "/OU=" + request.getSubject().getOrganizationalUnit(); certSubject += "/OU=" + request.getSubject().getOrganizationalUnit();
@ -58,7 +64,8 @@ public class OpenSSLCertificateCreator {
} }
@Nullable @Nullable
public OpenSSLCertificateResult createCertificate(CertificateRequest request) throws CommandLineOperationException, InterruptedException { public OpenSSLCertificateResult createCertificate(CertificateRequest request)
throws CommandLineOperationException, InterruptedException {
Path tmpDir; Path tmpDir;
try { try {
tmpDir = Files.createTempDirectory("certassist"); tmpDir = Files.createTempDirectory("certassist");
@ -75,12 +82,26 @@ public class OpenSSLCertificateCreator {
return new OpenSSLCertificateResult(tmpDir); return new OpenSSLCertificateResult(tmpDir);
} }
private Path createKeyfile(CertificateRequest request, Path outFile) throws CommandLineOperationException, InterruptedException { private Path createKeyfile(CertificateRequest request, Path outFile)
throws CommandLineOperationException, InterruptedException {
Path keyFile = outFile.toAbsolutePath(); Path keyFile = outFile.toAbsolutePath();
LOGGER.atDebug().log("Writing new certificate key to {}", keyFile); LOGGER.atDebug().log("Writing new certificate key to {}", keyFile);
try { try {
StartedProcess keygenProc = new ProcessExecutor().command(resolveOpenSSL(), "genrsa", "-out", keyFile.toString(), "-passout", "env:KEY_PASS", Integer.toString(request.getRequestedKeyLength())).environment("KEY_PASS", request.getOid()).redirectOutput(Slf4jStream.ofCaller().asDebug()).redirectError(Slf4jStream.ofCaller().asError()).start(); StartedProcess keygenProc = new ProcessExecutor()
.command(
resolveOpenSSL(),
"genrsa",
"-out",
keyFile.toString(),
"-passout",
"env:KEY_PASS",
Integer.toString(request.getRequestedKeyLength())
)
.environment("KEY_PASS", request.getOid())
.redirectOutput(Slf4jStream.ofCaller().asDebug())
.redirectError(Slf4jStream.ofCaller().asError())
.start();
keygenProc.getFuture().get(); keygenProc.getFuture().get();
} catch (IOException e) { } catch (IOException e) {
throw new CommandLineOperationException("Failure running OpenSSL keygen command.", e); throw new CommandLineOperationException("Failure running OpenSSL keygen command.", e);
@ -90,12 +111,36 @@ public class OpenSSLCertificateCreator {
return keyFile; return keyFile;
} }
private Path createCertificate(CertificateRequest request, Path keyFile, Path outFile) throws CommandLineOperationException, InterruptedException { private Path createCertificate(CertificateRequest request, Path keyFile, Path outFile)
throws CommandLineOperationException, InterruptedException {
LOGGER.atDebug().log("Writing new certificate file {}", outFile); LOGGER.atDebug().log("Writing new certificate file {}", outFile);
String certSubject = buildSubjectArg(request); String certSubject = buildSubjectArg(request);
try { try {
StartedProcess certGenProc = new ProcessExecutor().command(resolveOpenSSL(), "req", "-new", "-passin", "env:KEY_PASS", "-key", keyFile.toString(), "-sha256", "-days", Integer.toString(request.getRequestedValidityDays()), "-out", outFile.toString(), "-passout", "env:KEY_PASS", "-utf8", "-subj", certSubject).environment("KEY_PASS", request.getOid()).redirectOutput(Slf4jStream.ofCaller().asDebug()).redirectError(Slf4jStream.ofCaller().asError()).start(); StartedProcess certGenProc = new ProcessExecutor()
.command(
resolveOpenSSL(),
"req",
"-new",
"-passin",
"env:KEY_PASS",
"-key",
keyFile.toString(),
"-sha256",
"-days",
Integer.toString(request.getRequestedValidityDays()),
"-out",
outFile.toString(),
"-passout",
"env:KEY_PASS",
"-utf8",
"-subj",
certSubject
)
.environment("KEY_PASS", request.getOid())
.redirectOutput(Slf4jStream.ofCaller().asDebug())
.redirectError(Slf4jStream.ofCaller().asError())
.start();
certGenProc.getFuture().get(); certGenProc.getFuture().get();
} catch (IOException e) { } catch (IOException e) {
throw new CommandLineOperationException("Failure running OpenSSL req command.", e); throw new CommandLineOperationException("Failure running OpenSSL req command.", e);
@ -105,14 +150,16 @@ public class OpenSSLCertificateCreator {
return outFile; return outFile;
} }
private Path signCertificate(CertificateRequest request, Path caCert, Path caKey, Path csrFile) throws CommandLineOperationException, InterruptedException { private Path signCertificate(CertificateRequest request, Path caCert, Path caKey, Path csrFile)
throws CommandLineOperationException, InterruptedException {
Path outFile = csrFile.resolveSibling(csrFile.getFileName().toString().replace(".csr", ".crt")); Path outFile = csrFile.resolveSibling(csrFile.getFileName().toString().replace(".csr", ".crt"));
LOGGER.atDebug().log("Writing new signed certificate file {}", outFile); LOGGER.atDebug().log("Writing new signed certificate file {}", outFile);
Path extFile = csrFile.resolveSibling(csrFile.getFileName().toString().replace(".csr", ".ext")); Path extFile = csrFile.resolveSibling(csrFile.getFileName().toString().replace(".csr", ".ext"));
try { try {
String extContent = CSR_EXT_TEMPLATE; String extContent = CSR_EXT_TEMPLATE;
List<String> altNames = Optional.ofNullable(request.getExtension()) List<String> altNames = Optional
.ofNullable(request.getExtension())
.map(CertificateRequestExtension::getAlternativeNames) .map(CertificateRequestExtension::getAlternativeNames)
.orElse(List.of()); .orElse(List.of());
if (!altNames.isEmpty()) { if (!altNames.isEmpty()) {
@ -124,13 +171,40 @@ public class OpenSSLCertificateCreator {
} }
LOGGER.debug("Writing extension file content: \n {}", extContent); LOGGER.debug("Writing extension file content: \n {}", extContent);
Files.writeString(extFile, extContent, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); Files.writeString(
extFile,
extContent,
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING
);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
try { try {
StartedProcess certGenProc = new ProcessExecutor().command(resolveOpenSSL(), "x509", "-req", "-days", Integer.toString(request.getRequestedValidityDays()), "-in", csrFile.toString(), "-CA", caCert.toString(), "-CAkey", caKey.toString(), "-CAcreateserial", "-out", outFile.toString(), "-extfile", extFile.toString()).redirectOutput(Slf4jStream.ofCaller().asDebug()).redirectError(Slf4jStream.ofCaller().asError()).start(); StartedProcess certGenProc = new ProcessExecutor()
.command(
resolveOpenSSL(),
"x509",
"-req",
"-days",
Integer.toString(request.getRequestedValidityDays()),
"-in",
csrFile.toString(),
"-CA",
caCert.toString(),
"-CAkey",
caKey.toString(),
"-CAcreateserial",
"-out",
outFile.toString(),
"-extfile",
extFile.toString()
)
.redirectOutput(Slf4jStream.ofCaller().asDebug())
.redirectError(Slf4jStream.ofCaller().asError())
.start();
certGenProc.getFuture().get(); certGenProc.getFuture().get();
} catch (IOException e) { } catch (IOException e) {
throw new CommandLineOperationException("Failure running OpenSSL x509 command.", e); throw new CommandLineOperationException("Failure running OpenSSL x509 command.", e);

View file

@ -1,14 +1,13 @@
package de.mlessmann.certassist.openssl; package de.mlessmann.certassist.openssl;
import de.mlessmann.certassist.DeleteRecursiveFileVisitor; import static org.slf4j.LoggerFactory.getLogger;
import org.slf4j.Logger;
import de.mlessmann.certassist.DeleteRecursiveFileVisitor;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Set; import java.util.Set;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
public class OpenSSLCertificateResult implements AutoCloseable { public class OpenSSLCertificateResult implements AutoCloseable {

View file

@ -20,7 +20,13 @@ public class TestOpenSSLCertificateCreator {
@Test @Test
void testCertificateCreation() throws Exception { void testCertificateCreation() throws Exception {
CertificateRequest certRequest = CertificateRequest.builder().commonName("test.home").type(RequestType.STANDALONE_CERTIFICATE).subject(CertificateSubject.builder().country("DE").state("SH").locality("HH").organization("Crazy-Cats")).extension(CertificateRequestExtension.builder().alternativeNames("test2.home", "test3.home")).build(); CertificateRequest certRequest = CertificateRequest
.builder()
.commonName("test.home")
.type(RequestType.STANDALONE_CERTIFICATE)
.subject(CertificateSubject.builder().country("DE").state("SH").locality("HH").organization("Crazy-Cats"))
.extension(CertificateRequestExtension.builder().alternativeNames("test2.home", "test3.home"))
.build();
try (var cert = openSSLCertificateCreator.createCertificate(certRequest)) { try (var cert = openSSLCertificateCreator.createCertificate(certRequest)) {
System.out.println("Certificate created: " + cert); System.out.println("Certificate created: " + cert);