diff --git a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/ArtifactRequestCreationProcessor.kt b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/ArtifactRequestCreationProcessor.kt index 05d3629d..99cb1e81 100644 --- a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/ArtifactRequestCreationProcessor.kt +++ b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/ArtifactRequestCreationProcessor.kt @@ -36,15 +36,17 @@ class ArtifactRequestCreationProcessor : Processor { LOG.debug("[IN] ${this::class.java.simpleName}") } ArtifactRequestMessageBuilder().run { - exchange.getProperty(ARTIFACT_URI_PROPERTY)?.let { - if (it is URI) { - it - } else { - URI.create(it.toString()) + exchange + .getProperty(ARTIFACT_URI_PROPERTY) + ?.let { + if (it is URI) { + it + } else { + URI.create(it.toString()) + } + }?.let { + _requestedArtifact_(it) } - }?.let { - _requestedArtifact_(it) - } let { if (LOG.isDebugEnabled) { LOG.debug("Serialisation header: {}", SERIALIZER.serialize(it.build())) diff --git a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/ContractRequestCreationProcessor.kt b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/ContractRequestCreationProcessor.kt index 904ebfc9..6cfda53a 100644 --- a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/ContractRequestCreationProcessor.kt +++ b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/ContractRequestCreationProcessor.kt @@ -71,8 +71,7 @@ class ContractRequestCreationProcessor : Processor { ._action_(listOf(Action.USE)) .build() ) - ) - .build() + ).build() SERIALIZER.serialize(contractRequest).let { if (LOG.isDebugEnabled) LOG.debug("Serialization body: {}", it) exchange.message.body = it diff --git a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/UsageControlMaps.kt b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/UsageControlMaps.kt index b82496ea..3e577431 100644 --- a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/UsageControlMaps.kt +++ b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/UsageControlMaps.kt @@ -37,13 +37,12 @@ object UsageControlMaps { fun getExchangePeerIdentity(exchange: Exchange): String? = exchangePeerIdentityMap[exchange] - fun getExchangeContract(exchange: Exchange): ContractAgreement? { - return exchangePeerIdentityMap[exchange]?.let { identity -> + fun getExchangeContract(exchange: Exchange): ContractAgreement? = + exchangePeerIdentityMap[exchange]?.let { identity -> peerContracts[identity]?.let { uri -> contractMap[uri] ?: throw RuntimeException("Contract $uri is not available!") } } - } fun addContractAgreement(contractAgreement: ContractAgreement) { contractMap[contractAgreement.id] = contractAgreement diff --git a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/multipart/MultiPartStringParser.kt b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/multipart/MultiPartStringParser.kt index 1447aae2..68e30095 100644 --- a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/multipart/MultiPartStringParser.kt +++ b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/camel/processors/multipart/MultiPartStringParser.kt @@ -29,61 +29,62 @@ import java.io.InputStream import java.io.InputStreamReader import java.nio.charset.StandardCharsets -class MultiPartStringParser internal constructor(private val multipartInput: InputStream) : - UploadContext { - private var boundary: String? = null - var header: String? = null - var payload: InputStream? = null - var payloadContentType: String? = null +class MultiPartStringParser internal constructor( + private val multipartInput: InputStream +) : UploadContext { + private var boundary: String? = null + var header: String? = null + var payload: InputStream? = null + var payloadContentType: String? = null - override fun getCharacterEncoding(): String = StandardCharsets.UTF_8.name() + override fun getCharacterEncoding(): String = StandardCharsets.UTF_8.name() - @Deprecated( - "Deprecated in favor of contentLength(), see parent class org.apache.commons.fileupload.UploadContext", - ReplaceWith("contentLength()") - ) - override fun getContentLength() = -1 + @Deprecated( + "Deprecated in favor of contentLength(), see parent class org.apache.commons.fileupload.UploadContext", + ReplaceWith("contentLength()") + ) + override fun getContentLength() = -1 - override fun getContentType() = "multipart/form-data, boundary=$boundary" + override fun getContentType() = "multipart/form-data, boundary=$boundary" - override fun getInputStream() = multipartInput + override fun getInputStream() = multipartInput - override fun contentLength() = -1L + override fun contentLength() = -1L - companion object { - private val LOG = LoggerFactory.getLogger(MultiPartStringParser::class.java) - } + companion object { + private val LOG = LoggerFactory.getLogger(MultiPartStringParser::class.java) + } - init { - multipartInput.mark(10240) - BufferedReader(InputStreamReader(multipartInput, StandardCharsets.UTF_8)).use { reader -> - val boundaryLine = - reader.readLine() - ?: throw IOException( - "Message body appears to be empty, expected multipart boundary." - ) - boundary = boundaryLine.substring(2).trim { it <= ' ' } - multipartInput.reset() - for (i in FileUpload(DiskFileItemFactory()).parseRequest(this)) { - val fieldName = i.fieldName - if (LOG.isTraceEnabled) { - LOG.trace("Found multipart field with name \"{}\"", fieldName) + init { + multipartInput.mark(10240) + BufferedReader(InputStreamReader(multipartInput, StandardCharsets.UTF_8)).use { reader -> + val boundaryLine = + reader.readLine() + ?: throw IOException( + "Message body appears to be empty, expected multipart boundary." + ) + boundary = boundaryLine.substring(2).trim { it <= ' ' } + multipartInput.reset() + for (i in FileUpload(DiskFileItemFactory()).parseRequest(this)) { + val fieldName = i.fieldName + if (LOG.isTraceEnabled) { + LOG.trace("Found multipart field with name \"{}\"", fieldName) + } + if (MultiPartConstants.MULTIPART_HEADER == fieldName) { + header = i.string + if (LOG.isDebugEnabled) { + LOG.debug("Found header:\n{}", header) } - if (MultiPartConstants.MULTIPART_HEADER == fieldName) { - header = i.string - if (LOG.isDebugEnabled) { - LOG.debug("Found header:\n{}", header) - } - } else if (MultiPartConstants.MULTIPART_PAYLOAD == fieldName) { - payload = i.inputStream - payloadContentType = i.contentType - if (LOG.isDebugEnabled) { - LOG.debug("Found body with Content-Type \"{}\"", payloadContentType) - } - } else { - throw IOException("Unknown multipart field name detected: $fieldName") + } else if (MultiPartConstants.MULTIPART_PAYLOAD == fieldName) { + payload = i.inputStream + payloadContentType = i.contentType + if (LOG.isDebugEnabled) { + LOG.debug("Found body with Content-Type \"{}\"", payloadContentType) } + } else { + throw IOException("Unknown multipart field name detected: $fieldName") } } } } +} diff --git a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/idscp2/beans/AisecDapsDriverFactoryBean.kt b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/idscp2/beans/AisecDapsDriverFactoryBean.kt index 5bcd9f23..8fe3ac10 100644 --- a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/idscp2/beans/AisecDapsDriverFactoryBean.kt +++ b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/idscp2/beans/AisecDapsDriverFactoryBean.kt @@ -46,9 +46,11 @@ class AisecDapsDriverFactoryBean : FactoryBean { var transportCertificatesParameters: SSLContextParameters by BeanSetter { val ks = loadKeyStore( - it.keyManagers.keyStore.resource.let(Paths::get) + it.keyManagers.keyStore.resource + .let(Paths::get) ?: throw RuntimeException("Error loading transport certificates: No KeyStore file provided!"), - it.keyManagers.keyStore.password?.toCharArray() + it.keyManagers.keyStore.password + ?.toCharArray() ?: throw RuntimeException("Error loading transport certificates: No KeyStore password provided!") ) builder.loadTransportCertsFromKeystore(ks) diff --git a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/idscp2/beans/BeanSetter.kt b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/idscp2/beans/BeanSetter.kt index 724b9fa4..30d539c8 100644 --- a/camel-processors/src/main/kotlin/de/fhg/aisec/ids/idscp2/beans/BeanSetter.kt +++ b/camel-processors/src/main/kotlin/de/fhg/aisec/ids/idscp2/beans/BeanSetter.kt @@ -23,13 +23,13 @@ import org.springframework.beans.factory.FactoryBean import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty -class BeanSetter(val setConsumer: (T) -> Unit) : ReadWriteProperty, T> { +class BeanSetter( + val setConsumer: (T) -> Unit +) : ReadWriteProperty, T> { override operator fun getValue( thisRef: FactoryBean, property: KProperty<*> - ): T { - throw UnsupportedOperationException("FactoryBean set-only Builder method") - } + ): T = throw UnsupportedOperationException("FactoryBean set-only Builder method") override operator fun setValue( thisRef: FactoryBean, diff --git a/ids-acme/src/main/kotlin/de/fhg/aisec/ids/acme/AcmeClientService.kt b/ids-acme/src/main/kotlin/de/fhg/aisec/ids/acme/AcmeClientService.kt index dead9cfb..bd9e1d22 100644 --- a/ids-acme/src/main/kotlin/de/fhg/aisec/ids/acme/AcmeClientService.kt +++ b/ids-acme/src/main/kotlin/de/fhg/aisec/ids/acme/AcmeClientService.kt @@ -60,7 +60,10 @@ import java.util.Date // Every day at 3:00 (3 am) // property = [Scheduler.PROPERTY_SCHEDULER_EXPRESSION + "=0 0 3 * * ?"] ) -class AcmeClientService : AcmeClient, Runnable, SslContextFactoryReloadableRegistry { +class AcmeClientService : + AcmeClient, + Runnable, + SslContextFactoryReloadableRegistry { @Autowired private lateinit var settings: Settings @@ -82,9 +85,7 @@ class AcmeClientService : AcmeClient, Runnable, SslContextFactoryReloadableRegis } } - override fun getChallengeAuthorization(challenge: String): String? { - return challengeMap[challenge] - } + override fun getChallengeAuthorization(challenge: String): String? = challengeMap[challenge] private fun ensureKeys(targetDirectory: Path) { listOf("acme.key", "domain.key").forEach { keyFile -> @@ -109,7 +110,8 @@ class AcmeClientService : AcmeClient, Runnable, SslContextFactoryReloadableRegis private fun getACMEKeyPair(targetDirectory: Path): KeyPair { try { - Files.newBufferedReader(targetDirectory.resolve("acme.key"), StandardCharsets.UTF_8) + Files + .newBufferedReader(targetDirectory.resolve("acme.key"), StandardCharsets.UTF_8) .use { fileReader -> return KeyPairUtils.readKeyPair(fileReader) } @@ -190,8 +192,7 @@ class AcmeClientService : AcmeClient, Runnable, SslContextFactoryReloadableRegis .parallelStream() .map { authorization -> authorization.findChallenge(Http01Challenge.TYPE) - } - .forEach { challenge -> + }.forEach { challenge -> challengeMap[challenge.token] = challenge.authorization try { // solve the challenge @@ -222,21 +223,21 @@ class AcmeClientService : AcmeClient, Runnable, SslContextFactoryReloadableRegis val timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss.SSS")) try { - Files.newBufferedReader( - targetDirectory.resolve("domain.key"), - StandardCharsets.UTF_8 - ) - .use { keyReader -> - Files.newBufferedWriter( - targetDirectory.resolve("csr_ $timestamp.csr"), - StandardCharsets.UTF_8 - ) - .use { csrWriter -> - Files.newBufferedWriter( - targetDirectory.resolve("cert-chain_$timestamp.crt"), - StandardCharsets.UTF_8 - ) - .use { chainWriter -> + Files + .newBufferedReader( + targetDirectory.resolve("domain.key"), + StandardCharsets.UTF_8 + ).use { keyReader -> + Files + .newBufferedWriter( + targetDirectory.resolve("csr_ $timestamp.csr"), + StandardCharsets.UTF_8 + ).use { csrWriter -> + Files + .newBufferedWriter( + targetDirectory.resolve("cert-chain_$timestamp.crt"), + StandardCharsets.UTF_8 + ).use { chainWriter -> val domainKeyPair = KeyPairUtils.readKeyPair(keyReader) val csrb = CSRBuilder() diff --git a/ids-acme/src/main/kotlin/de/fhg/aisec/ids/acme/provider/BoulderAcmeProvider.kt b/ids-acme/src/main/kotlin/de/fhg/aisec/ids/acme/provider/BoulderAcmeProvider.kt index 11b83cc6..78aefd2b 100644 --- a/ids-acme/src/main/kotlin/de/fhg/aisec/ids/acme/provider/BoulderAcmeProvider.kt +++ b/ids-acme/src/main/kotlin/de/fhg/aisec/ids/acme/provider/BoulderAcmeProvider.kt @@ -32,9 +32,7 @@ import java.util.regex.Pattern * @see [Boulder](https://github.com/letsencrypt/boulder) */ class BoulderAcmeProvider : AbstractAcmeProvider() { - override fun accepts(serverUri: URI): Boolean { - return "acme" == serverUri.scheme && "boulder" == serverUri.host - } + override fun accepts(serverUri: URI): Boolean = "acme" == serverUri.scheme && "boulder" == serverUri.host override fun resolve(serverUri: URI): URL { try { diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/LazyProducer.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/LazyProducer.kt index f3eb06d8..3b2b24a9 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/LazyProducer.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/LazyProducer.kt @@ -19,7 +19,9 @@ */ package de.fhg.aisec.ids.api -class LazyProducer(generator: () -> T) : () -> T { +class LazyProducer( + generator: () -> T +) : () -> T { private val value: T by lazy(generator) override operator fun invoke() = value diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/Result.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/Result.kt index 2c410577..9ae7d484 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/Result.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/Result.kt @@ -20,4 +20,7 @@ package de.fhg.aisec.ids.api /** Generic result of an API call. */ -open class Result(var isSuccessful: Boolean = true, var message: String = "ok") +open class Result( + var isSuccessful: Boolean = true, + var message: String = "ok" +) diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/RunCommand.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/RunCommand.kt index ddf03728..1afcd186 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/RunCommand.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/RunCommand.kt @@ -22,8 +22,8 @@ package de.fhg.aisec.ids.api import java.io.IOException import java.util.concurrent.TimeUnit -fun String.runCommand(): String? { - return try { +fun String.runCommand(): String? = + try { val parts = this.split("\\s".toRegex()) val proc = ProcessBuilder(*parts.toTypedArray()) @@ -36,4 +36,3 @@ fun String.runCommand(): String? { e.printStackTrace() null } -} diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/cm/ApplicationContainer.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/cm/ApplicationContainer.kt index af34dd53..bcf33dac 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/cm/ApplicationContainer.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/cm/ApplicationContainer.kt @@ -71,8 +71,8 @@ class ApplicationContainer { var labels: Map = emptyMap() var volumes: List = emptyList() - override fun toString(): String { - return ( + override fun toString(): String = + ( "ApplicationContainer [id=" + id + ", image=" + @@ -97,5 +97,4 @@ class ApplicationContainer { description + "]" ) - } } diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPClientEndpoint.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPClientEndpoint.kt index 43e94e1f..6f8dc14a 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPClientEndpoint.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPClientEndpoint.kt @@ -30,7 +30,5 @@ class IDSCPClientEndpoint { var attestationResult: RatResult? = null var endpointKey: String? = null - override fun toString(): String { - return "IDSCPEndpoint [endpoint_identifier=$endpointIdentifier]" - } + override fun toString(): String = "IDSCPEndpoint [endpoint_identifier=$endpointIdentifier]" } diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPIncomingConnection.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPIncomingConnection.kt index c4e1e4b1..c71db72a 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPIncomingConnection.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPIncomingConnection.kt @@ -32,15 +32,14 @@ class IDSCPIncomingConnection { var metaData: String? = null private var dynamicAttributeToken: String? = null - override fun toString(): String { - return ( + override fun toString(): String = + ( "IDSCPConnection [endpoint_identifier=" + endpointIdentifier + ", attestationResult=" + attestationResult + "]" ) - } fun setDynamicAttributeToken(dynamicAttributeToken: String?) { this.dynamicAttributeToken = dynamicAttributeToken diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPOutgoingConnection.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPOutgoingConnection.kt index 720f4aff..622ce3c4 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPOutgoingConnection.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/IDSCPOutgoingConnection.kt @@ -32,7 +32,5 @@ class IDSCPOutgoingConnection { var attestationResult: RatResult? = null var metaData: String? = null - override fun toString(): String { - return "IDSCPOutgoingConnection [endpoint_identifier=$endpointIdentifier]" - } + override fun toString(): String = "IDSCPOutgoingConnection [endpoint_identifier=$endpointIdentifier]" } diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/RatResult.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/RatResult.kt index d4b969ca..2a4f0ff4 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/RatResult.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/conm/RatResult.kt @@ -24,7 +24,10 @@ package de.fhg.aisec.ids.api.conm * * @author Julian Schuette (julian.schuette@aisec.fraunhofer.de) */ -class RatResult(val status: Status, reason: String?) { +class RatResult( + val status: Status, + reason: String? +) { enum class Status { FAILED, SUCCESS diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/CounterExample.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/CounterExample.kt index 4464233a..3087c011 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/CounterExample.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/CounterExample.kt @@ -25,10 +25,9 @@ abstract class CounterExample { var steps: List? = null protected set - override fun toString(): String { - return """ - Explanation: $explanation - ${java.lang.String.join("\n|-- ", steps)} - """.trimIndent() - } + override fun toString(): String = + """ + Explanation: $explanation + ${java.lang.String.join("\n|-- ", steps)} + """.trimIndent() } diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/RouteVerificationProof.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/RouteVerificationProof.kt index 2504e3c4..db728ca8 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/RouteVerificationProof.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/RouteVerificationProof.kt @@ -36,7 +36,9 @@ import java.util.ArrayList * * @author Julian Schuette (julian.schuette@aisec.fraunhofer.de) */ -class RouteVerificationProof(routeId: String?) { +class RouteVerificationProof( + routeId: String? +) { val routeId: String var proofTimeNanos: Long = 0 var isValid = true @@ -45,7 +47,12 @@ class RouteVerificationProof(routeId: String?) { override fun toString(): String { val sb = StringBuilder() - sb.append("Proof for ").append(query).append(" is ").append(if (isValid) "VALID" else "INVALID").append("\n") + sb + .append("Proof for ") + .append(query) + .append(" is ") + .append(if (isValid) "VALID" else "INVALID") + .append("\n") .append("Example flows violating policy:\n") for (ce in counterExamples) { sb.append("|-- ").append(ce.toString()).append("\n\n") diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/Edge.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/Edge.kt index 3b0b37fb..519baa11 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/Edge.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/Edge.kt @@ -19,4 +19,7 @@ */ package de.fhg.aisec.ids.api.router.graph -data class Edge(val source: String, val target: String) +data class Edge( + val source: String, + val target: String +) diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/GraphData.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/GraphData.kt index 25cd2e56..703e14ee 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/GraphData.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/GraphData.kt @@ -31,11 +31,7 @@ class GraphData { links.add(edge) } - fun getNodes(): Set { - return nodes - } + fun getNodes(): Set = nodes - fun getLinks(): Set { - return links - } + fun getLinks(): Set = links } diff --git a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/Node.kt b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/Node.kt index 3c669a61..3ee4216d 100644 --- a/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/Node.kt +++ b/ids-api/src/main/kotlin/de/fhg/aisec/ids/api/router/graph/Node.kt @@ -19,7 +19,11 @@ */ package de.fhg.aisec.ids.api.router.graph -data class Node(val name: String, val action: String, val type: NodeType) { +data class Node( + val name: String, + val action: String, + val type: NodeType +) { enum class NodeType { EntryNode, Node, diff --git a/ids-connector/src/main/kotlin/de/fhg/aisec/ids/ConnectorConfiguration.kt b/ids-connector/src/main/kotlin/de/fhg/aisec/ids/ConnectorConfiguration.kt index 00cd0dad..3c3d23aa 100644 --- a/ids-connector/src/main/kotlin/de/fhg/aisec/ids/ConnectorConfiguration.kt +++ b/ids-connector/src/main/kotlin/de/fhg/aisec/ids/ConnectorConfiguration.kt @@ -59,8 +59,8 @@ class ConnectorConfiguration { private lateinit var senderAgent: String @Bean - fun configureIdscp2(): CommandLineRunner { - return CommandLineRunner { + fun configureIdscp2(): CommandLineRunner = + CommandLineRunner { Utils.issuerProducer = LazyProducer { if (connectorUrl.isNotBlank()) { @@ -97,44 +97,40 @@ class ConnectorConfiguration { UsageControlMaps.setPeerContract(connection.peerDat.identity, transferContract) } } - } @Bean - fun listBeans(ctx: ApplicationContext): CommandLineRunner { - return CommandLineRunner { + fun listBeans(ctx: ApplicationContext): CommandLineRunner = + CommandLineRunner { if (TrustedConnector.LOG.isDebugEnabled) { ctx.beanDefinitionNames.sorted().forEach { TrustedConnector.LOG.debug("Loaded bean: {}", it) } } } - } @Bean - fun listContainers(ctx: ApplicationContext): CommandLineRunner { - return CommandLineRunner { + fun listContainers(ctx: ApplicationContext): CommandLineRunner = + CommandLineRunner { if (TrustedConnector.LOG.isDebugEnabled) { cml?.list(false)?.forEach { TrustedConnector.LOG.debug("Container: {}", it.names) } } } - } @Bean - fun showConnectorProfile(ctx: ApplicationContext): CommandLineRunner { - return CommandLineRunner { + fun showConnectorProfile(ctx: ApplicationContext): CommandLineRunner = + CommandLineRunner { if (TrustedConnector.LOG.isDebugEnabled) { im.connector?.let { TrustedConnector.LOG.debug("Connector profile:\n{}", im.connectorAsJsonLd) } ?: TrustedConnector.LOG.debug("No connector profile stored yet.") } } - } @Bean - fun showCamelInfo(ctx: ApplicationContext): CommandLineRunner { - return CommandLineRunner { + fun showCamelInfo(ctx: ApplicationContext): CommandLineRunner = + CommandLineRunner { val routes = rm.routes for (route in routes) { @@ -147,5 +143,4 @@ class ConnectorConfiguration { TrustedConnector.LOG.debug("Component: {}", component.bundle) } } - } } diff --git a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/ContainerManagerService.kt b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/ContainerManagerService.kt index 169fe841..fe871968 100644 --- a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/ContainerManagerService.kt +++ b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/ContainerManagerService.kt @@ -60,9 +60,7 @@ class ContainerManagerService : ContainerManager { } } - override fun list(onlyRunning: Boolean): List { - return containerManager.list(onlyRunning) - } + override fun list(onlyRunning: Boolean): List = containerManager.list(onlyRunning) override fun wipe(containerID: String) { try { diff --git a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/docker/DockerCM.kt b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/docker/DockerCM.kt index 8b1d8372..c2824eb6 100644 --- a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/docker/DockerCM.kt +++ b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/docker/DockerCM.kt @@ -167,9 +167,7 @@ class DockerCM : ContainerManager { } } - private fun getImages(filters: Map>?): Images { - return dockerClient.images().filter(filters ?: emptyMap()) - } + private fun getImages(filters: Map>?): Images = dockerClient.images().filter(filters ?: emptyMap()) override fun list(onlyRunning: Boolean): List { val jsonArrayToList = { jsonValue: JsonValue? -> @@ -217,8 +215,7 @@ class DockerCM : ContainerManager { LOG.warn("Error while resolving ip address \"$ip\"", x) null } - } - .toList() + }.toList() app.size = "${humanReadableByteCount((c["SizeRw"] ?: 0).toString().toLong())} RW (data), " + "${humanReadableByteCount((c["SizeRootFs"] ?: 0).toString().toLong())} RO (layers)" @@ -239,8 +236,7 @@ class DockerCM : ContainerManager { } else { e.key } - } - .toList() + }.toList() app.names = name if (running) { app.uptime = @@ -269,17 +265,15 @@ class DockerCM : ContainerManager { ) return@map null } - } - .filterNotNull() + }.filterNotNull() .toList() } - private fun getContainer(containerID: String): Container { - return getContainerSequence(true, mapOf("id" to listOf(containerID))).firstOrNull() + private fun getContainer(containerID: String): Container = + getContainerSequence(true, mapOf("id" to listOf(containerID))).firstOrNull() ?: throw NoContainerExistsException( "The container with ID $containerID has not been found!" ) - } private fun getImage(container: Container) = getImages(mapOf("reference" to listOf(container.getString("Image")))).firstOrNull() @@ -357,8 +351,7 @@ class DockerCM : ContainerManager { "(?:((?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}" + "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])):)?" + "([0-9]+):([0-9]+)(?:/(tcp|udp))?" - ) - .toRegex() + ).toRegex() for (port in app.ports) { val match = portRegex.matchEntire(port) if (match == null) { @@ -437,9 +430,8 @@ class DockerCM : ContainerManager { * * @param containerID The ID of the container to query labels from */ - override fun getMetadata(containerID: String): Map { - return getContainer(containerID).inspect().getJsonObject("Config").getJsonObject("Labels") - } + override fun getMetadata(containerID: String): Map = + getContainer(containerID).inspect().getJsonObject("Config").getJsonObject("Labels") override fun setIpRule( containerID: String, @@ -458,9 +450,7 @@ class DockerCM : ContainerManager { * @param containerID container id * @return container information */ - override fun inspectContainer(containerID: String): String { - return getContainer(containerID).inspect().toString() - } + override fun inspectContainer(containerID: String): String = getContainer(containerID).inspect().toString() /** Returns the version of docker on the system */ override val version: String diff --git a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/dummy/DummyCM.kt b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/dummy/DummyCM.kt index bb756303..73b89208 100644 --- a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/dummy/DummyCM.kt +++ b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/dummy/DummyCM.kt @@ -31,9 +31,7 @@ import de.fhg.aisec.ids.api.cm.Protocol * @author Julian Schütte (julian.schuette@aisec.fraunhofer.de) */ class DummyCM : ContainerManager { - override fun list(onlyRunning: Boolean): List { - return ArrayList() - } + override fun list(onlyRunning: Boolean): List = ArrayList() override fun wipe(containerID: String) {} @@ -46,13 +44,9 @@ class DummyCM : ContainerManager { override fun restartContainer(containerID: String) {} - override fun pullImage(app: ApplicationContainer): String? { - return null - } + override fun pullImage(app: ApplicationContainer): String? = null - override fun getMetadata(containerID: String): Map { - return HashMap() - } + override fun getMetadata(containerID: String): Map = HashMap() override fun setIpRule( containerID: String, @@ -65,9 +59,7 @@ class DummyCM : ContainerManager { ) { } - override fun inspectContainer(containerID: String): String { - return "" - } + override fun inspectContainer(containerID: String): String = "" override val version: String get() = "no cmld installed" diff --git a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXCM.kt b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXCM.kt index 51ab254c..6a91c98b 100644 --- a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXCM.kt +++ b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXCM.kt @@ -54,20 +54,22 @@ import kotlin.math.abs */ class TrustXCM @JvmOverloads - constructor(socket: String = SOCKET) : ContainerManager { + constructor( + socket: String = SOCKET + ) : ContainerManager { private var socketThread: TrustmeUnixSocketThread = TrustmeUnixSocketThread(socket) private var responseHandler: TrustmeUnixSocketResponseHandler = TrustmeUnixSocketResponseHandler() private val formatter = - DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + DateTimeFormatter + .ofLocalizedDateTime(FormatStyle.SHORT) .withLocale(Locale.GERMANY) .withZone(ZoneId.systemDefault()) - private fun stateToStatusString(state: ContainerState): ContainerStatus { - return when (state) { + private fun stateToStatusString(state: ContainerState): ContainerStatus = + when (state) { ContainerState.RUNNING, ContainerState.SETUP -> ContainerStatus.RUNNING else -> ContainerStatus.EXITED } - } override fun list(onlyRunning: Boolean): List { LOG.debug("Starting list containers") @@ -152,9 +154,7 @@ class TrustXCM sendCommand(ControllerToDaemon.Command.CONTAINER_START) } - override fun pullImage(app: ApplicationContainer): String? { - return null - } + override fun pullImage(app: ApplicationContainer): String? = null override fun inspectContainer(containerID: String): String? { // TODO Auto-generated method stub @@ -235,9 +235,7 @@ class TrustXCM } @Throws(InvalidProtocolBufferException::class) - private fun parseResponse(response: ByteArray?): DaemonToController { - return DaemonToController.parseFrom(response) - } + private fun parseResponse(response: ByteArray?): DaemonToController = DaemonToController.parseFrom(response) companion object { private val LOG = LoggerFactory.getLogger(TrustXCM::class.java) diff --git a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/ChangeRequest.kt b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/ChangeRequest.kt index 7ab7bd34..38f61316 100644 --- a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/ChangeRequest.kt +++ b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/ChangeRequest.kt @@ -21,7 +21,11 @@ package de.fhg.aisec.ids.comm.unixsocket import jnr.unixsocket.UnixSocketChannel -class ChangeRequest(var channel: UnixSocketChannel, var type: Int, var ops: Int) { +class ChangeRequest( + var channel: UnixSocketChannel, + var type: Int, + var ops: Int +) { companion object { const val REGISTER = 1 const val CHANGEOPS = 2 diff --git a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/TrustmeUnixSocketThread.kt b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/TrustmeUnixSocketThread.kt index 3355df66..7f6340e4 100644 --- a/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/TrustmeUnixSocketThread.kt +++ b/ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/TrustmeUnixSocketThread.kt @@ -33,7 +33,9 @@ import java.util.Collections import java.util.LinkedList import java.util.concurrent.TimeUnit -class TrustmeUnixSocketThread(private val socket: String) : Runnable { +class TrustmeUnixSocketThread( + private val socket: String +) : Runnable { // The selector we'll be monitoring private val selector: Selector private val lengthBuffer = ByteBuffer.allocate(4) @@ -315,14 +317,10 @@ class TrustmeUnixSocketThread(private val socket: String) : Runnable { // initialize the selector @Throws(IOException::class) - private fun initSelector(): Selector { - return NativeSelectorProvider.getInstance().openSelector() - } + private fun initSelector(): Selector = NativeSelectorProvider.getInstance().openSelector() // get the channel - private fun getChannel(k: SelectionKey): UnixSocketChannel { - return k.channel() as UnixSocketChannel - } + private fun getChannel(k: SelectionKey): UnixSocketChannel = k.channel() as UnixSocketChannel companion object { private val LOG = LoggerFactory.getLogger(TrustmeUnixSocketThread::class.java) diff --git a/ids-container-manager/src/test/kotlin/de/fhg/aisec/ids/cm/impl/trustx/ServerDataEvent.kt b/ids-container-manager/src/test/kotlin/de/fhg/aisec/ids/cm/impl/trustx/ServerDataEvent.kt index dfe1ff89..3d7ab4c7 100644 --- a/ids-container-manager/src/test/kotlin/de/fhg/aisec/ids/cm/impl/trustx/ServerDataEvent.kt +++ b/ids-container-manager/src/test/kotlin/de/fhg/aisec/ids/cm/impl/trustx/ServerDataEvent.kt @@ -21,4 +21,8 @@ package de.fhg.aisec.ids.cm.impl.trustx import jnr.unixsocket.UnixSocketChannel -internal class ServerDataEvent(var server: TrustXMock, var socket: UnixSocketChannel, var data: ByteArray) +internal class ServerDataEvent( + var server: TrustXMock, + var socket: UnixSocketChannel, + var data: ByteArray +) diff --git a/ids-container-manager/src/test/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXMock.kt b/ids-container-manager/src/test/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXMock.kt index c01a8362..31bf0279 100644 --- a/ids-container-manager/src/test/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXMock.kt +++ b/ids-container-manager/src/test/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXMock.kt @@ -32,7 +32,10 @@ import java.nio.channels.SelectionKey import java.nio.channels.Selector import java.util.LinkedList -class TrustXMock(private var socket: String, private var handler: TrustXMockHandler) : Runnable { +class TrustXMock( + private var socket: String, + private var handler: TrustXMockHandler +) : Runnable { private var channel: UnixServerSocketChannel? = null // The selector we'll be monitoring @@ -193,9 +196,7 @@ class TrustXMock(private var socket: String, private var handler: TrustXMockHand } // get the channel - private fun getChannel(k: SelectionKey): UnixSocketChannel { - return k.channel() as UnixSocketChannel - } + private fun getChannel(k: SelectionKey): UnixSocketChannel = k.channel() as UnixSocketChannel companion object { private val LOG = LoggerFactory.getLogger(TrustXMock::class.java) diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/CamelInterceptor.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/CamelInterceptor.kt index 920c7380..18516877 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/CamelInterceptor.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/CamelInterceptor.kt @@ -49,9 +49,7 @@ class CamelInterceptor : InterceptStrategy { node: NamedNode, target: Processor, nextTarget: Processor? - ): Processor { - return PolicyEnforcementPoint(node, target) - } + ): Processor = PolicyEnforcementPoint(node, target) companion object { private lateinit var instance: CamelInterceptor diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/ContractManagerImpl.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/ContractManagerImpl.kt index 21a096a0..3008e58e 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/ContractManagerImpl.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/ContractManagerImpl.kt @@ -68,8 +68,7 @@ class ContractManagerImpl : ContractManager { ContractUtils.DATATYPE_FACTORY.newXMLGregorianCalendar(dateTime.toString()).toString(), ContractUtils.TYPE_DATETIMESTAMP ) - ) - .build() + ).build() } // Add not before (AFTER) usage constraint notBeforeDateTime?.let { dateTime -> @@ -82,8 +81,7 @@ class ContractManagerImpl : ContractManager { ContractUtils.DATATYPE_FACTORY.newXMLGregorianCalendar(dateTime).toString(), ContractUtils.TYPE_DATETIMESTAMP ) - ) - .build() + ).build() } return ContractOfferBuilder() ._contractDate_(contractDate) @@ -99,8 +97,7 @@ class ContractManagerImpl : ContractManager { ._action_(listOf(Action.USE)) ._constraint_( timeConstraints - ) - .build() + ).build() ) } else { // If Docker images have been specified, combine each with the specified time constraints @@ -116,12 +113,10 @@ class ContractManagerImpl : ContractManager { ._rightOperandReference_(it) .build() ) + timeConstraints - ) - .build() + ).build() } } - ) - .build() + ).build() } override fun storeContract( diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/PolicyDecisionPoint.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/PolicyDecisionPoint.kt index e630f52e..5da1b625 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/PolicyDecisionPoint.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/PolicyDecisionPoint.kt @@ -56,7 +56,9 @@ import java.util.concurrent.TimeUnit * @author Julian Schuette (julian.schuette@aisec.fraunhofer.de) */ @Component("idsDataflowControl") -class PolicyDecisionPoint : PDP, PAP { +class PolicyDecisionPoint : + PDP, + PAP { // Convenience val for this thread's LuconEngine instance private val engine: LuconEngine get() = threadEngine.get() @@ -65,7 +67,8 @@ class PolicyDecisionPoint : PDP, PAP { private var routeManager: RouteManager? = null private val transformationCache = - CacheBuilder.newBuilder() + CacheBuilder + .newBuilder() .maximumSize(10000) .expireAfterAccess(1, TimeUnit.DAYS) .build() @@ -134,7 +137,8 @@ class PolicyDecisionPoint : PDP, PAP { // } // sb.append('(').append(capProp.joinToString(", ")).append("),\n") // } - sb.append("once(setof(S, action_service(") + sb + .append("once(setof(S, action_service(") .append(plEndpoint) .append(", S), SC); SC = []),\n") .append("collect_creates_labels(SC, ACraw), set_of(ACraw, Adds),\n") @@ -152,7 +156,8 @@ class PolicyDecisionPoint : PDP, PAP { return } var loaded = false - Files.walk(deployPath) + Files + .walk(deployPath) .filter { Files.isRegularFile(it) && it.toString().endsWith(LUCON_FILE_EXTENSION) } .forEach { if (!loaded) { @@ -366,15 +371,14 @@ class PolicyDecisionPoint : PDP, PAP { LuconEngine.setDefaultPolicy(theory) } - override fun listRules(): List { - return try { + override fun listRules(): List = + try { val rules = this.engine.query("rule(X).", true) rules.map { it.getVarValue("X").toString() }.toList() } catch (e: PrologException) { LOG.error("Prolog error while retrieving rules " + e.message, e) emptyList() } - } override val policy: String get() = this.engine.theory diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/PolicyEnforcementPoint.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/PolicyEnforcementPoint.kt index 0f4d776a..42f22fec 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/PolicyEnforcementPoint.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/PolicyEnforcementPoint.kt @@ -39,8 +39,10 @@ import org.slf4j.LoggerFactory import java.net.URI class PolicyEnforcementPoint - internal constructor(private val destinationNode: NamedNode, target: Processor) : - DelegateAsyncProcessor(target) { + internal constructor( + private val destinationNode: NamedNode, + target: Processor + ) : DelegateAsyncProcessor(target) { /** * The method performs flow control and calls Exchange.setException() when necessary It iterates * through nodes in CamelRoute (, , , , , ...) and launches node diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/CounterExampleImpl.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/CounterExampleImpl.kt index 8ed47292..94d72aee 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/CounterExampleImpl.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/CounterExampleImpl.kt @@ -24,7 +24,9 @@ import alice.tuprolog.Term import de.fhg.aisec.ids.api.router.CounterExample import java.util.LinkedList -class CounterExampleImpl(term: Term) : CounterExample() { +class CounterExampleImpl( + term: Term +) : CounterExample() { init { val traceIterator = (term as Struct).listIterator() val steps = LinkedList() @@ -42,7 +44,8 @@ class CounterExampleImpl(term: Term) : CounterExample() { // appendCSList(sb, explanation) // sb.append("]") // } - sb.append(", which is forbidden by rule \"") + sb + .append(", which is forbidden by rule \"") .append(reasonIterator.next().toString()) .append("\".") this.explanation = sb.toString() diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/LuconEngine.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/LuconEngine.kt index 50766800..f2c759b1 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/LuconEngine.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/LuconEngine.kt @@ -42,7 +42,9 @@ import java.util.regex.Pattern * * @author Julian Schuette (julian.schuette@aisec.fraunhofer.de) */ -class LuconEngine(out: OutputStream?) { +class LuconEngine( + out: OutputStream? +) { private val p: Prolog = Prolog() val theory: String diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/LuconLibrary.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/LuconLibrary.kt index a2befc32..25452507 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/LuconLibrary.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/LuconLibrary.kt @@ -38,7 +38,8 @@ import java.util.concurrent.TimeUnit class LuconLibrary : Library() { @Transient private val regexCache = - CacheBuilder.newBuilder() + CacheBuilder + .newBuilder() .expireAfterAccess(1, TimeUnit.DAYS) .maximumWeight(1e6.toLong()) .weigher { k, _ -> k.length } diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/TuPrologHelper.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/TuPrologHelper.kt index bb5e2bca..8cd528df 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/TuPrologHelper.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/TuPrologHelper.kt @@ -58,13 +58,12 @@ object TuPrologHelper { ) } - fun unquote(s: String): String { - return if (s.length > 2 && s[0] == '\'' && s[s.length - 1] == '\'') { + fun unquote(s: String): String = + if (s.length > 2 && s[0] == '\'' && s[s.length - 1] == '\'') { s.substring(1, s.length - 1) } else if (s.length == 2 && "''" == s) { "" } else { s } - } } diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/DockerImageConstraint.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/DockerImageConstraint.kt index bbfed8cb..95d74bc1 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/DockerImageConstraint.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/DockerImageConstraint.kt @@ -24,7 +24,9 @@ import de.fhg.aisec.ids.dataflowcontrol.CamelInterceptor import java.net.InetAddress import java.net.URI -class DockerImageConstraint(dockerUri: URI) : LuconConstraint { +class DockerImageConstraint( + dockerUri: URI +) : LuconConstraint { private val hash: String private val port: Int diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/LuconContract.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/LuconContract.kt index c12be676..6f0cc169 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/LuconContract.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/LuconContract.kt @@ -34,7 +34,9 @@ import org.slf4j.LoggerFactory import java.net.URI import java.util.Collections -class LuconContract private constructor(contract: ContractAgreement) { +class LuconContract private constructor( + contract: ContractAgreement +) { val permissions = contract.permission.map(::LuconPermission) private val contractId: String = contract.id.toString() diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/LuconPermission.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/LuconPermission.kt index 2e90b735..f0ba8e14 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/LuconPermission.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/LuconPermission.kt @@ -25,7 +25,9 @@ import de.fraunhofer.iais.eis.Constraint import de.fraunhofer.iais.eis.LeftOperand import de.fraunhofer.iais.eis.Permission -class LuconPermission(permission: Permission) { +class LuconPermission( + permission: Permission +) { val constraints: List init { diff --git a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/UsageTimeConstraint.kt b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/UsageTimeConstraint.kt index 96272c4c..66d6ff2a 100644 --- a/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/UsageTimeConstraint.kt +++ b/ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/usagecontrol/UsageTimeConstraint.kt @@ -23,7 +23,9 @@ import de.fraunhofer.iais.eis.BinaryOperator import de.fraunhofer.iais.eis.Constraint import javax.xml.datatype.DatatypeFactory -class UsageTimeConstraint(private val constraint: Constraint) : LuconConstraint { +class UsageTimeConstraint( + private val constraint: Constraint +) : LuconConstraint { private var notAfterDateTime: String? = null private var notBeforeDateTime: String? = null @@ -50,7 +52,9 @@ class UsageTimeConstraint(private val constraint: Constraint) : LuconConstraint } val currentTimestamp = System.currentTimeMillis() val policyTimestamp = - DATATYPE_FACTORY.newXMLGregorianCalendar(rightOperand.value).toGregorianCalendar() + DATATYPE_FACTORY + .newXMLGregorianCalendar(rightOperand.value) + .toGregorianCalendar() .timeInMillis if (constraint.operator == BinaryOperator.BEFORE) { if (currentTimestamp < policyTimestamp) { diff --git a/ids-dataflow-control/src/test/kotlin/de/fhg/aisec/ids/dataflowcontrol/LuconEngineTest.kt b/ids-dataflow-control/src/test/kotlin/de/fhg/aisec/ids/dataflowcontrol/LuconEngineTest.kt index 9576350b..a7c2d019 100644 --- a/ids-dataflow-control/src/test/kotlin/de/fhg/aisec/ids/dataflowcontrol/LuconEngineTest.kt +++ b/ids-dataflow-control/src/test/kotlin/de/fhg/aisec/ids/dataflowcontrol/LuconEngineTest.kt @@ -229,7 +229,8 @@ class LuconEngineTest { val rm = Mockito.mock(RouteManager::class.java) println("------ ROUTE ----------") println(VERIFIABLE_ROUTE) - Mockito.`when`(rm.getRouteAsProlog(ArgumentMatchers.anyString())) + Mockito + .`when`(rm.getRouteAsProlog(ArgumentMatchers.anyString())) .thenReturn(VERIFIABLE_ROUTE) // Create policy decision point and attach to route manager @@ -485,20 +486,28 @@ class LuconEngineTest { sb.append("has_decision(").append(ruleName).append(", allow).\n") sb.append("has_alternativedecision(").append(ruleName).append(", allow).\n") sb.append("receives_label(").append(ruleName).append(").\n") - sb.append("has_target(").append(ruleName).append(", ").append(targetName).append(").\n") - sb.append("has_obligation(") + sb + .append("has_target(") + .append(ruleName) + .append(", ") + .append(targetName) + .append(").\n") + sb + .append("has_obligation(") .append(ruleName) .append(", testObligation") .append(i) .append(").\n") sb.append("service(").append(targetName).append(").\n") sb.append("has_endpoint(").append(targetName).append(", \".*\").\n") - sb.append("creates_label(") + sb + .append("creates_label(") .append(targetName) .append(", ") .append(labelName) .append(").\n") - sb.append("removes_label(") + sb + .append("removes_label(") .append(targetName) .append(", ") .append(labelName) diff --git a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/ConnectionManagerService.kt b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/ConnectionManagerService.kt index 40ef1b63..65cc4a63 100644 --- a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/ConnectionManagerService.kt +++ b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/ConnectionManagerService.kt @@ -58,26 +58,28 @@ class ConnectionManagerService : ConnectionManager { } } - override fun listAvailableEndpoints(): List { - return camelContexts.flatMapTo(mutableSetOf()) { cCtx -> - cCtx.endpointRegistry.values.mapNotNull { ep -> - if (ep is Idscp2ServerEndpoint) { - val baseUri = ep.endpointBaseUri - val matchGroups = - listOf(Regex("(.*?)://(.*?):([0-9]+).*"), Regex("(.*?)://(.*?).*")) - .asSequence().mapNotNull { it.matchEntire(baseUri)?.groupValues }.firstOrNull() - ServerEndpoint( - baseUri, - matchGroups?.get(1) ?: "?", - matchGroups?.get(2) ?: "?", - matchGroups?.get(3) ?: "?" - ) - } else { - null + override fun listAvailableEndpoints(): List = + camelContexts + .flatMapTo(mutableSetOf()) { cCtx -> + cCtx.endpointRegistry.values.mapNotNull { ep -> + if (ep is Idscp2ServerEndpoint) { + val baseUri = ep.endpointBaseUri + val matchGroups = + listOf(Regex("(.*?)://(.*?):([0-9]+).*"), Regex("(.*?)://(.*?).*")) + .asSequence() + .mapNotNull { it.matchEntire(baseUri)?.groupValues } + .firstOrNull() + ServerEndpoint( + baseUri, + matchGroups?.get(1) ?: "?", + matchGroups?.get(2) ?: "?", + matchGroups?.get(3) ?: "?" + ) + } else { + null + } } - } - }.toList() - } + }.toList() // TODO: Register Listener, get connection information and return results in listOutgoing/IncomingConnections() @@ -185,11 +187,7 @@ class ConnectionManagerService : ConnectionManager { ListenerManager.removeConnectionListener(connectionListener) } - override fun listIncomingConnections(): List { - return incomingConnections - } + override fun listIncomingConnections(): List = incomingConnections - override fun listOutgoingConnections(): List { - return outgoingConnections - } + override fun listOutgoingConnections(): List = outgoingConnections } diff --git a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/RouteManagerService.kt b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/RouteManagerService.kt index edb2af5d..2c8bb400 100644 --- a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/RouteManagerService.kt +++ b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/RouteManagerService.kt @@ -189,8 +189,8 @@ class RouteManagerService : RouteManager { private fun routeDefinitionToObject( cCtx: CamelContext, rd: RouteDefinition - ): RouteObject { - return RouteObject( + ): RouteObject = + RouteObject( rd.id, rd.descriptionText, routeToDot(rd), @@ -199,7 +199,6 @@ class RouteManagerService : RouteManager { cCtx.uptimeMillis, cCtx.routeController.getRouteStatus(rd.id).toString() ) - } /** * Creates a visualization of a Camel route in DOT (graphviz) format. @@ -245,8 +244,7 @@ class RouteManagerService : RouteManager { .parallelStream() .filter { cCtx: CamelContext -> cCtx.adapt(ModelCamelContext::class.java).getRouteDefinition(routeId) != null - } - .findAny() + }.findAny() if (c.isPresent) { try { val rd = c.get().adapt(ModelCamelContext::class.java).getRouteDefinition(routeId) diff --git a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/XmlDeployWatcher.kt b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/XmlDeployWatcher.kt index d61d0c69..abd70855 100644 --- a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/XmlDeployWatcher.kt +++ b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/XmlDeployWatcher.kt @@ -257,10 +257,9 @@ class XmlDeployWatcher : ApplicationContextAware { private const val FS_WATCHER_POLL_INTERVAL = 1000L @Throws(BeansException::class) - fun getBeansOfType(type: Class?): List { - return xmlContexts.values + fun getBeansOfType(type: Class?): List = + xmlContexts.values .filter { it.isDone } .flatMap { it.get().getBeansOfType(type).values } - } } } diff --git a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/CamelRouteToDot.kt b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/CamelRouteToDot.kt index 97547eee..7e247585 100644 --- a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/CamelRouteToDot.kt +++ b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/CamelRouteToDot.kt @@ -240,9 +240,7 @@ class CamelRouteToDot { return answer } - private fun isMulticastNode(node: ProcessorDefinition<*>?): Boolean { - return node is MulticastDefinition || node is ChoiceDefinition - } + private fun isMulticastNode(node: ProcessorDefinition<*>?): Boolean = node is MulticastDefinition || node is ChoiceDefinition /** Is the given node a pipeline */ private fun isPipeline(node: ProcessorDefinition<*>): Boolean { diff --git a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/NodeData.kt b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/NodeData.kt index ebbb988d..a274c918 100644 --- a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/NodeData.kt +++ b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/NodeData.kt @@ -37,7 +37,11 @@ import org.apache.camel.util.ObjectHelper import java.util.Locale /** Represents a node in Graphviz representation of a route. */ -class NodeData(var id: String, node: Any?, imagePrefix: String) { +class NodeData( + var id: String, + node: Any?, + imagePrefix: String +) { var image: String? = null var label: String? = null var shape: String? = null @@ -48,15 +52,14 @@ class NodeData(var id: String, node: Any?, imagePrefix: String) { var url: String? = null var outputs: List>? = null - private fun removeQueryString(text: String?): String? { - return text?.indexOf('?')?.let { idx -> + private fun removeQueryString(text: String?): String? = + text?.indexOf('?')?.let { idx -> if (idx <= 0) { text } else { text.substring(0, idx) } } - } companion object { /** Inserts a space before each upper case letter after a lowercase */ diff --git a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/PrologNode.kt b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/PrologNode.kt index 320f4500..105c461c 100644 --- a/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/PrologNode.kt +++ b/ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/PrologNode.kt @@ -36,7 +36,9 @@ import org.apache.camel.model.WhenDefinition import org.apache.camel.util.ObjectHelper /** Represents a node in the EIP diagram tree */ -class PrologNode(node: Any) { +class PrologNode( + node: Any +) { // public String id; private var nodeType: String? = null private var value: String? = null diff --git a/ids-settings/src/main/kotlin/de/fhg/aisec/ids/settings/ElsaSerializer.kt b/ids-settings/src/main/kotlin/de/fhg/aisec/ids/settings/ElsaSerializer.kt index 977c1a56..f0235b5b 100644 --- a/ids-settings/src/main/kotlin/de/fhg/aisec/ids/settings/ElsaSerializer.kt +++ b/ids-settings/src/main/kotlin/de/fhg/aisec/ids/settings/ElsaSerializer.kt @@ -38,7 +38,5 @@ class ElsaSerializer : Serializer { override fun deserialize( input: DataInput2, available: Int - ): T { - return serializer.deserialize(input) - } + ): T = serializer.deserialize(input) } diff --git a/ids-settings/src/main/kotlin/de/fhg/aisec/ids/settings/SettingsComponent.kt b/ids-settings/src/main/kotlin/de/fhg/aisec/ids/settings/SettingsComponent.kt index 6d18b2ca..746a028d 100644 --- a/ids-settings/src/main/kotlin/de/fhg/aisec/ids/settings/SettingsComponent.kt +++ b/ids-settings/src/main/kotlin/de/fhg/aisec/ids/settings/SettingsComponent.kt @@ -142,7 +142,9 @@ class SettingsComponent : Settings { } } - internal class NullableSetting(private val key: String) : ReadWriteProperty { + internal class NullableSetting( + private val key: String + ) : ReadWriteProperty { override operator fun getValue( thisRef: Settings, property: KProperty<*> @@ -203,9 +205,7 @@ class SettingsComponent : Settings { mapDB.commit() } - override fun getUsers(): Map { - return userStore.toMap() - } + override fun getUsers(): Map = userStore.toMap() override fun removeUser(username: String) { userStore.remove(username) diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/AppApi.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/AppApi.kt index c9578e1a..11b62820 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/AppApi.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/AppApi.kt @@ -83,8 +83,8 @@ class AppApi { responseContainer = "List" ) @ApiResponses(ApiResponse(code = 200, message = "List of apps")) - fun list(): List { - return cml.list(false).sortedWith { app1, app2 -> + fun list(): List = + cml.list(false).sortedWith { app1, app2 -> try { val date1 = ZonedDateTime.parse(app1.created) val date2 = ZonedDateTime.parse(app2.created) @@ -99,7 +99,6 @@ class AppApi { 0 } } - } @GetMapping("start/{containerId}", produces = [MediaType.APPLICATION_JSON]) @ApiOperation( @@ -122,9 +121,7 @@ class AppApi { @ApiParam(value = "ID of the app to start") @PathVariable("containerId") containerId: String - ): Boolean { - return start(containerId, null) - } + ): Boolean = start(containerId, null) @GetMapping("start/{containerId}/{key}", produces = [MediaType.APPLICATION_JSON]) @ApiOperation( @@ -149,15 +146,14 @@ class AppApi { @ApiParam(value = "Key for user token (required for trustX containers)") @PathVariable("key") key: String? - ): Boolean { - return try { + ): Boolean = + try { cml.startContainer(containerId, key) true } catch (e: NoContainerExistsException) { LOG.error("Error starting container", e) false } - } @GetMapping("stop/{containerId}", produces = [MediaType.APPLICATION_JSON]) @ApiOperation( @@ -179,15 +175,14 @@ class AppApi { @ApiParam(value = "ID of the app to stop") @PathVariable("containerId") containerId: String - ): Boolean { - return try { + ): Boolean = + try { cml.stopContainer(containerId) true } catch (e: NoContainerExistsException) { LOG.error(e.message, e) false } - } @PostMapping("install", consumes = [MediaType.APPLICATION_JSON]) @ApiOperation(value = "Install an app", notes = "Requests to install an app.", response = Boolean::class) @@ -252,15 +247,14 @@ class AppApi { value = "Returns the version of the currently active container management layer", response = MutableMap::class ) - fun getCml(): Map { - return try { + fun getCml(): Map = + try { val result: MutableMap = HashMap() result["cml_version"] = cml.version result } catch (sue: Exception) { emptyMap() } - } @PostMapping( "search", @@ -269,8 +263,8 @@ class AppApi { ) suspend fun search( @RequestBody term: String? - ): List { - return httpClient.get(settings.connectorConfig.appstoreUrl).body>().let { res -> + ): List = + httpClient.get(settings.connectorConfig.appstoreUrl).body>().let { res -> if (term?.isNotBlank() == true) { res.filter { app: ApplicationContainer -> app.name?.contains(term, true) ?: false || @@ -283,7 +277,6 @@ class AppApi { res } } - } companion object { private val LOG = LoggerFactory.getLogger(AppApi::class.java) diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/CertApi.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/CertApi.kt index 58374797..0f3cb722 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/CertApi.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/CertApi.kt @@ -117,7 +117,10 @@ class CertApi( acmeClient?.renewCertificate( FileSystems.getDefault().getPath("etc", "tls-webconsole"), URI.create(config.acmeServerWebcon), - config.acmeDnsWebcon.trim { it <= ' ' }.split("\\s*,\\s*".toRegex()).toTypedArray(), + config.acmeDnsWebcon + .trim { it <= ' ' } + .split("\\s*,\\s*".toRegex()) + .toTypedArray(), config.acmePortWebcon ) } else { @@ -137,9 +140,7 @@ class CertApi( @ApiParam(value = "URI to retrieve the TOS from") @RequestParam uri: String - ): AcmeTermsOfService? { - return acmeClient?.getTermsOfService(URI.create(uri.trim())) - } + ): AcmeTermsOfService? = acmeClient?.getTermsOfService(URI.create(uri.trim())) @GetMapping("list_certs", produces = [MediaType.APPLICATION_JSON]) @ApiOperation( @@ -244,14 +245,13 @@ class CertApi( // return "Error: certificate has NOT been uploaded to $trustStoreName" // } - private inline fun notThrowing(block: () -> Unit): Boolean { - return try { + private inline fun notThrowing(block: () -> Unit): Boolean = + try { block() true } catch (t: Throwable) { false } - } private fun X509Certificate.isValid() = notThrowing { this.checkValidity() } @@ -318,9 +318,8 @@ class CertApi( * @param byteArray Byte array to get hexadecimal representation for * @return Hexadecimal representation of the given bytes */ - private fun encodeHexString(byteArray: ByteArray): String { - return byteArray.joinToString("") { hexLookup.computeIfAbsent(it) { num: Byte -> byteToHex(num.toInt()) } } - } + private fun encodeHexString(byteArray: ByteArray): String = + byteArray.joinToString("") { hexLookup.computeIfAbsent(it) { num: Byte -> byteToHex(num.toInt()) } } private fun Certificate.sha256Hash(): String { val sha256 = MessageDigest.getInstance("SHA-256") @@ -341,19 +340,22 @@ class CertApi( fun storeEstCACerts( @RequestBody certificates: String ) { - certificates.split("-----END CERTIFICATE-----").map { - it.replace(CLEAR_PEM_REGEX, "") - }.filter { it.isNotEmpty() }.map { c -> - val trustStoreName = settings.connectorConfig.truststoreName - val encoded = Base64.getDecoder().decode(c.replace(WHITESPACE_REGEX, "")) - val cf = CertificateFactory.getInstance("X.509") - val cert = cf.generateCertificate(ByteArrayInputStream(encoded)) as X509Certificate - try { - storeCertificate(trustStoreName, listOf(cert)) - } catch (t: Throwable) { - LOG.error("Error saving a CA certificate", t) + certificates + .split("-----END CERTIFICATE-----") + .map { + it.replace(CLEAR_PEM_REGEX, "") + }.filter { it.isNotEmpty() } + .map { c -> + val trustStoreName = settings.connectorConfig.truststoreName + val encoded = Base64.getDecoder().decode(c.replace(WHITESPACE_REGEX, "")) + val cf = CertificateFactory.getInstance("X.509") + val cert = cf.generateCertificate(ByteArrayInputStream(encoded)) as X509Certificate + try { + storeCertificate(trustStoreName, listOf(cert)) + } catch (t: Throwable) { + LOG.error("Error saving a CA certificate", t) + } } - } } @PostMapping("/request_est_identity", consumes = [MediaType.APPLICATION_JSON]) @@ -427,14 +429,16 @@ class CertApi( ): PKCS7 { val trustStoreFile = getKeystoreFile(settings.connectorConfig.truststoreName) val trustManagers = - TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).also { tmf -> - KeyStore.getInstance("pkcs12").also { - FileInputStream(trustStoreFile).use { fis -> - it.load(fis, KEYSTORE_PWD.toCharArray()) - tmf.init(it) + TrustManagerFactory + .getInstance(TrustManagerFactory.getDefaultAlgorithm()) + .also { tmf -> + KeyStore.getInstance("pkcs12").also { + FileInputStream(trustStoreFile).use { fis -> + it.load(fis, KEYSTORE_PWD.toCharArray()) + tmf.init(it) + } } - } - }.trustManagers + }.trustManagers val secureHttpClient = HttpClient(Java) { engine { @@ -495,7 +499,11 @@ class CertApi( } val entryAlias = alias ?: certificateChain[0].subjectX500Principal.name.let { name -> - name.split(",").map { it.split("=") }.firstOrNull { it[0] == "CN" }?.get(1) ?: name + name + .split(",") + .map { it.split("=") } + .firstOrNull { it[0] == "CN" } + ?.get(1) ?: name } if (key == null) { // Add a CA certificate @@ -566,8 +574,7 @@ class CertApi( } else { null } - } - .map { (alias, certificate) -> + }.map { (alias, certificate) -> Cert().also { cert -> cert.alias = alias cert.file = keystoreFile.name.replaceFirst("[.][^.]+$".toRegex(), "") diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConfigApi.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConfigApi.kt index de1a97ec..f93c218d 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConfigApi.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConfigApi.kt @@ -72,9 +72,7 @@ class ConfigApi { @ApiOperation(value = "Retrieves the current configuration", response = ConnectorConfig::class) @GetMapping("/connectorConfig", produces = [MediaType.APPLICATION_JSON]) - fun get(): ConnectorConfig { - return settings.connectorConfig - } + fun get(): ConnectorConfig = settings.connectorConfig @PostMapping("/connectorConfig", consumes = [MediaType.APPLICATION_JSON]) @ApiOperation(value = "Sets the overall configuration of the connector") @@ -136,9 +134,7 @@ class ConfigApi { @ApiOperation(value = "Sends configuration of a connection", response = ConnectionSettings::class) fun getConnectionConfigurations( @PathVariable("con") connection: String - ): ConnectionSettings { - return settings.getConnectionSettings(connection) - } + ): ConnectionSettings = settings.getConnectionSettings(connection) /** * Sends configurations of all connections @@ -209,8 +205,7 @@ class ConfigApi { .entries .filter { (_, value1) -> value1.any { u: String -> u.startsWith("idsserver://$key") } - } - .map { "$it - $key" } + }.map { "$it - $key" } .ifEmpty { listOf(" - $key") } // add endpoint configurations diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConnectionApi.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConnectionApi.kt index bdcf1289..f54b00ae 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConnectionApi.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConnectionApi.kt @@ -69,7 +69,5 @@ class ConnectionApi { responseContainer = "List" ) @GetMapping("/endpoints", produces = [MediaType.APPLICATION_JSON]) - fun availableEndpoints(): List { - return connectionManager.listAvailableEndpoints() - } + fun availableEndpoints(): List = connectionManager.listAvailableEndpoints() } diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/JwtRestApiFilter.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/JwtRestApiFilter.kt index b5db92e9..27e9ed0b 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/JwtRestApiFilter.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/JwtRestApiFilter.kt @@ -62,11 +62,10 @@ class JwtRestApiFilter : OncePerRequestFilter() { chain.doFilter(request, response) } - override fun shouldNotFilter(request: HttpServletRequest): Boolean { - return request.requestURI.let { + override fun shouldNotFilter(request: HttpServletRequest): Boolean = + request.requestURI.let { it == "/api/v1/user/login" || !it.startsWith("/api/v1") } - } companion object { private val LOG = LoggerFactory.getLogger(JwtRestApiFilter::class.java) diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/RouteApi.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/RouteApi.kt index 7ceafc07..85e201a5 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/RouteApi.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/RouteApi.kt @@ -78,9 +78,7 @@ class RouteApi { response = RouteObject::class, responseContainer = "List" ) - fun list(): List { - return rm.routes - } + fun list(): List = rm.routes @GetMapping("/get/{id}", produces = [MediaType.APPLICATION_JSON]) @ApiOperation(value = "Get a Camel route", response = RouteObject::class) @@ -88,39 +86,35 @@ class RouteApi { @ApiParam(value = "Route ID") @PathVariable("id") id: String - ): RouteObject { - return rm.getRoute(id) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Route not found") - } + ): RouteObject = rm.getRoute(id) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Route not found") /** Stop a route based on an id. */ @GetMapping("/startroute/{id}", produces = [MediaType.APPLICATION_JSON]) @ApiOperation(value = "Starts a Camel route. The route will start to process messages.") fun startRoute( @PathVariable("id") id: String - ): Result { - return try { + ): Result = + try { rm.startRoute(id) Result() } catch (e: Exception) { LOG.warn(e.message, e) e.message?.let { Result(false, it) } ?: Result(false) } - } /** Stop a route based on its id. */ @GetMapping("/stoproute/{id}", produces = [MediaType.APPLICATION_JSON]) @ApiOperation(value = "Stops a Camel route. The route will remain installed but it will not process any messages.") fun stopRoute( @PathVariable("id") id: String - ): Result { - return try { + ): Result = + try { rm.stopRoute(id) Result() } catch (e: Exception) { LOG.warn(e.message, e) e.message?.let { Result(false, it) } ?: Result(false) } - } /** * Retrieve list of supported components (aka protocols which can be addressed by Camel) @@ -132,9 +126,7 @@ class RouteApi { /** Retrieve list of currently installed endpoints (aka URIs to/from which routes exist) */ @GetMapping("/list_endpoints", produces = [MediaType.APPLICATION_JSON]) - fun listEndpoints(): Map { - return rm.listEndpoints() - } + fun listEndpoints(): Map = rm.listEndpoints() @GetMapping("/validate/{routeId}", produces = [MediaType.APPLICATION_JSON]) fun validate( @@ -155,9 +147,7 @@ class RouteApi { @GetMapping("/prolog/{routeId}", produces = [MediaType.TEXT_PLAIN]) fun getRouteProlog( @PathVariable("routeId") routeId: String - ): String { - return rm.getRouteAsProlog(routeId) - } + ): String = rm.getRouteAsProlog(routeId) companion object { private val LOG = LoggerFactory.getLogger(RouteApi::class.java) diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/UserApi.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/UserApi.kt index 91b115f3..77bdd423 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/UserApi.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/UserApi.kt @@ -83,7 +83,8 @@ class UserApi( private fun issueToken(username: String?): String { val tomorrow = Calendar.getInstance().apply { timeInMillis += 86400000 }.time - return JWT.create() + return JWT + .create() .withClaim("user", username) .withExpiresAt(tomorrow) .withIssuer("ids-connector") @@ -94,8 +95,8 @@ class UserApi( private fun authenticate( username: String, password: String - ): Boolean { - return if (settings.isUserStoreEmpty()) { + ): Boolean = + if (settings.isUserStoreEmpty()) { LOG.warn("WARNING: User store is empty! This is insecure! Please create an admin user via the REST API!") username == "ids" && password == "ids" } else { @@ -107,7 +108,6 @@ class UserApi( } loginOk } - } @PostMapping("/saveUser", consumes = [MediaType.APPLICATION_JSON]) fun addUser( diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/EstIdRequest.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/EstIdRequest.kt index e9399468..2a6f243d 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/EstIdRequest.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/EstIdRequest.kt @@ -19,4 +19,9 @@ */ package de.fhg.aisec.ids.webconsole.api.data -data class EstIdRequest(val estUrl: String, val rootCertHash: String, val iet: String, val alias: String) +data class EstIdRequest( + val estUrl: String, + val rootCertHash: String, + val iet: String, + val alias: String +) diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/PasswordChangeRequest.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/PasswordChangeRequest.kt index f18c79a7..09b08e12 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/PasswordChangeRequest.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/PasswordChangeRequest.kt @@ -19,4 +19,8 @@ */ package de.fhg.aisec.ids.webconsole.api.data -data class PasswordChangeRequest(val username: String, val oldPassword: String, val newPassword: String) +data class PasswordChangeRequest( + val username: String, + val oldPassword: String, + val newPassword: String +) diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/User.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/User.kt index a615a0ee..90b7577c 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/User.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/User.kt @@ -19,4 +19,7 @@ */ package de.fhg.aisec.ids.webconsole.api.data -data class User(val username: String, val password: String) +data class User( + val username: String, + val password: String +) diff --git a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/helper/StreamGobbler.kt b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/helper/StreamGobbler.kt index 4c8573ef..aa2112c3 100644 --- a/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/helper/StreamGobbler.kt +++ b/ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/helper/StreamGobbler.kt @@ -29,7 +29,10 @@ import java.io.OutputStream import java.io.OutputStreamWriter import java.nio.charset.StandardCharsets -internal class StreamGobbler(var `is`: InputStream, var out: OutputStream?) : Thread() { +internal class StreamGobbler( + var `is`: InputStream, + var out: OutputStream? +) : Thread() { override fun run() { try { InputStreamReader(`is`, StandardCharsets.UTF_8).use { isr ->