diff --git a/pom.xml b/pom.xml index 6c7b1a1..df45934 100644 --- a/pom.xml +++ b/pom.xml @@ -10,14 +10,78 @@ alvarium-sdk https://alvarium.org/ - + + + + + com.diffplug.spotless + spotless-maven-plugin + 2.43.0 + + + + + .gitattributes + .gitignore + + + + + + + + + 1.17.0 + + true + false + + + + + true + 2 + + + true + 1 + + + + /******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ + + + + + java,javafx,scala,com,net,org,com.twitter,static + + + + + + + + 11 11 + - + org.apache.httpcomponents httpclient @@ -30,7 +94,7 @@ 4.11 test - + com.google.crypto.tink tink @@ -38,47 +102,47 @@ - com.google.code.gson - gson - 2.8.8 + com.google.code.gson + gson + 2.8.8 - de.huxhorn.sulky - de.huxhorn.sulky.ulid - 8.2.0 + de.huxhorn.sulky + de.huxhorn.sulky.ulid + 8.2.0 - org.eclipse.paho - org.eclipse.paho.client.mqttv3 - 1.2.5 + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.2.5 + + + + io.pravega + pravega-client + 0.10.0 + + + + org.apache.logging.log4j + log4j-api + 2.21.0 + + + + org.apache.logging.log4j + log4j-core + 2.21.0 + test - io.pravega - pravega-client - 0.10.0 + org.spdx + spdx-jackson-store + 1.1.9.1 - - org.apache.logging.log4j - log4j-api - 2.21.0 - - - - org.apache.logging.log4j - log4j-core - 2.21.0 - test - - - - org.spdx - spdx-jackson-store - 1.1.9.1 - - diff --git a/src/main/java/com/alvarium/DefaultSdk.java b/src/main/java/com/alvarium/DefaultSdk.java index 44dba56..94c97ac 100644 --- a/src/main/java/com/alvarium/DefaultSdk.java +++ b/src/main/java/com/alvarium/DefaultSdk.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium; import java.util.ArrayList; @@ -39,7 +38,8 @@ public class DefaultSdk implements Sdk { private final StreamProvider stream; private final Logger logger; - public DefaultSdk(Annotator[] annotators, SdkInfo config, Logger logger) throws StreamException { + public DefaultSdk(Annotator[] annotators, SdkInfo config, Logger logger) + throws StreamException { this.annotators = annotators; this.config = config; this.logger = logger; @@ -51,37 +51,35 @@ public DefaultSdk(Annotator[] annotators, SdkInfo config, Logger logger) throws this.logger.debug("stream provider connected successfully."); } - public void create(PropertyBag properties, byte[] data) throws AnnotatorException, - StreamException { + public void create(PropertyBag properties, byte[] data) + throws AnnotatorException, StreamException { final List annotations = this.createAnnotations(properties, data); this.publishAnnotations(SdkAction.CREATE, annotations); this.logger.debug("data annotated and published successfully."); } - + public void create(byte[] data) throws AnnotatorException, StreamException { final PropertyBag properties = new ImmutablePropertyBag(new HashMap()); this.create(properties, data); } - public void mutate(PropertyBag properties, byte[] oldData, byte[] newData) throws - AnnotatorException, StreamException { + public void mutate(PropertyBag properties, byte[] oldData, byte[] newData) + throws AnnotatorException, StreamException { final List annotations = new ArrayList(); // source annotate the old data final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final Annotator sourceAnnotator = annotatorFactory.getAnnotator( - new AnnotatorConfig(AnnotationType.SOURCE), - this.config, - this.logger - ); + final Annotator sourceAnnotator = + annotatorFactory.getAnnotator( + new AnnotatorConfig(AnnotationType.SOURCE), this.config, this.logger); final Annotation sourceAnnotation = sourceAnnotator.execute(properties, oldData); annotations.add(sourceAnnotation); // Add annotations for new data - for (Annotation annotation: this.createAnnotations(properties, newData)) { + for (Annotation annotation : this.createAnnotations(properties, newData)) { // TLS is ignored in mutate to prevent needless penalization // See https://github.com/project-alvarium/alvarium-sdk-go/issues/19 - if(annotation.getKind() != AnnotationType.TLS) { + if (annotation.getKind() != AnnotationType.TLS) { annotations.add(annotation); } } @@ -96,8 +94,8 @@ public void mutate(byte[] oldData, byte[] newData) throws AnnotatorException, St this.mutate(properties, oldData, newData); } - public void transit(PropertyBag properties, byte[] data) throws AnnotatorException, - StreamException { + public void transit(PropertyBag properties, byte[] data) + throws AnnotatorException, StreamException { final List annotations = this.createAnnotations(properties, data); this.publishAnnotations(SdkAction.TRANSIT, annotations); this.logger.debug("data annotated and published successfully."); @@ -108,13 +106,13 @@ public void transit(byte[] data) throws AnnotatorException, StreamException { this.transit(properties, data); } - public void publish(PropertyBag properties, byte[] data) throws AnnotatorException, - StreamException { + public void publish(PropertyBag properties, byte[] data) + throws AnnotatorException, StreamException { final List annotations = this.createAnnotations(properties, data); this.publishAnnotations(SdkAction.PUBLISH, annotations); this.logger.debug("data annotated and published successfully."); } - + public void publish(byte[] data) throws AnnotatorException, StreamException { final PropertyBag properties = new ImmutablePropertyBag(new HashMap()); this.publish(properties, data); @@ -132,12 +130,12 @@ public void close() throws StreamException { * @return * @throws AnnotatorException */ - private List createAnnotations(PropertyBag properties, byte[] data) + private List createAnnotations(PropertyBag properties, byte[] data) throws AnnotatorException { final List annotations = new ArrayList(); // Annotate incoming data - for (Annotator annotator: this.annotators) { + for (Annotator annotator : this.annotators) { final Annotation annotation = annotator.execute(properties, data); annotations.add(annotation); } @@ -146,22 +144,19 @@ private List createAnnotations(PropertyBag properties, byte[] data) } /** - * Wraps the annotation list with a publish wrapper that specifies the SDK action and the + * Wraps the annotation list with a publish wrapper that specifies the SDK action and the * content type * @param action * @param annotations * @throws StreamException */ - private void publishAnnotations(SdkAction action, List annotations) + private void publishAnnotations(SdkAction action, List annotations) throws StreamException { final AnnotationList annotationList = new AnnotationList(annotations); - + // publish list of annotations to the StreamProvider - final PublishWrapper wrapper = new PublishWrapper( - action, - annotationList.getClass().getName(), - annotationList - ); + final PublishWrapper wrapper = + new PublishWrapper(action, annotationList.getClass().getName(), annotationList); this.stream.publish(wrapper); } } diff --git a/src/main/java/com/alvarium/PublishWrapper.java b/src/main/java/com/alvarium/PublishWrapper.java index 9051883..b874939 100644 --- a/src/main/java/com/alvarium/PublishWrapper.java +++ b/src/main/java/com/alvarium/PublishWrapper.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium; import java.io.Serializable; @@ -51,30 +50,34 @@ public Object getContent() { } /** - * The content field in the returned JSON will be Base64 string encoded + * The content field in the returned JSON will be Base64 string encoded * @return String representation of the PublishWrapper JSON */ public String toJson() { - Gson gson = new GsonBuilder() - .registerTypeAdapter(Annotation.class, new AnnotationConverter()) - .disableHtmlEscaping() - .create(); - + Gson gson = + new GsonBuilder() + .registerTypeAdapter(Annotation.class, new AnnotationConverter()) + .disableHtmlEscaping() + .create(); + // Change the content field to a base64 encoded string before serializing to json final JsonElement decodedContent = gson.toJsonTree(this.content); final String encodedContent; - - // `toString()` will work if the content is a primitive type, but will add additional - // quotes (e.g. "foo" will be "\"foo\"") but `getAsString()` will produce correct behavior but + + // `toString()` will work if the content is a primitive type, but will add additional + // quotes (e.g. "foo" will be "\"foo\"") but `getAsString()` will produce correct behavior + // but // using `getAsString()` on a non-primitive type will throw an exception. // This condition ensures that the correct method is called on the correct type if (decodedContent.isJsonPrimitive()) { - encodedContent = Base64.getEncoder().encodeToString(decodedContent.getAsString().getBytes()); + encodedContent = + Base64.getEncoder().encodeToString(decodedContent.getAsString().getBytes()); } else { - encodedContent = Base64.getEncoder().encodeToString(decodedContent.toString().getBytes()); + encodedContent = + Base64.getEncoder().encodeToString(decodedContent.toString().getBytes()); } - // new publish wrapper returned as JSON string with encoded content + // new publish wrapper returned as JSON string with encoded content // to prevent setting the object content value final PublishWrapper wrapper = new PublishWrapper(action, messageType, encodedContent); return gson.toJson(wrapper); diff --git a/src/main/java/com/alvarium/Sdk.java b/src/main/java/com/alvarium/Sdk.java index 0346920..db13687 100644 --- a/src/main/java/com/alvarium/Sdk.java +++ b/src/main/java/com/alvarium/Sdk.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium; import com.alvarium.annotators.AnnotatorException; @@ -22,7 +21,7 @@ public interface Sdk { /** * Annotates incoming data based on the list of annotators that was provided to the sdk and * publishes it to the given StreamProvider. - * + * * @param properties : A property bag that may be used by specific (or custom) annotators to pass * custom values to them. The built-in annotators that require custom values are *
    @@ -33,11 +32,11 @@ public interface Sdk { * @throws AnnotatorException * @throws StreamException */ - public void create(PropertyBag properties, byte[] data) + public void create(PropertyBag properties, byte[] data) throws AnnotatorException, StreamException; /** - * Annotates incoming data based on the list of annotators that was provided to the sdk and + * Annotates incoming data based on the list of annotators that was provided to the sdk and * publishes it to the given StreamProvider. * @param data : data being annotated * @throws AnnotatorException @@ -57,7 +56,7 @@ public void create(PropertyBag properties, byte[] data) * @throws AnnotatorException * @throws StreamException */ - public void transit(PropertyBag properties, byte[] data) + public void transit(PropertyBag properties, byte[] data) throws AnnotatorException, StreamException; /** @@ -68,6 +67,7 @@ public void transit(PropertyBag properties, byte[] data) * @throws StreamException */ public void transit(byte[] data) throws AnnotatorException, StreamException; + /** * Handles annotations related to any type of data modification. * @param properties : A property bag that may be used by specific (or custom) annotators to pass @@ -80,8 +80,8 @@ public void transit(PropertyBag properties, byte[] data) * @throws AnnotatorException * @throws StreamException */ - public void mutate(PropertyBag properties, byte[] oldData, byte[] newData) throws - AnnotatorException, StreamException; + public void mutate(PropertyBag properties, byte[] oldData, byte[] newData) + throws AnnotatorException, StreamException; /** * Handles annotations related to any type of data modification. @@ -91,11 +91,11 @@ public void mutate(PropertyBag properties, byte[] oldData, byte[] newData) throw /** * Publish is proposed to provide extensibility for annotators that may need - * to attest to the state of data before it is sent over the wire. Publish could + * to attest to the state of data before it is sent over the wire. Publish could * also be useful in cases where the downstream host receiving the data isn't r * running Alvarium-enabled applications. * @param properties : A property bag that may be used by specific (or custom) - * annotators to pass custom values to them. The built-in + * annotators to pass custom values to them. The built-in * annotators that requires custom values are *
      *
    • TLS: Takes a key-value pair of "TLS": Socket
    • @@ -104,12 +104,12 @@ public void mutate(PropertyBag properties, byte[] oldData, byte[] newData) throw * @throws AnnotatorException * @throws StreamException */ - public void publish(PropertyBag properties, byte[] data) + public void publish(PropertyBag properties, byte[] data) throws AnnotatorException, StreamException; /** * Publish is proposed to provide extensibility for annotators that may need - * to attest to the state of data before it is sent over the wire. Publish could + * to attest to the state of data before it is sent over the wire. Publish could * also be useful in cases where the downstream host receiving the data isn't * running Alvarium-enabled applications. * @param data @@ -119,7 +119,7 @@ public void publish(PropertyBag properties, byte[] data) public void publish(byte[] data) throws AnnotatorException, StreamException; /** - * Closes any open connections + * Closes any open connections * @throws StreamException */ public void close() throws StreamException; diff --git a/src/main/java/com/alvarium/SdkAction.java b/src/main/java/com/alvarium/SdkAction.java index f80c43c..2deb625 100644 --- a/src/main/java/com/alvarium/SdkAction.java +++ b/src/main/java/com/alvarium/SdkAction.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium; import com.google.gson.annotations.SerializedName; diff --git a/src/main/java/com/alvarium/SdkInfo.java b/src/main/java/com/alvarium/SdkInfo.java index d419cf0..5aa00ed 100644 --- a/src/main/java/com/alvarium/SdkInfo.java +++ b/src/main/java/com/alvarium/SdkInfo.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium; import java.io.Serializable; @@ -36,8 +35,12 @@ public class SdkInfo implements Serializable { private final StreamInfo stream; private final LayerType layer; - public SdkInfo(AnnotatorConfig[] annotators, HashInfo hash, SignatureInfo signature, - StreamInfo stream, LayerType layer) { + public SdkInfo( + AnnotatorConfig[] annotators, + HashInfo hash, + SignatureInfo signature, + StreamInfo stream, + LayerType layer) { this.annotators = annotators; this.hash = hash; this.signature = signature; @@ -61,23 +64,25 @@ public StreamInfo getStream() { return this.stream; } - public LayerType getLayer(){ + public LayerType getLayer() { return this.layer; } public String toJson() { - Gson gson = new GsonBuilder() - .registerTypeAdapter(StreamInfo.class, new StreamInfoConverter()) - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); + Gson gson = + new GsonBuilder() + .registerTypeAdapter(StreamInfo.class, new StreamInfoConverter()) + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); return gson.toJson(this); } public static SdkInfo fromJson(String json) { - Gson gson = new GsonBuilder() - .registerTypeAdapter(StreamInfo.class, new StreamInfoConverter()) - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); + Gson gson = + new GsonBuilder() + .registerTypeAdapter(StreamInfo.class, new StreamInfoConverter()) + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); return gson.fromJson(json, SdkInfo.class); } } diff --git a/src/main/java/com/alvarium/annotators/AbstractAnnotator.java b/src/main/java/com/alvarium/annotators/AbstractAnnotator.java index 7ffdaa5..1f8f0c3 100644 --- a/src/main/java/com/alvarium/annotators/AbstractAnnotator.java +++ b/src/main/java/com/alvarium/annotators/AbstractAnnotator.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.IOException; @@ -18,8 +18,6 @@ import java.nio.file.Files; import java.nio.file.Paths; -import org.apache.logging.log4j.Logger; - import com.alvarium.contracts.Annotation; import com.alvarium.hash.HashProvider; import com.alvarium.hash.HashProviderFactory; @@ -31,12 +29,14 @@ import com.alvarium.sign.SignProviderFactory; import com.alvarium.utils.Encoder; +import org.apache.logging.log4j.Logger; + /** * A Util class responsible for carrying out common operations done by the annotators */ abstract class AbstractAnnotator { - protected Logger logger; + protected Logger logger; AbstractAnnotator(Logger logger) { this.logger = logger; @@ -45,7 +45,7 @@ abstract class AbstractAnnotator { public Logger getLogger() { return logger; } - + /** * returns hash of the provided data depending on the given hash type * @param type @@ -55,7 +55,7 @@ public Logger getLogger() { */ protected String deriveHash(HashType type, byte[] data) throws AnnotatorException { final HashProviderFactory hashFactory = new HashProviderFactory(); - + try { final HashProvider provider = hashFactory.getProvider(type); return provider.derive(data); @@ -72,15 +72,15 @@ protected String deriveHash(HashType type, byte[] data) throws AnnotatorExceptio * @return * @throws AnnotatorException */ - protected String signAnnotation(KeyInfo keyInfo, Annotation annotation) throws - AnnotatorException { + protected String signAnnotation(KeyInfo keyInfo, Annotation annotation) + throws AnnotatorException { final SignProviderFactory signFactory = new SignProviderFactory(); try { final SignProvider provider = signFactory.getProvider(keyInfo.getType()); - final String key = Files.readString(Paths.get(keyInfo.getPath()), - StandardCharsets.US_ASCII); - return provider.sign(Encoder.hexToBytes(key), annotation.toJson().getBytes()); + final String key = + Files.readString(Paths.get(keyInfo.getPath()), StandardCharsets.US_ASCII); + return provider.sign(Encoder.hexToBytes(key), annotation.toJson().getBytes()); } catch (SignException e) { throw new AnnotatorException("cannot sign annotation.", e); } catch (IOException e) { diff --git a/src/main/java/com/alvarium/annotators/AbstractPkiAnnotator.java b/src/main/java/com/alvarium/annotators/AbstractPkiAnnotator.java index 752850d..594e6e5 100644 --- a/src/main/java/com/alvarium/annotators/AbstractPkiAnnotator.java +++ b/src/main/java/com/alvarium/annotators/AbstractPkiAnnotator.java @@ -1,3 +1,16 @@ +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.IOException; @@ -5,14 +18,14 @@ import java.nio.file.Files; import java.nio.file.Paths; -import org.apache.logging.log4j.Logger; - import com.alvarium.sign.KeyInfo; import com.alvarium.sign.SignException; import com.alvarium.sign.SignProvider; import com.alvarium.sign.SignProviderFactory; import com.alvarium.utils.Encoder; +import org.apache.logging.log4j.Logger; + abstract class AbstractPkiAnnotator extends AbstractAnnotator { AbstractPkiAnnotator(Logger logger) { super(logger); @@ -21,7 +34,7 @@ abstract class AbstractPkiAnnotator extends AbstractAnnotator { /** * Responsible for verifying the signature, returns true if the verification * passed, false otherwise. - * + * * @param key The public key used to verify the signature * @param signable Contains the data (seed) and signature * @return True if signature valid, false otherwise @@ -39,9 +52,8 @@ protected Boolean verifySignature(KeyInfo key, Signable signable) throws Annotat try { // Load public key final String publicKeyPath = key.getPath(); - final String publicKey = Files.readString( - Paths.get(publicKeyPath), - StandardCharsets.US_ASCII); + final String publicKey = + Files.readString(Paths.get(publicKeyPath), StandardCharsets.US_ASCII); // Verify signature signProvider.verify( @@ -55,6 +67,5 @@ protected Boolean verifySignature(KeyInfo key, Signable signable) throws Annotat } catch (IOException e) { throw new AnnotatorException("Failed to load public key", e); } - - } + } } diff --git a/src/main/java/com/alvarium/annotators/Annotator.java b/src/main/java/com/alvarium/annotators/Annotator.java index 1678039..90ffb36 100644 --- a/src/main/java/com/alvarium/annotators/Annotator.java +++ b/src/main/java/com/alvarium/annotators/Annotator.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import com.alvarium.contracts.Annotation; @@ -27,5 +27,5 @@ public interface Annotator { * @return Annotation object * @throws AnnotatorException */ - public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException; + public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException; } diff --git a/src/main/java/com/alvarium/annotators/AnnotatorConfig.java b/src/main/java/com/alvarium/annotators/AnnotatorConfig.java index 9094c5b..a65d8a2 100644 --- a/src/main/java/com/alvarium/annotators/AnnotatorConfig.java +++ b/src/main/java/com/alvarium/annotators/AnnotatorConfig.java @@ -1,18 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.Serializable; @@ -20,14 +18,13 @@ import com.alvarium.contracts.AnnotationType; public class AnnotatorConfig implements Serializable { - private AnnotationType kind; - - public AnnotatorConfig(AnnotationType kind) { - this.kind = kind; - } + private AnnotationType kind; - public AnnotationType getKind() { - return this.kind; - } + public AnnotatorConfig(AnnotationType kind) { + this.kind = kind; + } + public AnnotationType getKind() { + return this.kind; + } } diff --git a/src/main/java/com/alvarium/annotators/AnnotatorException.java b/src/main/java/com/alvarium/annotators/AnnotatorException.java index e873a9f..c6880cc 100644 --- a/src/main/java/com/alvarium/annotators/AnnotatorException.java +++ b/src/main/java/com/alvarium/annotators/AnnotatorException.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; /** diff --git a/src/main/java/com/alvarium/annotators/AnnotatorFactory.java b/src/main/java/com/alvarium/annotators/AnnotatorFactory.java index 4581bf3..2641da1 100644 --- a/src/main/java/com/alvarium/annotators/AnnotatorFactory.java +++ b/src/main/java/com/alvarium/annotators/AnnotatorFactory.java @@ -1,20 +1,18 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; -import org.apache.logging.log4j.Logger; - import com.alvarium.SdkInfo; import com.alvarium.annotators.sbom.SbomAnnotatorConfig; import com.alvarium.annotators.vulnerability.VulnerabilityAnnotatorConfig; @@ -22,19 +20,22 @@ import com.alvarium.hash.HashType; import com.alvarium.sign.SignatureInfo; +import org.apache.logging.log4j.Logger; + public class AnnotatorFactory { - public Annotator getAnnotator(AnnotatorConfig cfg, SdkInfo config, Logger logger) throws AnnotatorException { + public Annotator getAnnotator(AnnotatorConfig cfg, SdkInfo config, Logger logger) + throws AnnotatorException { final HashType hash = config.getHash().getType(); final SignatureInfo signature = config.getSignature(); final LayerType layer = config.getLayer(); switch (cfg.getKind()) { case MOCK: try { - MockAnnotatorConfig mockCfg = MockAnnotatorConfig.class.cast(cfg); - return new MockAnnotator(mockCfg, hash, signature, layer); - } catch(ClassCastException e) { - throw new AnnotatorException("Invalid annotator config", e); + MockAnnotatorConfig mockCfg = MockAnnotatorConfig.class.cast(cfg); + return new MockAnnotator(mockCfg, hash, signature, layer); + } catch (ClassCastException e) { + throw new AnnotatorException("Invalid annotator config", e); } case TLS: return new TlsAnnotator(hash, signature, logger, layer); diff --git a/src/main/java/com/alvarium/annotators/ChecksumAnnotator.java b/src/main/java/com/alvarium/annotators/ChecksumAnnotator.java index bbea2f6..f82294a 100644 --- a/src/main/java/com/alvarium/annotators/ChecksumAnnotator.java +++ b/src/main/java/com/alvarium/annotators/ChecksumAnnotator.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.FileInputStream; @@ -22,8 +22,6 @@ import java.nio.file.Paths; import java.time.Instant; -import org.apache.logging.log4j.Logger; - import com.alvarium.contracts.Annotation; import com.alvarium.contracts.AnnotationType; import com.alvarium.contracts.LayerType; @@ -34,134 +32,121 @@ import com.alvarium.sign.SignatureInfo; import com.alvarium.utils.PropertyBag; -public class ChecksumAnnotator extends AbstractAnnotator implements Annotator { - - final private HashType hash; - final private SignatureInfo signature; - private final AnnotationType kind; - private final LayerType layer; +import org.apache.logging.log4j.Logger; - private HashProvider hashProvider; +public class ChecksumAnnotator extends AbstractAnnotator implements Annotator { - protected ChecksumAnnotator(HashType hash, SignatureInfo signature, Logger logger, LayerType layer) { - super(logger); - this.hash = hash; - this.signature = signature; - this.kind = AnnotationType.CHECKSUM; - this.layer = layer; + private final HashType hash; + private final SignatureInfo signature; + private final AnnotationType kind; + private final LayerType layer; + + private HashProvider hashProvider; + + protected ChecksumAnnotator( + HashType hash, SignatureInfo signature, Logger logger, LayerType layer) { + super(logger); + this.hash = hash; + this.signature = signature; + this.kind = AnnotationType.CHECKSUM; + this.layer = layer; + } + + @Override + public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException { + + this.initHashProvider(this.hash); + final String key = this.hashProvider.derive(data); + + final ChecksumAnnotatorProps props = + ctx.getProperty(AnnotationType.CHECKSUM.name(), ChecksumAnnotatorProps.class); + + String host = ""; + boolean isSatisfied; + try { + host = InetAddress.getLocalHost().getHostName(); + // Get artifact checksum + final String checksum = this.readFile(props.getChecksumPath()); + + // Validate artifact checksum + final String artifactHash = this.hashFile(props.getArtifactPath()); + + isSatisfied = checksum.equals(artifactHash); + } catch (UnknownHostException | AnnotatorException e) { + isSatisfied = false; + // log the error using the logger + this.logger.error("Error during ChecksumAnnotator execution: ", e); } - - @Override - public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException { - - this.initHashProvider(this.hash); - final String key = this.hashProvider.derive(data); - - final ChecksumAnnotatorProps props = ctx.getProperty( - AnnotationType.CHECKSUM.name(), - ChecksumAnnotatorProps.class - ); - - String host = ""; - boolean isSatisfied; - try{ - host = InetAddress.getLocalHost().getHostName(); - // Get artifact checksum - final String checksum = this.readFile(props.getChecksumPath()); - - // Validate artifact checksum - final String artifactHash = this.hashFile(props.getArtifactPath()); - - isSatisfied = checksum.equals(artifactHash); - } catch (UnknownHostException | AnnotatorException e) { - isSatisfied = false; - //log the error using the logger - this.logger.error("Error during ChecksumAnnotator execution: ",e); - } - final Annotation annotation = new Annotation( - key, - this.hash, - host, - layer, - this.kind, - null, - isSatisfied, - Instant.now() - ); - - final String annotationSignature = super.signAnnotation( - this.signature.getPrivateKey(), - annotation - ); - annotation.setSignature(annotationSignature); - return annotation; + final Annotation annotation = + new Annotation( + key, this.hash, host, layer, this.kind, null, isSatisfied, Instant.now()); + + final String annotationSignature = + super.signAnnotation(this.signature.getPrivateKey(), annotation); + annotation.setSignature(annotationSignature); + return annotation; + } + + /** + * Initializes a hash provider + * @return HashProvider + * @throws AnnotatorException - If hashing algorithm not found, + * or if an unknown exception was thrown + */ + private final void initHashProvider(HashType hashType) throws AnnotatorException { + try { + this.hashProvider = new HashProviderFactory().getProvider(hashType); + } catch (HashTypeException e) { + throw new AnnotatorException( + "Hashing algorithm not found, could not hash data or validate checksum", e); + } catch (Exception e) { + throw new AnnotatorException("Could not hash data or validate checksum", e); } - - /** - * Initializes a hash provider - * @return HashProvider - * @throws AnnotatorException - If hashing algorithm not found, - * or if an unknown exception was thrown - */ - private final void initHashProvider(HashType hashType) throws AnnotatorException { - try { - this.hashProvider = new HashProviderFactory().getProvider(hashType); - } catch (HashTypeException e) { - throw new AnnotatorException("Hashing algorithm not found, could not hash data or validate checksum", e); - } catch (Exception e) { - throw new AnnotatorException("Could not hash data or validate checksum", e); - } - } - - /** - * Reads a file on the local file system - * @param filePath - * @return String content of file - * @throws AnnotatorException - When bad file path or corrupted file given - */ - private final String readFile(String filePath) throws AnnotatorException { - final String content; - try { - content = Files.readString( - Paths.get(filePath), - StandardCharsets.UTF_8 - ); - } catch (IOException e) { - throw new AnnotatorException("Failed to read file, could not validate checksum", e); - } - return content; + } + + /** + * Reads a file on the local file system + * @param filePath + * @return String content of file + * @throws AnnotatorException - When bad file path or corrupted file given + */ + private final String readFile(String filePath) throws AnnotatorException { + final String content; + try { + content = Files.readString(Paths.get(filePath), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new AnnotatorException("Failed to read file, could not validate checksum", e); } - - /** - * Reads and hashes a file on the local file system in in chunks of 8KB - * @param filePath - * @return hash of the file's contents in string format - * @throws AnnotatorException - When bad file path or corrupted file given - */ - private final String hashFile(String filePath) throws AnnotatorException { - try { - FileInputStream fs = new FileInputStream(filePath); - final byte[] buffer = new byte[8192]; - - int bytesRead = 0; - while (true) { - bytesRead = fs.read(buffer); - if (bytesRead == -1) { // indicates EOF - break; - } else { - this.hashProvider.update(buffer, 0, bytesRead); - } - } - - fs.close(); - } catch(IOException e) { - throw new AnnotatorException( - "Failed to hash artifact, could not validate checksum", - e - ); + return content; + } + + /** + * Reads and hashes a file on the local file system in in chunks of 8KB + * @param filePath + * @return hash of the file's contents in string format + * @throws AnnotatorException - When bad file path or corrupted file given + */ + private final String hashFile(String filePath) throws AnnotatorException { + try { + FileInputStream fs = new FileInputStream(filePath); + final byte[] buffer = new byte[8192]; + + int bytesRead = 0; + while (true) { + bytesRead = fs.read(buffer); + if (bytesRead == -1) { // indicates EOF + break; + } else { + this.hashProvider.update(buffer, 0, bytesRead); } + } - return this.hashProvider.getValue(); + fs.close(); + } catch (IOException e) { + throw new AnnotatorException("Failed to hash artifact, could not validate checksum", e); } + + return this.hashProvider.getValue(); + } } diff --git a/src/main/java/com/alvarium/annotators/ChecksumAnnotatorProps.java b/src/main/java/com/alvarium/annotators/ChecksumAnnotatorProps.java index 82e263a..2e63aec 100644 --- a/src/main/java/com/alvarium/annotators/ChecksumAnnotatorProps.java +++ b/src/main/java/com/alvarium/annotators/ChecksumAnnotatorProps.java @@ -1,32 +1,32 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; public class ChecksumAnnotatorProps { - final private String checksumPath; - final private String artifactPath; - - public ChecksumAnnotatorProps(String artifactPath, String checksumPath) { - this.artifactPath = artifactPath; - this.checksumPath = checksumPath; - } + private final String checksumPath; + private final String artifactPath; - public String getChecksumPath() { - return this.checksumPath; - } + public ChecksumAnnotatorProps(String artifactPath, String checksumPath) { + this.artifactPath = artifactPath; + this.checksumPath = checksumPath; + } - public String getArtifactPath() { - return this.artifactPath; - } + public String getChecksumPath() { + return this.checksumPath; + } + + public String getArtifactPath() { + return this.artifactPath; + } } diff --git a/src/main/java/com/alvarium/annotators/MockAnnotator.java b/src/main/java/com/alvarium/annotators/MockAnnotator.java index 2ce39fe..c720768 100644 --- a/src/main/java/com/alvarium/annotators/MockAnnotator.java +++ b/src/main/java/com/alvarium/annotators/MockAnnotator.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.net.InetAddress; @@ -37,7 +36,8 @@ class MockAnnotator implements Annotator { private final SignatureInfo signature; private final LayerType layer; - protected MockAnnotator(MockAnnotatorConfig cfg, HashType hash, SignatureInfo signature, LayerType layer) { + protected MockAnnotator( + MockAnnotatorConfig cfg, HashType hash, SignatureInfo signature, LayerType layer) { this.cfg = cfg; this.hash = hash; this.kind = AnnotationType.MOCK; @@ -52,12 +52,21 @@ public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorExceptio final String host = InetAddress.getLocalHost().getHostName(); final String sig = signature.getPublicKey().getType().toString(); - final Annotation annotation = new Annotation(key, hash, host, layer, kind, sig, cfg.getShouldSatisfy(), Instant.now()); + final Annotation annotation = + new Annotation( + key, + hash, + host, + layer, + kind, + sig, + cfg.getShouldSatisfy(), + Instant.now()); return annotation; } catch (HashTypeException e) { throw new AnnotatorException("failed to hash data", e); } catch (UnknownHostException e) { throw new AnnotatorException("Could not get hostname", e); } - } + } } diff --git a/src/main/java/com/alvarium/annotators/MockAnnotatorConfig.java b/src/main/java/com/alvarium/annotators/MockAnnotatorConfig.java index 2ad5367..d55348e 100644 --- a/src/main/java/com/alvarium/annotators/MockAnnotatorConfig.java +++ b/src/main/java/com/alvarium/annotators/MockAnnotatorConfig.java @@ -1,35 +1,29 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; - - import com.alvarium.contracts.AnnotationType; public class MockAnnotatorConfig extends AnnotatorConfig { - private final boolean shouldSatisfy; - - MockAnnotatorConfig(boolean shouldSatisfy) { - super(AnnotationType.MOCK); - this.shouldSatisfy = shouldSatisfy; - } - - public boolean getShouldSatisfy() { - return this.shouldSatisfy; - } + private final boolean shouldSatisfy; + MockAnnotatorConfig(boolean shouldSatisfy) { + super(AnnotationType.MOCK); + this.shouldSatisfy = shouldSatisfy; + } + public boolean getShouldSatisfy() { + return this.shouldSatisfy; + } } diff --git a/src/main/java/com/alvarium/annotators/PkiAnnotator.java b/src/main/java/com/alvarium/annotators/PkiAnnotator.java index 9c4d9af..e7904d5 100644 --- a/src/main/java/com/alvarium/annotators/PkiAnnotator.java +++ b/src/main/java/com/alvarium/annotators/PkiAnnotator.java @@ -1,25 +1,22 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.net.InetAddress; import java.net.UnknownHostException; import java.time.Instant; -import org.apache.logging.log4j.Logger; - import com.alvarium.contracts.Annotation; import com.alvarium.contracts.AnnotationType; import com.alvarium.contracts.LayerType; @@ -27,6 +24,8 @@ import com.alvarium.sign.SignatureInfo; import com.alvarium.utils.PropertyBag; +import org.apache.logging.log4j.Logger; + class PkiAnnotator extends AbstractPkiAnnotator implements Annotator { private final HashType hash; private final SignatureInfo signature; @@ -54,23 +53,15 @@ public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorExceptio isSatisfied = verifySignature(signature.getPublicKey(), signable); } catch (UnknownHostException | AnnotatorException e) { isSatisfied = false; - this.logger.error("Error during PkiAnnotator execution: ",e); - } + this.logger.error("Error during PkiAnnotator execution: ", e); + } - final Annotation annotation = new Annotation( - key, - hash, - host, - layer, - kind, - null, - isSatisfied, - Instant.now()); + final Annotation annotation = + new Annotation(key, hash, host, layer, kind, null, isSatisfied, Instant.now()); - final String annotationSignature = super.signAnnotation(signature.getPrivateKey(), annotation); + final String annotationSignature = + super.signAnnotation(signature.getPrivateKey(), annotation); annotation.setSignature(annotationSignature); return annotation; - } - } diff --git a/src/main/java/com/alvarium/annotators/PkiHttpAnnotator.java b/src/main/java/com/alvarium/annotators/PkiHttpAnnotator.java index f91ca75..52b0f8e 100644 --- a/src/main/java/com/alvarium/annotators/PkiHttpAnnotator.java +++ b/src/main/java/com/alvarium/annotators/PkiHttpAnnotator.java @@ -1,26 +1,24 @@ - /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.net.InetAddress; import java.net.URISyntaxException; import java.net.UnknownHostException; +import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; -import java.nio.file.Path; import com.alvarium.annotators.http.ParseResult; import com.alvarium.annotators.http.ParseResultException; @@ -29,8 +27,8 @@ import com.alvarium.contracts.LayerType; import com.alvarium.hash.HashType; import com.alvarium.sign.KeyInfo; -import com.alvarium.sign.SignatureInfo; import com.alvarium.sign.SignType; +import com.alvarium.sign.SignatureInfo; import com.alvarium.utils.PropertyBag; import org.apache.http.client.methods.HttpUriRequest; @@ -42,7 +40,8 @@ class PkiHttpAnnotator extends AbstractPkiAnnotator implements Annotator { private final AnnotationType kind; private final LayerType layer; - protected PkiHttpAnnotator(HashType hash, SignatureInfo signature, Logger logger, LayerType layer) { + protected PkiHttpAnnotator( + HashType hash, SignatureInfo signature, Logger logger, LayerType layer) { super(logger); this.hash = hash; this.signature = signature; @@ -57,9 +56,10 @@ public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorExceptio try { request = ctx.getProperty(AnnotationType.PKIHttp.name(), HttpUriRequest.class); } catch (IllegalArgumentException e) { - throw new AnnotatorException(String.format("Property %s not found", AnnotationType.PKIHttp.name())); + throw new AnnotatorException( + String.format("Property %s not found", AnnotationType.PKIHttp.name())); } - ParseResult parsed; + ParseResult parsed; try { parsed = new ParseResult(request); } catch (URISyntaxException e) { @@ -86,24 +86,17 @@ public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorExceptio String host = ""; boolean isSatisfied; - try{ + try { host = InetAddress.getLocalHost().getHostName(); isSatisfied = verifySignature(sig.getPublicKey(), signable); } catch (UnknownHostException | AnnotatorException e) { isSatisfied = false; - this.logger.error("Error during PkiHttpAnnotator execution: ",e); + this.logger.error("Error during PkiHttpAnnotator execution: ", e); } - - final Annotation annotation = new Annotation( - key, - hash, - host, - layer, - kind, - null, - isSatisfied, - Instant.now()); + + final Annotation annotation = + new Annotation(key, hash, host, layer, kind, null, isSatisfied, Instant.now()); final String annotationSignature = super.signAnnotation(sig.getPrivateKey(), annotation); annotation.setSignature(annotationSignature); diff --git a/src/main/java/com/alvarium/annotators/SbomAnnotator.java b/src/main/java/com/alvarium/annotators/SbomAnnotator.java index c5bd074..6e7bf9c 100644 --- a/src/main/java/com/alvarium/annotators/SbomAnnotator.java +++ b/src/main/java/com/alvarium/annotators/SbomAnnotator.java @@ -1,24 +1,22 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.net.InetAddress; import java.net.UnknownHostException; import java.time.Instant; -import org.apache.logging.log4j.Logger; - import com.alvarium.annotators.sbom.SbomAnnotatorConfig; import com.alvarium.annotators.sbom.SbomException; import com.alvarium.annotators.sbom.SbomProvider; @@ -30,6 +28,8 @@ import com.alvarium.sign.SignatureInfo; import com.alvarium.utils.PropertyBag; +import org.apache.logging.log4j.Logger; + public class SbomAnnotator extends AbstractAnnotator implements Annotator { final SbomAnnotatorConfig cfg; @@ -38,7 +38,12 @@ public class SbomAnnotator extends AbstractAnnotator implements Annotator { final AnnotationType kind; final LayerType layer; - protected SbomAnnotator(SbomAnnotatorConfig cfg, HashType hash, SignatureInfo signature, Logger logger, LayerType layer) { + protected SbomAnnotator( + SbomAnnotatorConfig cfg, + HashType hash, + SignatureInfo signature, + Logger logger, + LayerType layer) { super(logger); this.cfg = cfg; this.hash = hash; @@ -46,18 +51,18 @@ protected SbomAnnotator(SbomAnnotatorConfig cfg, HashType hash, SignatureInfo si this.kind = AnnotationType.SBOM; this.layer = layer; } - - @Override + + @Override public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException { final String key = deriveHash(this.hash, data); String host = ""; - try{ + try { host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { - this.logger.error("Error during SbomAnnotator execution: ",e); + this.logger.error("Error during SbomAnnotator execution: ", e); } - + boolean isSatisfied = false; try { final SbomProvider sbom = new SbomProviderFactory().getProvider(this.cfg, this.logger); @@ -71,24 +76,14 @@ public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorExceptio } catch (Exception e) { this.logger.error("Error during SbomAnnotator execution: ", e); } - - final Annotation annotation = new Annotation( - key, - hash, - host, - layer, - kind, - null, - isSatisfied, - Instant.now() - ); - final String annotationSignature = super.signAnnotation( - this.signature.getPrivateKey(), - annotation - ); + final Annotation annotation = + new Annotation(key, hash, host, layer, kind, null, isSatisfied, Instant.now()); + + final String annotationSignature = + super.signAnnotation(this.signature.getPrivateKey(), annotation); annotation.setSignature(annotationSignature); - return annotation; + return annotation; } } diff --git a/src/main/java/com/alvarium/annotators/Signable.java b/src/main/java/com/alvarium/annotators/Signable.java index 05152d1..5d629b2 100644 --- a/src/main/java/com/alvarium/annotators/Signable.java +++ b/src/main/java/com/alvarium/annotators/Signable.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.Serializable; diff --git a/src/main/java/com/alvarium/annotators/SourceAnnotator.java b/src/main/java/com/alvarium/annotators/SourceAnnotator.java index 8011d73..c21a4db 100644 --- a/src/main/java/com/alvarium/annotators/SourceAnnotator.java +++ b/src/main/java/com/alvarium/annotators/SourceAnnotator.java @@ -1,25 +1,22 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.net.InetAddress; import java.net.UnknownHostException; import java.time.Instant; -import org.apache.logging.log4j.Logger; - import com.alvarium.contracts.Annotation; import com.alvarium.contracts.AnnotationType; import com.alvarium.contracts.LayerType; @@ -27,6 +24,8 @@ import com.alvarium.sign.SignatureInfo; import com.alvarium.utils.PropertyBag; +import org.apache.logging.log4j.Logger; + /** * A unit used to provide lineage from one version of data to another as a result of * change or transformation @@ -36,14 +35,15 @@ class SourceAnnotator extends AbstractAnnotator implements Annotator { private final AnnotationType kind; private final SignatureInfo signatureInfo; private final LayerType layer; - - protected SourceAnnotator(HashType hash, SignatureInfo signatureInfo, Logger logger, LayerType layer) { + + protected SourceAnnotator( + HashType hash, SignatureInfo signatureInfo, Logger logger, LayerType layer) { super(logger); this.hash = hash; this.kind = AnnotationType.SOURCE; this.signatureInfo = signatureInfo; this.layer = layer; - } + } public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException { // hash incoming data @@ -56,17 +56,18 @@ public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorExceptio host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { isSatisfied = false; - this.logger.error("Error during SourceAnnotator execution: ",e); + this.logger.error("Error during SourceAnnotator execution: ", e); } isSatisfied = true; // create an annotation without signature - final Annotation annotation = new Annotation(key, this.hash, host, layer, this.kind, null, isSatisfied, - Instant.now()); - + final Annotation annotation = + new Annotation( + key, this.hash, host, layer, this.kind, null, isSatisfied, Instant.now()); + final String signature = super.signAnnotation(signatureInfo.getPrivateKey(), annotation); annotation.setSignature(signature); return annotation; - } + } } diff --git a/src/main/java/com/alvarium/annotators/SourceCodeAnnotator.java b/src/main/java/com/alvarium/annotators/SourceCodeAnnotator.java index 00f659b..6aba3bd 100644 --- a/src/main/java/com/alvarium/annotators/SourceCodeAnnotator.java +++ b/src/main/java/com/alvarium/annotators/SourceCodeAnnotator.java @@ -1,20 +1,18 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -29,7 +27,6 @@ import java.util.Collections; import java.util.List; import java.util.Locale; -import org.apache.logging.log4j.Logger; import com.alvarium.contracts.Annotation; import com.alvarium.contracts.AnnotationType; @@ -41,182 +38,172 @@ import com.alvarium.sign.SignatureInfo; import com.alvarium.utils.PropertyBag; -class SourceCodeAnnotator extends AbstractAnnotator implements Annotator { - - private final HashType hash; - private final AnnotationType kind; - private final SignatureInfo signature; - private final LayerType layer; +import org.apache.logging.log4j.Logger; - private HashProvider hashProvider; +class SourceCodeAnnotator extends AbstractAnnotator implements Annotator { - protected SourceCodeAnnotator(HashType hash, SignatureInfo signature, Logger logger, LayerType layer) { - super(logger); - this.hash = hash; - this.kind = AnnotationType.SourceCode; - this.signature = signature; - this.layer = layer; + private final HashType hash; + private final AnnotationType kind; + private final SignatureInfo signature; + private final LayerType layer; + + private HashProvider hashProvider; + + protected SourceCodeAnnotator( + HashType hash, SignatureInfo signature, Logger logger, LayerType layer) { + super(logger); + this.hash = hash; + this.kind = AnnotationType.SourceCode; + this.signature = signature; + this.layer = layer; + } + + // File (git working directory) is to be passed in the ctx bag + // expects commitHash and directory from ctx + @Override + public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException { + this.initHashProvider(this.hash); + final String key = this.hashProvider.derive(data); + + final SourceCodeAnnotatorProps props = + ctx.getProperty(AnnotationType.SourceCode.name(), SourceCodeAnnotatorProps.class); + + String host = ""; + boolean isSatisfied; + try { + host = InetAddress.getLocalHost().getHostName(); + final String checksum = this.readChecksum(props.getChecksumPath()); + final String generatedChecksum = this.generateChecksum(props.getSourceCodePath()); + isSatisfied = generatedChecksum.equals(checksum); + } catch (UnknownHostException | AnnotatorException e) { + isSatisfied = false; + this.logger.error("Error during SourceCodeAnnotator execution: ", e); } - // File (git working directory) is to be passed in the ctx bag - // expects commitHash and directory from ctx - @Override - public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException { - this.initHashProvider(this.hash); - final String key = this.hashProvider.derive(data); - - final SourceCodeAnnotatorProps props = ctx.getProperty( - AnnotationType.SourceCode.name(), - SourceCodeAnnotatorProps.class - ); - - String host = ""; - boolean isSatisfied; - try{ - host = InetAddress.getLocalHost().getHostName(); - final String checksum = this.readChecksum(props.getChecksumPath()); - final String generatedChecksum = this.generateChecksum(props.getSourceCodePath()); - isSatisfied = generatedChecksum.equals(checksum); - } catch (UnknownHostException | AnnotatorException e) { - isSatisfied = false; - this.logger.error("Error during SourceCodeAnnotator execution: ",e); - } - - final Annotation annotation = new Annotation( - key, - hash, - host, - layer, - kind, - null, - isSatisfied, - Instant.now()); - - final String annotationSignature = super.signAnnotation(signature.getPrivateKey(), annotation); - annotation.setSignature(annotationSignature); - return annotation; + final Annotation annotation = + new Annotation(key, hash, host, layer, kind, null, isSatisfied, Instant.now()); + + final String annotationSignature = + super.signAnnotation(signature.getPrivateKey(), annotation); + annotation.setSignature(annotationSignature); + return annotation; + } + + private String readChecksum(String path) throws AnnotatorException { + try { + final Path p = Paths.get(path); + return Files.readString(p); + } catch (IOException e) { + throw new AnnotatorException("Failed to read file, could not validate checksum", e); + } catch (SecurityException e) { + throw new AnnotatorException( + "Insufficient permission to access file, could not validate checksum", e); + } catch (OutOfMemoryError e) { + throw new AnnotatorException( + "Failed to read file due to size larger than 2GB, could not validate checksum " + + e); + } catch (Exception e) { + throw new AnnotatorException("Could not validate checksum"); } - - private String readChecksum(String path) throws AnnotatorException { - try { - final Path p = Paths.get(path); - return Files.readString(p); - } catch (IOException e) { - throw new AnnotatorException("Failed to read file, could not validate checksum", e); - } catch (SecurityException e) { - throw new AnnotatorException( - "Insufficient permission to access file, could not validate checksum", - e - ); - } catch (OutOfMemoryError e) { - throw new AnnotatorException( - "Failed to read file due to size larger than 2GB, could not validate checksum " + e - ); - } catch (Exception e) { - throw new AnnotatorException("Could not validate checksum"); - } + } + + /** + * Initializes the hash provider used to hash the source code + * @return HashProvider + * @throws AnnotatorException - If hashing algorithm not found, + * or if an unknown exception was thrown + */ + private final void initHashProvider(HashType hashType) throws AnnotatorException { + try { + this.hashProvider = new HashProviderFactory().getProvider(hashType); + } catch (HashTypeException e) { + throw new AnnotatorException( + "Hashing algorithm not found, could not hash data or generate checksum", e); + } catch (Exception e) { + throw new AnnotatorException("Could not hash data or generate checksum", e); } - - /** - * Initializes the hash provider used to hash the source code - * @return HashProvider - * @throws AnnotatorException - If hashing algorithm not found, - * or if an unknown exception was thrown - */ - private final void initHashProvider(HashType hashType) throws AnnotatorException { - try { - this.hashProvider = new HashProviderFactory().getProvider(hashType); - } catch (HashTypeException e) { - throw new AnnotatorException("Hashing algorithm not found, could not hash data or generate checksum", e); - } catch (Exception e) { - throw new AnnotatorException("Could not hash data or generate checksum", e); + } + + /** + * Recursively gets all files in a directory as a list of absolute paths + * @param path + * @return List of all files in directory + */ + private List getAllFiles(String path) { + List files = new ArrayList<>(); + File directory = new File(path); + + if (directory.isDirectory()) { + File[] directoryFiles = directory.listFiles(); + if (directoryFiles != null) { + for (File file : directoryFiles) { + if (file.isFile()) { + files.add(file.getAbsolutePath()); + } else if (file.isDirectory()) { + files.addAll(getAllFiles(file.getAbsolutePath())); + } } + } + } else if (directory.isFile()) { + files.add(directory.getAbsolutePath()); } - - /** - * Recursively gets all files in a directory as a list of absolute paths - * @param path - * @return List of all files in directory - */ - private List getAllFiles(String path) { - List files = new ArrayList<>(); - File directory = new File(path); - - if (directory.isDirectory()) { - File[] directoryFiles = directory.listFiles(); - if (directoryFiles != null) { - for (File file : directoryFiles) { - if (file.isFile()) { - files.add(file.getAbsolutePath()); - } else if (file.isDirectory()) { - files.addAll(getAllFiles(file.getAbsolutePath())); - } - } - } - } else if (directory.isFile()) { - files.add(directory.getAbsolutePath()); + return files; + } + + /** + * Reads and hashes a file on the local file system in in chunks of 8KB + * @param filePath + * @return hash of the file's contents in string format + * @throws AnnotatorException - When bad file path or corrupted file given + */ + private final String readAndHashFile(String filePath) throws AnnotatorException { + try { + FileInputStream fs = new FileInputStream(filePath); + final byte[] buffer = new byte[8192]; + int bytesRead = 0; + while (true) { + bytesRead = fs.read(buffer); + if (bytesRead == -1) { // indicates EOF + break; + } else { + this.hashProvider.update(buffer, 0, bytesRead); } - return files; + } + fs.close(); + } catch (OutOfMemoryError e) { + throw new AnnotatorException( + "Failed to read file due to size larger than 2GB, could not validate checksum" + + e); + } catch (IOException e) { + throw new AnnotatorException( + "Failed to read file contents, could not generate checksum", e); + } catch (SecurityException e) { + throw new AnnotatorException( + "Insufficient permission to access file, could not validate checksum", e); + } catch (Exception e) { + throw new AnnotatorException("Could not validate checksum", e); } - - /** - * Reads and hashes a file on the local file system in in chunks of 8KB - * @param filePath - * @return hash of the file's contents in string format - * @throws AnnotatorException - When bad file path or corrupted file given - */ - private final String readAndHashFile(String filePath) throws AnnotatorException { - try { - FileInputStream fs = new FileInputStream(filePath); - final byte[] buffer = new byte[8192]; - int bytesRead = 0; - while (true) { - bytesRead = fs.read(buffer); - if (bytesRead == -1) { // indicates EOF - break; - } else { - this.hashProvider.update(buffer, 0, bytesRead); - } - } - fs.close(); - } catch (OutOfMemoryError e) { - throw new AnnotatorException( - "Failed to read file due to size larger than 2GB, could not validate checksum" + e - ); - } catch (IOException e) { - throw new AnnotatorException( - "Failed to read file contents, could not generate checksum", - e - ); - } catch (SecurityException e) { - throw new AnnotatorException( - "Insufficient permission to access file, could not validate checksum", - e - ); - } catch (Exception e) { - throw new AnnotatorException("Could not validate checksum", e); - } - return this.hashProvider.getValue(); + return this.hashProvider.getValue(); + } + + /** + * Computes the hash of all files hashes and their corresponding paths in the specified directory and returns the + * hash value as a string. + * @param path the path of the directory to hash + * @return the hash value of the directory as a string + * @throws AnnotatorException if an error occurs while hashing the directory + */ + private String generateChecksum(String path) throws AnnotatorException { + List filePaths = getAllFiles(path); + for (int i = 0; i < filePaths.size(); i++) { + String hashThenPath = readAndHashFile(filePaths.get(i)) + " " + filePaths.get(i); + filePaths.set(i, hashThenPath); } + Collections.sort(filePaths, Collator.getInstance(Locale.US)); - /** - * Computes the hash of all files hashes and their corresponding paths in the specified directory and returns the - * hash value as a string. - * @param path the path of the directory to hash - * @return the hash value of the directory as a string - * @throws AnnotatorException if an error occurs while hashing the directory - */ - private String generateChecksum(String path) throws AnnotatorException { - List filePaths = getAllFiles(path); - for(int i = 0 ; i vulnerabilities; + boolean isSatisfied; + String host = ""; + try { + host = InetAddress.getLocalHost().getHostName(); + + Map packages = getPackages(dir); + vulnerabilities = retrievePackagesVulnerabilities(packages); + isSatisfied = vulnerabilities.isEmpty(); + } catch (UnknownHostException | AnnotatorException e) { + isSatisfied = false; + this.logger.error("Error during VulnerabilityAnnotator execution: ", e); } - @Override - public Annotation execute(PropertyBag ctx, byte[] data) throws AnnotatorException { - final String key = super.deriveHash(hash, data); - - String dir = ctx.getProperty(AnnotationType.VULNERABILITY.name(), String.class); - - List vulnerabilities; - boolean isSatisfied; - String host = ""; - try{ - host = InetAddress.getLocalHost().getHostName(); - - Map packages = getPackages(dir); - vulnerabilities = retrievePackagesVulnerabilities(packages); - isSatisfied = vulnerabilities.isEmpty(); - } catch (UnknownHostException | AnnotatorException e) { - isSatisfied = false; - this.logger.error("Error during VulnerabilityAnnotator execution: ",e); - } - - final Annotation annotation = new Annotation( - key, - this.hash, - host, - layer, - this.kind, - null, - isSatisfied, - Instant.now() - ); - - final String annotationSignature = super.signAnnotation( - this.sign.getPrivateKey(), - annotation - ); - - annotation.setSignature(annotationSignature); - return annotation; + final Annotation annotation = + new Annotation( + key, this.hash, host, layer, this.kind, null, isSatisfied, Instant.now()); + + final String annotationSignature = + super.signAnnotation(this.sign.getPrivateKey(), annotation); + + annotation.setSignature(annotationSignature); + return annotation; + } + + private Map getPackages(String dir) throws AnnotatorException { + try { + this.packageHandler = new PackageFileHandlerFactory().getHandler(dir); + return this.packageHandler.getPackages(); + } catch (VulnerabilityException e) { + throw new AnnotatorException("Failed to get dependency info", e); + } catch (Exception e) { + throw new AnnotatorException("Failed to get dependency info", e); } - - private Map getPackages(String dir) throws AnnotatorException { - try { - this.packageHandler = new PackageFileHandlerFactory().getHandler(dir); - return this.packageHandler.getPackages(); - } catch (VulnerabilityException e) { - throw new AnnotatorException("Failed to get dependency info", e); - } catch (Exception e) { - throw new AnnotatorException("Failed to get dependency info", e); - } + } + + private List retrievePackagesVulnerabilities(Map packages) + throws AnnotatorException { + try { + final VulnerabilityApiHandler apiHandler = + new VulnerabilityApiHandlerFactory().getHandler(this.cfg); + List vulnerabilities = apiHandler.getVulnerabilityIds(packages); + return vulnerabilities; + } catch (VulnerabilityException e) { + throw new AnnotatorException("Failed to retrieve packages vulnerabilities", e); + } catch (Exception e) { + throw new AnnotatorException("Failed to retrieve packages vulnerabilities", e); } - - private List retrievePackagesVulnerabilities( Map packages) throws AnnotatorException { - try{ - final VulnerabilityApiHandler apiHandler = new VulnerabilityApiHandlerFactory() - .getHandler(this.cfg); - List vulnerabilities = apiHandler.getVulnerabilityIds(packages); - return vulnerabilities; - } catch (VulnerabilityException e) { - throw new AnnotatorException("Failed to retrieve packages vulnerabilities", e); - } catch (Exception e) { - throw new AnnotatorException("Failed to retrieve packages vulnerabilities", e); - } - - } - + } } - diff --git a/src/main/java/com/alvarium/annotators/http/Ed2551RequestHandler.java b/src/main/java/com/alvarium/annotators/http/Ed2551RequestHandler.java index c545925..e150250 100644 --- a/src/main/java/com/alvarium/annotators/http/Ed2551RequestHandler.java +++ b/src/main/java/com/alvarium/annotators/http/Ed2551RequestHandler.java @@ -1,25 +1,23 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; import java.io.IOException; -import java.lang.StringBuilder; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; - import java.util.Date; import com.alvarium.sign.SignException; @@ -33,72 +31,76 @@ public class Ed2551RequestHandler implements RequestHandler { - HttpUriRequest request; - - public Ed2551RequestHandler(HttpUriRequest request) { - this.request = request; - } - - public void addSignatureHeaders(Date ticks, String[] fields, SignatureInfo keys) - throws RequestHandlerException { - - if (fields.length == 0) { - throw new RequestHandlerException("No fields found to be used in generating the seed"); - } - - // This will be the value returned for populating the Signature-Input header - StringBuilder headerValue = new StringBuilder(); - for (int i = 0; i < fields.length - 1; i++) { - headerValue.append(String.format("\"%s\" ", fields[i])); - } - - headerValue.append(String.format("\"%s\"", fields[fields.length - 1])); - - String timeInSeconds = Long.toString((ticks.getTime() / 1000)); - String tail = String.format( - ";created=%s;keyid=\"%s\";alg=\"%s\";", - timeInSeconds, - Paths.get(keys.getPublicKey().getPath()).getFileName(), - keys.getPublicKey().getType().getValue()); - - headerValue.append(tail); - - request.setHeader("Signature-Input", headerValue.toString()); - - ParseResult parseResult; - try { - parseResult = new ParseResult(request); - } catch (URISyntaxException e) { - throw new RequestHandlerException("Invalid request URI", e); - - } catch (ParseResultException e1) { - throw new RequestHandlerException("Error parsing the request", e1); - } - - // This will be the value used as input for the signature - String inputValue = parseResult.getSeed(); - - final SignProviderFactory signFactory = new SignProviderFactory(); - SignProvider signProvider; - try { - signProvider = signFactory.getProvider(SignType.Ed25519); - } catch (SignException e) { - throw new RequestHandlerException("Invalid key type", e); - } - - String privateKeyPath = ""; - try { - privateKeyPath = Files.readString(Paths.get(keys.getPrivateKey().getPath()), StandardCharsets.US_ASCII); - } catch (IOException e) { - throw new RequestHandlerException("Cannot read key.", e); - } - - String signature = ""; - try { - signature = signProvider.sign(Encoder.hexToBytes(privateKeyPath), inputValue.getBytes()); - } catch (SignException e) { - throw new RequestHandlerException("Cannot sign annotation.", e); - } - request.setHeader("Signature", signature); - } + HttpUriRequest request; + + public Ed2551RequestHandler(HttpUriRequest request) { + this.request = request; + } + + public void addSignatureHeaders(Date ticks, String[] fields, SignatureInfo keys) + throws RequestHandlerException { + + if (fields.length == 0) { + throw new RequestHandlerException("No fields found to be used in generating the seed"); + } + + // This will be the value returned for populating the Signature-Input header + StringBuilder headerValue = new StringBuilder(); + for (int i = 0; i < fields.length - 1; i++) { + headerValue.append(String.format("\"%s\" ", fields[i])); + } + + headerValue.append(String.format("\"%s\"", fields[fields.length - 1])); + + String timeInSeconds = Long.toString((ticks.getTime() / 1000)); + String tail = + String.format( + ";created=%s;keyid=\"%s\";alg=\"%s\";", + timeInSeconds, + Paths.get(keys.getPublicKey().getPath()).getFileName(), + keys.getPublicKey().getType().getValue()); + + headerValue.append(tail); + + request.setHeader("Signature-Input", headerValue.toString()); + + ParseResult parseResult; + try { + parseResult = new ParseResult(request); + } catch (URISyntaxException e) { + throw new RequestHandlerException("Invalid request URI", e); + + } catch (ParseResultException e1) { + throw new RequestHandlerException("Error parsing the request", e1); + } + + // This will be the value used as input for the signature + String inputValue = parseResult.getSeed(); + + final SignProviderFactory signFactory = new SignProviderFactory(); + SignProvider signProvider; + try { + signProvider = signFactory.getProvider(SignType.Ed25519); + } catch (SignException e) { + throw new RequestHandlerException("Invalid key type", e); + } + + String privateKeyPath = ""; + try { + privateKeyPath = + Files.readString( + Paths.get(keys.getPrivateKey().getPath()), StandardCharsets.US_ASCII); + } catch (IOException e) { + throw new RequestHandlerException("Cannot read key.", e); + } + + String signature = ""; + try { + signature = + signProvider.sign(Encoder.hexToBytes(privateKeyPath), inputValue.getBytes()); + } catch (SignException e) { + throw new RequestHandlerException("Cannot sign annotation.", e); + } + request.setHeader("Signature", signature); + } } diff --git a/src/main/java/com/alvarium/annotators/http/ParseResult.java b/src/main/java/com/alvarium/annotators/http/ParseResult.java index 9e6dccf..45a1e6b 100644 --- a/src/main/java/com/alvarium/annotators/http/ParseResult.java +++ b/src/main/java/com/alvarium/annotators/http/ParseResult.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; import java.net.URI; @@ -70,30 +70,31 @@ public ParseResult(HttpUriRequest request) throws URISyntaxException, ParseResul try { derivedComponent = DerivedComponent.fromString(key); } catch (EnumConstantNotPresentException e) { - throw new ParseResultException(String.format("Unhandled Derived Component %s", key)); + throw new ParseResultException( + String.format("Unhandled Derived Component %s", key)); } if (!uri.isAbsolute()) { throw new ParseResultException("Request URI is not absolute"); } switch (derivedComponent) { case METHOD: - signatureInputFields.put(key, new String[] { request.getMethod() }); + signatureInputFields.put(key, new String[] {request.getMethod()}); break; case TARGETURI: - signatureInputFields.put(key, new String[] { uri.toString() }); + signatureInputFields.put(key, new String[] {uri.toString()}); break; case AUTHORITY: - signatureInputFields.put(key, new String[] { uri.getAuthority() }); + signatureInputFields.put(key, new String[] {uri.getAuthority()}); break; case SCHEME: - signatureInputFields.put(key, new String[] { uri.getScheme() }); + signatureInputFields.put(key, new String[] {uri.getScheme()}); break; case PATH: - signatureInputFields.put(key, new String[] { uri.getPath() }); + signatureInputFields.put(key, new String[] {uri.getPath()}); break; case QUERY: String query = "?" + uri.getRawQuery(); - signatureInputFields.put(key, new String[] { query }); + signatureInputFields.put(key, new String[] {query}); break; case QUERYPARAMS: String[] rawQueryParams = uri.getRawQuery().split("&", -1); @@ -106,7 +107,8 @@ public ParseResult(HttpUriRequest request) throws URISyntaxException, ParseResul queryParams.add(String.format(";name=\"%s\": %s", name, value)); } } - signatureInputFields.put(key, queryParams.toArray(new String[queryParams.size()])); + signatureInputFields.put( + key, queryParams.toArray(new String[queryParams.size()])); } } else { Header[] fieldValues = request.getHeaders(key); @@ -121,7 +123,7 @@ public ParseResult(HttpUriRequest request) throws URISyntaxException, ParseResul // Remove extra spaces from fieldValue String fieldValue = String.join(" ", value.toString().trim().split("\\s+")); - signatureInputFields.put(key, new String[] { fieldValue }); + signatureInputFields.put(key, new String[] {fieldValue}); } } diff --git a/src/main/java/com/alvarium/annotators/http/ParseResultException.java b/src/main/java/com/alvarium/annotators/http/ParseResultException.java index 8583289..668b3b8 100644 --- a/src/main/java/com/alvarium/annotators/http/ParseResultException.java +++ b/src/main/java/com/alvarium/annotators/http/ParseResultException.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; /** diff --git a/src/main/java/com/alvarium/annotators/http/RequestHandler.java b/src/main/java/com/alvarium/annotators/http/RequestHandler.java index 0b58816..1766f2a 100644 --- a/src/main/java/com/alvarium/annotators/http/RequestHandler.java +++ b/src/main/java/com/alvarium/annotators/http/RequestHandler.java @@ -1,20 +1,20 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; import java.util.Date; + import com.alvarium.sign.SignatureInfo; /** @@ -28,13 +28,12 @@ public interface RequestHandler { * signing. * Assembles the SignatureInput and Signature fields, then adds them to the * request as headers. - * + * * @param ticks Date of creation of request * @param fields Array of the fields to be taken into consideration for the * SignatureInput header * @param keys Signature info to use in signing the seed */ - - void addSignatureHeaders(Date ticks, String[] fields, SignatureInfo keys) throws RequestHandlerException; - + void addSignatureHeaders(Date ticks, String[] fields, SignatureInfo keys) + throws RequestHandlerException; } diff --git a/src/main/java/com/alvarium/annotators/http/RequestHandlerException.java b/src/main/java/com/alvarium/annotators/http/RequestHandlerException.java index 007b083..8daeb9e 100644 --- a/src/main/java/com/alvarium/annotators/http/RequestHandlerException.java +++ b/src/main/java/com/alvarium/annotators/http/RequestHandlerException.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; /** diff --git a/src/main/java/com/alvarium/annotators/http/RequestHandlerFactory.java b/src/main/java/com/alvarium/annotators/http/RequestHandlerFactory.java index 817af5e..6bee67e 100644 --- a/src/main/java/com/alvarium/annotators/http/RequestHandlerFactory.java +++ b/src/main/java/com/alvarium/annotators/http/RequestHandlerFactory.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; import com.alvarium.sign.SignType; diff --git a/src/main/java/com/alvarium/annotators/sbom/SbomAnnotatorConfig.java b/src/main/java/com/alvarium/annotators/sbom/SbomAnnotatorConfig.java index 25658d5..836b913 100644 --- a/src/main/java/com/alvarium/annotators/sbom/SbomAnnotatorConfig.java +++ b/src/main/java/com/alvarium/annotators/sbom/SbomAnnotatorConfig.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.sbom; import com.alvarium.annotators.AnnotatorConfig; diff --git a/src/main/java/com/alvarium/annotators/sbom/SbomException.java b/src/main/java/com/alvarium/annotators/sbom/SbomException.java index 8e4d622..5aece0e 100644 --- a/src/main/java/com/alvarium/annotators/sbom/SbomException.java +++ b/src/main/java/com/alvarium/annotators/sbom/SbomException.java @@ -1,24 +1,23 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.sbom; public class SbomException extends Exception { public SbomException(String msg) { super(msg); } - + public SbomException(String msg, Exception e) { super(msg, e); } diff --git a/src/main/java/com/alvarium/annotators/sbom/SbomProvider.java b/src/main/java/com/alvarium/annotators/sbom/SbomProvider.java index 6285b02..9497aa9 100644 --- a/src/main/java/com/alvarium/annotators/sbom/SbomProvider.java +++ b/src/main/java/com/alvarium/annotators/sbom/SbomProvider.java @@ -1,21 +1,22 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.sbom; public interface SbomProvider { public boolean exists(String filePath); + public boolean validate(String filePath) throws SbomException; + public boolean matchesBuild(String filePath, String sourceCodeRootDirPath) throws SbomException; } diff --git a/src/main/java/com/alvarium/annotators/sbom/SbomProviderFactory.java b/src/main/java/com/alvarium/annotators/sbom/SbomProviderFactory.java index 450c40b..1b78471 100644 --- a/src/main/java/com/alvarium/annotators/sbom/SbomProviderFactory.java +++ b/src/main/java/com/alvarium/annotators/sbom/SbomProviderFactory.java @@ -1,30 +1,30 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - - package com.alvarium.annotators.sbom; +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.sbom; import org.apache.logging.log4j.Logger; public class SbomProviderFactory { - public SbomProvider getProvider(SbomAnnotatorConfig cfg, Logger logger) throws SbomException { + public SbomProvider getProvider(SbomAnnotatorConfig cfg, Logger logger) throws SbomException { switch (cfg.getSbomType()) { case SPDX: - return new SpdxSbomProvider(cfg) ; + return new SpdxSbomProvider(cfg); default: throw new SbomException( - String.format("Could not find SBOM provider implementation: ", cfg.getSbomType()) - ); + String.format( + "Could not find SBOM provider implementation: ", + cfg.getSbomType())); } } } diff --git a/src/main/java/com/alvarium/annotators/sbom/SbomType.java b/src/main/java/com/alvarium/annotators/sbom/SbomType.java index 7470ed5..a0f4b01 100644 --- a/src/main/java/com/alvarium/annotators/sbom/SbomType.java +++ b/src/main/java/com/alvarium/annotators/sbom/SbomType.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.sbom; import com.google.gson.annotations.SerializedName; diff --git a/src/main/java/com/alvarium/annotators/sbom/SpdxSbomProvider.java b/src/main/java/com/alvarium/annotators/sbom/SpdxSbomProvider.java index b2cbff6..53c5445 100644 --- a/src/main/java/com/alvarium/annotators/sbom/SpdxSbomProvider.java +++ b/src/main/java/com/alvarium/annotators/sbom/SpdxSbomProvider.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.sbom; import java.io.File; @@ -32,7 +31,7 @@ import org.spdx.utility.compare.SpdxComparer; public class SpdxSbomProvider implements SbomProvider { - final private String version; + private final String version; SpdxSbomProvider(SbomAnnotatorConfig cfg) { this.version = cfg.getSbomVersion(); @@ -44,29 +43,26 @@ public boolean exists(String filePath) { } public boolean validate(String filePath) throws SbomException { - try (ISerializableModelStore modelStore = new MultiFormatStore( - new InMemSpdxStore(), - this.getFormat(filePath)) - ) { + try (ISerializableModelStore modelStore = + new MultiFormatStore(new InMemSpdxStore(), this.getFormat(filePath))) { // deSerialize() throws if object has invalid format SpdxDocument doc = this.deserializeSpdxFile(filePath, modelStore); String docVersion = doc.getSpecVersion(); if (!docVersion.equals(this.version)) { return false; } - } catch(InvalidSPDXAnalysisException e) { + } catch (InvalidSPDXAnalysisException e) { throw new SbomException("Could not validate SBOM", e); - } catch(Exception e) { + } catch (Exception e) { throw new SbomException("Could not validate SBOM", e); } return true; - } + } - public boolean matchesBuild(String filePath, String sourceCodeRootDirPath) throws SbomException { - try (ISerializableModelStore modelStore = new MultiFormatStore( - new InMemSpdxStore(), - this.getFormat(filePath)) - ) { + public boolean matchesBuild(String filePath, String sourceCodeRootDirPath) + throws SbomException { + try (ISerializableModelStore modelStore = + new MultiFormatStore(new InMemSpdxStore(), this.getFormat(filePath))) { SpdxDocument originalSbom = this.deserializeSpdxFile(filePath, modelStore); Optional sbomName = originalSbom.getName(); String pkgName = sbomName.get().split(" ")[0]; @@ -84,31 +80,29 @@ public boolean matchesBuild(String filePath, String sourceCodeRootDirPath) throw String supplierName = creator.split(" ")[1]; String sbomLocation = "."; - String cmd = String.format( - "sbom-tool generate -b %s -bc %s -nsb http://alvarium.com -pn %s -pv %s -ps %s -D true", - sbomLocation, - sourceCodeRootDirPath, - pkgName, - pkgVersion, - supplierName - ); + String cmd = + String.format( + "sbom-tool generate -b %s -bc %s -nsb http://alvarium.com -pn %s -pv %s" + + " -ps %s -D true", + sbomLocation, sourceCodeRootDirPath, pkgName, pkgVersion, supplierName); Process sbomGenerationProcess = Runtime.getRuntime().exec(cmd); int exitCode = sbomGenerationProcess.waitFor(); if (exitCode != 0) { throw new SbomException("SBoM generation failed with exit code " + exitCode); } - SpdxDocument generatedSbom = this.deserializeSpdxFile("_manifest/spdx_2.2/manifest.spdx.json", modelStore); + SpdxDocument generatedSbom = + this.deserializeSpdxFile("_manifest/spdx_2.2/manifest.spdx.json", modelStore); SpdxComparer comparer = new SpdxComparer(); comparer.compare(originalSbom, generatedSbom); boolean isBuildMissingPkg = comparer.getUniquePackages(1, 0).size() != 0; - boolean buildHasAdditionalPkg= comparer.getUniquePackages(0, 1).size() != 0; + boolean buildHasAdditionalPkg = comparer.getUniquePackages(0, 1).size() != 0; if (isBuildMissingPkg || buildHasAdditionalPkg) { return false; } - } catch(InvalidSPDXAnalysisException e) { + } catch (InvalidSPDXAnalysisException e) { throw new SbomException("Invalid source code SBoM ", e); - } catch(SpdxCompareException e) { + } catch (SpdxCompareException e) { return false; } catch (IOException e) { throw new SbomException("Could not read source code SBoM", e); @@ -118,21 +112,22 @@ public boolean matchesBuild(String filePath, String sourceCodeRootDirPath) throw throw new SbomException("Could not read source code SBoM", e); } return true; - } + } public Format getFormat(String fileName) throws SbomException { String[] parts = fileName.split("\\."); - String extension = parts[parts.length-1]; + String extension = parts[parts.length - 1]; switch (extension) { case "json": - return Format.JSON; + return Format.JSON; default: throw new SbomException("Unimplemented SPDX file format: " + extension); } } - private SpdxDocument deserializeSpdxFile(String filePath, ISerializableModelStore modelStore) throws SbomException { - try (InputStream stream = new FileInputStream(filePath);) { + private SpdxDocument deserializeSpdxFile(String filePath, ISerializableModelStore modelStore) + throws SbomException { + try (InputStream stream = new FileInputStream(filePath); ) { String documentUri = modelStore.deSerialize(stream, false); SpdxDocument doc = new SpdxDocument(modelStore, documentUri, null, false); return doc; @@ -140,7 +135,7 @@ private SpdxDocument deserializeSpdxFile(String filePath, ISerializableModelStor throw new SbomException("No SPDX file found", e); } catch (IOException e) { throw new SbomException("Could not read SPDX file", e); - } catch(InvalidSPDXAnalysisException e) { + } catch (InvalidSPDXAnalysisException e) { throw new SbomException("Invalid SPDX file", e); } catch (Exception e) { throw new SbomException("Could not validate SPDX file", e); diff --git a/src/main/java/com/alvarium/annotators/vulnerability/GoModHandler.java b/src/main/java/com/alvarium/annotators/vulnerability/GoModHandler.java index a4ba597..2ded20e 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/GoModHandler.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/GoModHandler.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; import java.io.BufferedReader; @@ -21,104 +20,101 @@ import java.util.HashMap; import java.util.Map; - public class GoModHandler implements PackageFileHandler { - final private File file; + private final File file; - protected GoModHandler(String dir) { - this.file = new File(dir + "/" + "go.mod"); - } + protected GoModHandler(String dir) { + this.file = new File(dir + "/" + "go.mod"); + } - @Override - public String getFileName() { - return this.file.getName(); - } + @Override + public String getFileName() { + return this.file.getName(); + } - @Override - public Map getPackages() throws VulnerabilityException { - Map packages = new HashMap<>(); + @Override + public Map getPackages() throws VulnerabilityException { + Map packages = new HashMap<>(); - try (BufferedReader reader = new BufferedReader(new FileReader(file))) { - String line; - boolean inRequireBlock = false; - boolean inReplaceBlock = false; - while ((line = reader.readLine()) != null) { - line = line.trim(); - if (this.isRequireBlock(line)) { - inRequireBlock = true; - continue; - } - if (this.isReplaceBlock(line)) { - inReplaceBlock = true; - continue; - } - if (line.startsWith(")")) { - inRequireBlock = false; - inReplaceBlock = false; - continue; - } - if (inRequireBlock) { - String[] parts = line.split("\\s+"); - if (parts.length >= 2) { - String path = parts[0]; - String version = parts[1]; - packages.put(path, version); - } - continue; - } - if (this.isInlineRequire(line)) { - String[] parts = line.split("\\s+"); - String path = parts[1]; - String version = parts[2]; - packages.put(path, version); - continue; - } - if (inReplaceBlock) { - String[] parts = line.split("\\s+"); - if (parts.length == 5) { - packages.remove(parts[0]); - packages.put(parts[3], parts[4]); - } - continue; - } - if (this.isInlineReplace(line)) { - String[] parts = line.split("\\s+"); - packages.remove(parts[1]); - packages.put(parts[4], parts[5]); - continue; - } - } - reader.close(); - } catch (IOException e) { - throw new VulnerabilityException("Failed to read go.mod file", e); + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + String line; + boolean inRequireBlock = false; + boolean inReplaceBlock = false; + while ((line = reader.readLine()) != null) { + line = line.trim(); + if (this.isRequireBlock(line)) { + inRequireBlock = true; + continue; + } + if (this.isReplaceBlock(line)) { + inReplaceBlock = true; + continue; + } + if (line.startsWith(")")) { + inRequireBlock = false; + inReplaceBlock = false; + continue; + } + if (inRequireBlock) { + String[] parts = line.split("\\s+"); + if (parts.length >= 2) { + String path = parts[0]; + String version = parts[1]; + packages.put(path, version); + } + continue; + } + if (this.isInlineRequire(line)) { + String[] parts = line.split("\\s+"); + String path = parts[1]; + String version = parts[2]; + packages.put(path, version); + continue; } - return packages; + if (inReplaceBlock) { + String[] parts = line.split("\\s+"); + if (parts.length == 5) { + packages.remove(parts[0]); + packages.put(parts[3], parts[4]); + } + continue; + } + if (this.isInlineReplace(line)) { + String[] parts = line.split("\\s+"); + packages.remove(parts[1]); + packages.put(parts[4], parts[5]); + continue; + } + } + reader.close(); + } catch (IOException e) { + throw new VulnerabilityException("Failed to read go.mod file", e); } + return packages; + } - @Override - public boolean exists() { - return this.file.exists(); - } - - private boolean isRequireBlock(String line) { - String[] parts = line.split("\\s+"); - return line.startsWith("require(") || - (line.startsWith("require") && parts.length == 2); - } + @Override + public boolean exists() { + return this.file.exists(); + } - private boolean isInlineRequire(String line) { - String[] parts = line.split("\\s+"); - return line.startsWith("require ") && parts.length == 3; - } + private boolean isRequireBlock(String line) { + String[] parts = line.split("\\s+"); + return line.startsWith("require(") || (line.startsWith("require") && parts.length == 2); + } - private boolean isReplaceBlock(String line) { - String[] parts = line.split("\\s+"); - return line.startsWith("replace(") || - (line.startsWith("replace") && parts.length == 2); - } + private boolean isInlineRequire(String line) { + String[] parts = line.split("\\s+"); + return line.startsWith("require ") && parts.length == 3; + } - private boolean isInlineReplace(String line) { - String[] parts = line.split("\\s+"); - return line.startsWith("replace ") && parts.length == 6; - } + private boolean isReplaceBlock(String line) { + String[] parts = line.split("\\s+"); + return line.startsWith("replace(") || (line.startsWith("replace") && parts.length == 2); + } + + private boolean isInlineReplace(String line) { + String[] parts = line.split("\\s+"); + return line.startsWith("replace ") && parts.length == 6; + } } diff --git a/src/main/java/com/alvarium/annotators/vulnerability/MavenHandler.java b/src/main/java/com/alvarium/annotators/vulnerability/MavenHandler.java index 233fabb..7d38c82 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/MavenHandler.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/MavenHandler.java @@ -1,24 +1,22 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -29,73 +27,60 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException; - public class MavenHandler implements PackageFileHandler { - final private File file; + private final File file; - protected MavenHandler(String dir) { - this.file = new File(dir + "/" + "pom.xml"); - } + protected MavenHandler(String dir) { + this.file = new File(dir + "/" + "pom.xml"); + } - @Override - public String getFileName() { - return this.file.getName(); - } + @Override + public String getFileName() { + return this.file.getName(); + } - @Override - public Map getPackages() throws VulnerabilityException { - final Map packages = new HashMap(); + @Override + public Map getPackages() throws VulnerabilityException { + final Map packages = new HashMap(); - final Document pom = this.getDocument(); - NodeList deps = pom.getElementsByTagName("dependency"); - for (int i = 0; i < deps.getLength(); i++) { - Node node = deps.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element dep = (Element) node; - String groupId = dep.getElementsByTagName("groupId").item(0).getTextContent(); - String artifactId = dep.getElementsByTagName("artifactId").item(0).getTextContent(); - String version = dep.getElementsByTagName("version").item(0).getTextContent(); - packages.put( - String.format("%s:%s", groupId, artifactId), - version - ); - } - } - return packages; + final Document pom = this.getDocument(); + NodeList deps = pom.getElementsByTagName("dependency"); + for (int i = 0; i < deps.getLength(); i++) { + Node node = deps.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element dep = (Element) node; + String groupId = dep.getElementsByTagName("groupId").item(0).getTextContent(); + String artifactId = dep.getElementsByTagName("artifactId").item(0).getTextContent(); + String version = dep.getElementsByTagName("version").item(0).getTextContent(); + packages.put(String.format("%s:%s", groupId, artifactId), version); + } } + return packages; + } - @Override - public boolean exists() { - return this.file.exists(); - } + @Override + public boolean exists() { + return this.file.exists(); + } - private Document getDocument() throws VulnerabilityException { - try { - final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - final Document doc = documentBuilder.parse(this.file); - doc.getDocumentElement().normalize(); - return doc; - } catch (ParserConfigurationException e) { - throw new VulnerabilityException( - "Failed to configure XML reader, could not read package info from pom.xml", - e - ); - } catch (IOException e) { - throw new VulnerabilityException( - "Failed to read file, could not read package info from pom.xml", - e - ); - } catch (SAXException e) { - throw new VulnerabilityException( - "Bad XML file, could not read package info from pom.xml", - e - ); - } catch (Exception e) { - throw new VulnerabilityException( - "Could not read package info from pom.xml", - e - ); - } + private Document getDocument() throws VulnerabilityException { + try { + final DocumentBuilder documentBuilder = + DocumentBuilderFactory.newInstance().newDocumentBuilder(); + final Document doc = documentBuilder.parse(this.file); + doc.getDocumentElement().normalize(); + return doc; + } catch (ParserConfigurationException e) { + throw new VulnerabilityException( + "Failed to configure XML reader, could not read package info from pom.xml", e); + } catch (IOException e) { + throw new VulnerabilityException( + "Failed to read file, could not read package info from pom.xml", e); + } catch (SAXException e) { + throw new VulnerabilityException( + "Bad XML file, could not read package info from pom.xml", e); + } catch (Exception e) { + throw new VulnerabilityException("Could not read package info from pom.xml", e); } - + } } diff --git a/src/main/java/com/alvarium/annotators/vulnerability/OsvApiHandler.java b/src/main/java/com/alvarium/annotators/vulnerability/OsvApiHandler.java index 5f8fb54..da32e5f 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/OsvApiHandler.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/OsvApiHandler.java @@ -1,80 +1,81 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; - -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; - -import com.google.gson.Gson; - -public class OsvApiHandler implements VulnerabilityApiHandler { - final private Gson gson = new Gson(); - final private VulnerabilityAnnotatorConfig cfg; - - public OsvApiHandler(VulnerabilityAnnotatorConfig cfg) { - this.cfg = cfg; - } - - private OsvBatchResponse makeApiCall(Map packages) throws VulnerabilityException { - try { - // Create the HTTP client and POST request - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost httpPost = new HttpPost(this.cfg.getQueryBatchPath()); - - // Set the request body - OsvBatchRequest req = new OsvBatchRequest(packages); - StringEntity entity = new StringEntity(gson.toJson(req), StandardCharsets.UTF_8); - httpPost.setEntity(entity); - - // Set the content type header - httpPost.setHeader("Content-Type", "application/json"); - - // Execute the request - CloseableHttpResponse response = httpClient.execute(httpPost); - - // Get the response body - HttpEntity responseEntity = response.getEntity(); - String responseBody = responseEntity != null ? EntityUtils.toString(responseEntity) : null; - - OsvBatchResponse responseBatch = gson.fromJson(responseBody, OsvBatchResponse.class); - - // Close the response and the client - response.close(); - httpClient.close(); - - return responseBatch; - } catch (IOException e) { - throw new VulnerabilityException("Error making API call: " + e.getMessage(), e); - } - } - - - public List getVulnerabilityIds(Map packages) throws VulnerabilityException { - OsvBatchResponse response = makeApiCall(packages); - final List vulnerabilitiyIds = response.getVulnerabilityIds(); - - return vulnerabilitiyIds; - } - -} +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; + +public class OsvApiHandler implements VulnerabilityApiHandler { + private final Gson gson = new Gson(); + private final VulnerabilityAnnotatorConfig cfg; + + public OsvApiHandler(VulnerabilityAnnotatorConfig cfg) { + this.cfg = cfg; + } + + private OsvBatchResponse makeApiCall(Map packages) + throws VulnerabilityException { + try { + // Create the HTTP client and POST request + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(this.cfg.getQueryBatchPath()); + + // Set the request body + OsvBatchRequest req = new OsvBatchRequest(packages); + StringEntity entity = new StringEntity(gson.toJson(req), StandardCharsets.UTF_8); + httpPost.setEntity(entity); + + // Set the content type header + httpPost.setHeader("Content-Type", "application/json"); + + // Execute the request + CloseableHttpResponse response = httpClient.execute(httpPost); + + // Get the response body + HttpEntity responseEntity = response.getEntity(); + String responseBody = + responseEntity != null ? EntityUtils.toString(responseEntity) : null; + + OsvBatchResponse responseBatch = gson.fromJson(responseBody, OsvBatchResponse.class); + + // Close the response and the client + response.close(); + httpClient.close(); + + return responseBatch; + } catch (IOException e) { + throw new VulnerabilityException("Error making API call: " + e.getMessage(), e); + } + } + + public List getVulnerabilityIds(Map packages) + throws VulnerabilityException { + OsvBatchResponse response = makeApiCall(packages); + final List vulnerabilitiyIds = response.getVulnerabilityIds(); + + return vulnerabilitiyIds; + } +} diff --git a/src/main/java/com/alvarium/annotators/vulnerability/OsvBatchRequest.java b/src/main/java/com/alvarium/annotators/vulnerability/OsvBatchRequest.java index 7d4c029..9231903 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/OsvBatchRequest.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/OsvBatchRequest.java @@ -1,54 +1,54 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.google.gson.annotations.SerializedName; - -public class OsvBatchRequest { - public List queries; - - OsvBatchRequest(Map packages) { - queries = new ArrayList(); - for (Map.Entry entry : packages.entrySet()) { - Package packageInfo = new Package(entry.getKey()); - queries.add(new Query(entry.getValue(), packageInfo)); - } - } - - static class Query { - @SerializedName("package") // package is a reserved keyword in Java - public Package packageInfo; - public String version; - - Query(String version, Package packageInfo) { - this.version = version; - this.packageInfo = packageInfo; - } - } - - static class Package { - public String name; - public String ecosystem; - - Package(String name) { - this.name = name; - this.ecosystem = "Maven"; - } - } - -} +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + +public class OsvBatchRequest { + public List queries; + + OsvBatchRequest(Map packages) { + queries = new ArrayList(); + for (Map.Entry entry : packages.entrySet()) { + Package packageInfo = new Package(entry.getKey()); + queries.add(new Query(entry.getValue(), packageInfo)); + } + } + + static class Query { + @SerializedName("package") // package is a reserved keyword in Java + public Package packageInfo; + + public String version; + + Query(String version, Package packageInfo) { + this.version = version; + this.packageInfo = packageInfo; + } + } + + static class Package { + public String name; + public String ecosystem; + + Package(String name) { + this.name = name; + this.ecosystem = "Maven"; + } + } +} diff --git a/src/main/java/com/alvarium/annotators/vulnerability/OsvBatchResponse.java b/src/main/java/com/alvarium/annotators/vulnerability/OsvBatchResponse.java index ba2e84c..7baedd8 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/OsvBatchResponse.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/OsvBatchResponse.java @@ -1,54 +1,54 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -import java.util.ArrayList; -import java.util.List; - -public class OsvBatchResponse { - - public List results; - - public List getVulnerabilityIds() { - List vulnerabilitiesIds = new ArrayList<>(); - for (Result result : results) { - if (result.vulns != null) { - for (Vulnerability vuln : result.vulns) { - if (vuln != null) { - vulnerabilitiesIds.add(vuln.id); - } - } - } - } - return vulnerabilitiesIds; - } - static class Result { - public List vulns; - - public Result(List vulns) { - this.vulns = vulns; - } - } - - static class Vulnerability { - public String id; - public String modified; - - public Vulnerability(String id, String modified) { - this.id = id; - this.modified = modified; - } - } - -} \ No newline at end of file +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +import java.util.ArrayList; +import java.util.List; + +public class OsvBatchResponse { + + public List results; + + public List getVulnerabilityIds() { + List vulnerabilitiesIds = new ArrayList<>(); + for (Result result : results) { + if (result.vulns != null) { + for (Vulnerability vuln : result.vulns) { + if (vuln != null) { + vulnerabilitiesIds.add(vuln.id); + } + } + } + } + return vulnerabilitiesIds; + } + + static class Result { + public List vulns; + + public Result(List vulns) { + this.vulns = vulns; + } + } + + static class Vulnerability { + public String id; + public String modified; + + public Vulnerability(String id, String modified) { + this.id = id; + this.modified = modified; + } + } +} diff --git a/src/main/java/com/alvarium/annotators/vulnerability/PackageFileHandler.java b/src/main/java/com/alvarium/annotators/vulnerability/PackageFileHandler.java index 5678180..a4ceb61 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/PackageFileHandler.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/PackageFileHandler.java @@ -1,25 +1,24 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; import java.util.Map; - public interface PackageFileHandler { - String getFileName(); - Map getPackages() throws VulnerabilityException; - boolean exists(); -} + String getFileName(); + Map getPackages() throws VulnerabilityException; + + boolean exists(); +} diff --git a/src/main/java/com/alvarium/annotators/vulnerability/PackageFileHandlerFactory.java b/src/main/java/com/alvarium/annotators/vulnerability/PackageFileHandlerFactory.java index e90dd2c..cbd9c69 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/PackageFileHandlerFactory.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/PackageFileHandlerFactory.java @@ -1,33 +1,29 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; public class PackageFileHandlerFactory { - - public PackageFileHandler getHandler(String dir) throws VulnerabilityException { - final PackageFileHandler[] handlers = { - new MavenHandler(dir), - new GoModHandler(dir) - }; - for (PackageFileHandler h : handlers) { - if(h.exists()) { - return h; - } - } + public PackageFileHandler getHandler(String dir) throws VulnerabilityException { + final PackageFileHandler[] handlers = {new MavenHandler(dir), new GoModHandler(dir)}; - throw new VulnerabilityException("Could not find a supported package file"); + for (PackageFileHandler h : handlers) { + if (h.exists()) { + return h; + } } + + throw new VulnerabilityException("Could not find a supported package file"); + } } diff --git a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityAnnotatorConfig.java b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityAnnotatorConfig.java index 1516fa6..ec3c592 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityAnnotatorConfig.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityAnnotatorConfig.java @@ -1,74 +1,70 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; - import com.alvarium.annotators.AnnotatorConfig; import com.alvarium.contracts.AnnotationType; import com.alvarium.utils.ServiceInfo; - public class VulnerabilityAnnotatorConfig extends AnnotatorConfig { - private final VulnerabilityProviderType type; - private final ServiceInfo provider; - private final EndpointPaths paths; - + private final VulnerabilityProviderType type; + private final ServiceInfo provider; + private final EndpointPaths paths; - VulnerabilityAnnotatorConfig(ServiceInfo provider, VulnerabilityProviderType type, EndpointPaths paths) { - super(AnnotationType.VULNERABILITY); - this.provider = provider; - this.type = type; - this.paths = paths; - } + VulnerabilityAnnotatorConfig( + ServiceInfo provider, VulnerabilityProviderType type, EndpointPaths paths) { + super(AnnotationType.VULNERABILITY); + this.provider = provider; + this.type = type; + this.paths = paths; + } - public ServiceInfo getProvider() { - return this.provider; - } + public ServiceInfo getProvider() { + return this.provider; + } - public VulnerabilityProviderType getProviderType() { - return this.type; - } + public VulnerabilityProviderType getProviderType() { + return this.type; + } - public String getQueryBatchPath() { - return this.provider.uri() + this.paths.getBatchQuery(); - } + public String getQueryBatchPath() { + return this.provider.uri() + this.paths.getBatchQuery(); + } - public String getQueryPath() { - return this.provider.uri() + this.paths.getQuery(); - } + public String getQueryPath() { + return this.provider.uri() + this.paths.getQuery(); + } - /** - * Holder for the API's endpoint query paths - */ - static class EndpointPaths { - private final String queryBatch; - private final String query; + /** + * Holder for the API's endpoint query paths + */ + static class EndpointPaths { + private final String queryBatch; + private final String query; - public EndpointPaths(String queryBatch, String query) { - this.queryBatch = queryBatch; - this.query = query; - } + public EndpointPaths(String queryBatch, String query) { + this.queryBatch = queryBatch; + this.query = query; + } - String getBatchQuery() { - return this.queryBatch; - } + String getBatchQuery() { + return this.queryBatch; + } - String getQuery() { - return this.query; - } - } - + String getQuery() { + return this.query; + } + } } diff --git a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandler.java b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandler.java index f815dea..dd7e01d 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandler.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandler.java @@ -1,23 +1,21 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -import java.util.List; -import java.util.Map; - - -public interface VulnerabilityApiHandler { - List getVulnerabilityIds(Map packages) throws VulnerabilityException; - -} \ No newline at end of file +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +import java.util.List; +import java.util.Map; + +public interface VulnerabilityApiHandler { + List getVulnerabilityIds(Map packages) throws VulnerabilityException; +} diff --git a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandlerFactory.java b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandlerFactory.java index 1e3533c..bb67abc 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandlerFactory.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandlerFactory.java @@ -1,27 +1,27 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -public class VulnerabilityApiHandlerFactory { - public VulnerabilityApiHandler getHandler(VulnerabilityAnnotatorConfig cfg - ) throws VulnerabilityException { - //switch case on apiProvider - switch (cfg.getProviderType()) { - case OSV: - return new OsvApiHandler(cfg); - default: - throw new VulnerabilityException("Vulnerability api provider not found"); - } - } -} +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +public class VulnerabilityApiHandlerFactory { + public VulnerabilityApiHandler getHandler(VulnerabilityAnnotatorConfig cfg) + throws VulnerabilityException { + // switch case on apiProvider + switch (cfg.getProviderType()) { + case OSV: + return new OsvApiHandler(cfg); + default: + throw new VulnerabilityException("Vulnerability api provider not found"); + } + } +} diff --git a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityException.java b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityException.java index 385b257..a9f09af 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityException.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityException.java @@ -1,25 +1,24 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; public class VulnerabilityException extends Exception { - public VulnerabilityException(String msg) { - super(msg); - } - - public VulnerabilityException(String msg, Exception e) { - super(msg, e); - } + public VulnerabilityException(String msg) { + super(msg); + } + + public VulnerabilityException(String msg, Exception e) { + super(msg, e); + } } diff --git a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityProviderType.java b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityProviderType.java index a80c162..f706f84 100644 --- a/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityProviderType.java +++ b/src/main/java/com/alvarium/annotators/vulnerability/VulnerabilityProviderType.java @@ -1,22 +1,21 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; import com.google.gson.annotations.SerializedName; public enum VulnerabilityProviderType { - @SerializedName("osv") - OSV + @SerializedName("osv") + OSV } diff --git a/src/main/java/com/alvarium/contracts/Annotation.java b/src/main/java/com/alvarium/contracts/Annotation.java index 4991d29..36b8d81 100644 --- a/src/main/java/com/alvarium/contracts/Annotation.java +++ b/src/main/java/com/alvarium/contracts/Annotation.java @@ -1,20 +1,18 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.contracts; - import java.io.Serializable; import java.time.Instant; @@ -30,7 +28,7 @@ * this will be generated by the annotators. */ public class Annotation implements Serializable { - private final String id; + private final String id; private final String key; private final HashType hash; private final String host; @@ -41,15 +39,24 @@ public class Annotation implements Serializable { private final Boolean isSatisfied; private final Instant timestamp; // TagEnvKey is an environment key used to associate annotations with specific metadata, - // aiding in the linkage of scores across different layers of the stack. For instance, in the "app" layer, + // aiding in the linkage of scores across different layers of the stack. For instance, in the + // "app" layer, // it is utilized to retrieve the commit SHA of the workload where the application is running, - // which is instrumental in tracing the impact on the current layer's score from the lower layers. + // which is instrumental in tracing the impact on the current layer's score from the lower + // layers. public static final String TAG_ENV_KEY = "TAG"; - public Annotation(String key, HashType hash, String host, LayerType layer, AnnotationType kind, String signature, - Boolean isSatisfied, Instant timestamp) { + public Annotation( + String key, + HashType hash, + String host, + LayerType layer, + AnnotationType kind, + String signature, + Boolean isSatisfied, + Instant timestamp) { ULID ulid = new ULID(); - this.id = ulid.nextULID(); + this.id = ulid.nextULID(); this.key = key; this.hash = hash; this.host = host; @@ -58,85 +65,89 @@ public Annotation(String key, HashType hash, String host, LayerType layer, Annot this.kind = kind; this.signature = signature; this.isSatisfied = isSatisfied; - this.timestamp = timestamp; - } - - //setters - - public void setSignature(String signature) { - this.signature = signature; - } - - // getters - - public String getId() { - return this.id; - } - - public String getKey() { - return this.key; - } - - public HashType getHash() { - return this.hash; - } - - public String getHost() { - return this.host; - } - - public String getTag() { - return this.tag; - } + this.timestamp = timestamp; + } - public LayerType getLayer() { - return this.layer; - } - - public AnnotationType getKind() { - return this.kind; - } - - public String getSignature() { - return this.signature; - } - - public Boolean getIsSatisfied() { - return this.isSatisfied; - } + // setters - public Instant getTimestamp() { - return this.timestamp; - } - - /** - * returns the JSON representation of the Annotation object - * @return json string representation - */ - public String toJson() { - Gson gson = new GsonBuilder().registerTypeAdapter(Instant.class, new InstantConverter()) - .create(); - return gson.toJson(this, Annotation.class); - } - - /** - * instaniates an Annotation object from a json representation - * @param json input JSON string - * @return Annotation Object - */ - public static Annotation fromJson(String json) { - Gson gson = new GsonBuilder().registerTypeAdapter(Instant.class, new InstantConverter()) - .create(); - return gson.fromJson(json, Annotation.class); - } - - private String getTagValue(LayerType layer) { - switch(layer){ - case Application: - return System.getenv(TAG_ENV_KEY) == null ? "" : System.getenv(TAG_ENV_KEY); - default: - break; - } - return ""; + public void setSignature(String signature) { + this.signature = signature; + } + + // getters + + public String getId() { + return this.id; + } + + public String getKey() { + return this.key; + } + + public HashType getHash() { + return this.hash; + } + + public String getHost() { + return this.host; + } + + public String getTag() { + return this.tag; + } + + public LayerType getLayer() { + return this.layer; + } + + public AnnotationType getKind() { + return this.kind; + } + + public String getSignature() { + return this.signature; + } + + public Boolean getIsSatisfied() { + return this.isSatisfied; + } + + public Instant getTimestamp() { + return this.timestamp; + } + + /** + * returns the JSON representation of the Annotation object + * @return json string representation + */ + public String toJson() { + Gson gson = + new GsonBuilder() + .registerTypeAdapter(Instant.class, new InstantConverter()) + .create(); + return gson.toJson(this, Annotation.class); + } + + /** + * instaniates an Annotation object from a json representation + * @param json input JSON string + * @return Annotation Object + */ + public static Annotation fromJson(String json) { + Gson gson = + new GsonBuilder() + .registerTypeAdapter(Instant.class, new InstantConverter()) + .create(); + return gson.fromJson(json, Annotation.class); + } + + private String getTagValue(LayerType layer) { + switch (layer) { + case Application: + return System.getenv(TAG_ENV_KEY) == null ? "" : System.getenv(TAG_ENV_KEY); + default: + break; } + return ""; + } } diff --git a/src/main/java/com/alvarium/contracts/AnnotationList.java b/src/main/java/com/alvarium/contracts/AnnotationList.java index 1f1618a..1583e86 100644 --- a/src/main/java/com/alvarium/contracts/AnnotationList.java +++ b/src/main/java/com/alvarium/contracts/AnnotationList.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.contracts; import java.util.List; @@ -20,7 +19,6 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; - /** * A wrapper over the list of annotations */ @@ -30,7 +28,7 @@ public class AnnotationList { public AnnotationList(Annotation[] annotations) { this.items = List.of(annotations); } - + public AnnotationList(List annotations) { this.items = annotations; } @@ -40,18 +38,20 @@ public List getAnnotations() { } public String toJson() { - Gson gson = new GsonBuilder() - .registerTypeAdapter(Annotation.class, new AnnotationConverter()) - .create(); + Gson gson = + new GsonBuilder() + .registerTypeAdapter(Annotation.class, new AnnotationConverter()) + .create(); return gson.toJson(this); } public static AnnotationList fromJson(String json) { - Gson gson = new GsonBuilder() - .registerTypeAdapter(Annotation.class, new AnnotationConverter()) - .create(); - + Gson gson = + new GsonBuilder() + .registerTypeAdapter(Annotation.class, new AnnotationConverter()) + .create(); + return gson.fromJson(json, AnnotationList.class); } } diff --git a/src/main/java/com/alvarium/contracts/AnnotationType.java b/src/main/java/com/alvarium/contracts/AnnotationType.java index 6b4bd89..08ce5ca 100644 --- a/src/main/java/com/alvarium/contracts/AnnotationType.java +++ b/src/main/java/com/alvarium/contracts/AnnotationType.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.contracts; import com.google.gson.annotations.SerializedName; diff --git a/src/main/java/com/alvarium/contracts/DerivedComponent.java b/src/main/java/com/alvarium/contracts/DerivedComponent.java index 0f123fa..b861082 100644 --- a/src/main/java/com/alvarium/contracts/DerivedComponent.java +++ b/src/main/java/com/alvarium/contracts/DerivedComponent.java @@ -1,22 +1,20 @@ - /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.contracts; -import java.util.Map; import java.util.HashMap; +import java.util.Map; public enum DerivedComponent { METHOD("@method"), diff --git a/src/main/java/com/alvarium/contracts/LayerType.java b/src/main/java/com/alvarium/contracts/LayerType.java index 702b965..b5a082d 100644 --- a/src/main/java/com/alvarium/contracts/LayerType.java +++ b/src/main/java/com/alvarium/contracts/LayerType.java @@ -1,28 +1,27 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.contracts; import com.google.gson.annotations.SerializedName; public enum LayerType { - @SerializedName("app") - Application, - @SerializedName("cicd") - CiCd, - @SerializedName("os") - Os, - @SerializedName("host") - Host; + @SerializedName("app") + Application, + @SerializedName("cicd") + CiCd, + @SerializedName("os") + Os, + @SerializedName("host") + Host; } - diff --git a/src/main/java/com/alvarium/hash/HashInfo.java b/src/main/java/com/alvarium/hash/HashInfo.java index 206d56c..f329885 100644 --- a/src/main/java/com/alvarium/hash/HashInfo.java +++ b/src/main/java/com/alvarium/hash/HashInfo.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; import java.io.Serializable; @@ -28,7 +27,7 @@ public HashInfo(HashType type) { this.type = type; } - public HashType getType(){ + public HashType getType() { return this.type; } diff --git a/src/main/java/com/alvarium/hash/HashProvider.java b/src/main/java/com/alvarium/hash/HashProvider.java index c7a20fc..632f65f 100644 --- a/src/main/java/com/alvarium/hash/HashProvider.java +++ b/src/main/java/com/alvarium/hash/HashProvider.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; /** @@ -19,7 +19,7 @@ */ public interface HashProvider { /** - * converts a byte array of data to it's hash value + * converts a byte array of data to it's hash value * @param data byte array of data * @return hashed value of the given data */ @@ -31,9 +31,9 @@ public interface HashProvider { * @return new hashed value of the given data */ void update(byte[] data); - + /** - * Updates the hash with new input data. Useful when hashing large byte arrays in chunks + * Updates the hash with new input data. Useful when hashing large byte arrays in chunks * where the offset and length parameters can prevent alloting * padded 0's to the digest when the input buffer is partially filled * @param data byte array of data @@ -46,7 +46,7 @@ public interface HashProvider { /** * Gets the current hash, resets any saved values from previous update() * calls - * @return the final hashing result of previous update() calls + * @return the final hashing result of previous update() calls */ String getValue(); } diff --git a/src/main/java/com/alvarium/hash/HashProviderFactory.java b/src/main/java/com/alvarium/hash/HashProviderFactory.java index 8c46f05..fe89e59 100644 --- a/src/main/java/com/alvarium/hash/HashProviderFactory.java +++ b/src/main/java/com/alvarium/hash/HashProviderFactory.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; public class HashProviderFactory { @@ -25,10 +24,7 @@ public HashProvider getProvider(HashType type) throws HashTypeException { case NoHash: return new NoneProvider(); default: - throw new HashTypeException(String.format("type %s is not supported" - , type)); + throw new HashTypeException(String.format("type %s is not supported", type)); } - } - + } } - diff --git a/src/main/java/com/alvarium/hash/HashType.java b/src/main/java/com/alvarium/hash/HashType.java index f604d54..5130b4d 100644 --- a/src/main/java/com/alvarium/hash/HashType.java +++ b/src/main/java/com/alvarium/hash/HashType.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; import com.google.gson.annotations.SerializedName; diff --git a/src/main/java/com/alvarium/hash/HashTypeException.java b/src/main/java/com/alvarium/hash/HashTypeException.java index 25517f7..b4bbc8d 100644 --- a/src/main/java/com/alvarium/hash/HashTypeException.java +++ b/src/main/java/com/alvarium/hash/HashTypeException.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; public class HashTypeException extends Exception { diff --git a/src/main/java/com/alvarium/hash/Md5Provider.java b/src/main/java/com/alvarium/hash/Md5Provider.java index b9bf189..6e19f29 100644 --- a/src/main/java/com/alvarium/hash/Md5Provider.java +++ b/src/main/java/com/alvarium/hash/Md5Provider.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; import java.security.MessageDigest; @@ -18,10 +18,10 @@ import com.alvarium.utils.Encoder; -class Md5Provider implements HashProvider{ +class Md5Provider implements HashProvider { private final MessageDigest md5; - protected Md5Provider() throws HashTypeException{ + protected Md5Provider() throws HashTypeException { try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { diff --git a/src/main/java/com/alvarium/hash/NoneProvider.java b/src/main/java/com/alvarium/hash/NoneProvider.java index 3bd945a..051a4d6 100644 --- a/src/main/java/com/alvarium/hash/NoneProvider.java +++ b/src/main/java/com/alvarium/hash/NoneProvider.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; import java.util.Arrays; diff --git a/src/main/java/com/alvarium/hash/Sha256Provider.java b/src/main/java/com/alvarium/hash/Sha256Provider.java index d4531e4..b1add91 100644 --- a/src/main/java/com/alvarium/hash/Sha256Provider.java +++ b/src/main/java/com/alvarium/hash/Sha256Provider.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; import java.security.MessageDigest; @@ -35,7 +35,7 @@ protected Sha256Provider() throws HashTypeException { public String derive(byte[] data) { final byte[] hashedBytes = this.sha256.digest(data); final String hashedString = Encoder.bytesToHex(hashedBytes); - return hashedString; + return hashedString; } @Override diff --git a/src/main/java/com/alvarium/serializers/AnnotationConverter.java b/src/main/java/com/alvarium/serializers/AnnotationConverter.java index e957605..f5080d5 100644 --- a/src/main/java/com/alvarium/serializers/AnnotationConverter.java +++ b/src/main/java/com/alvarium/serializers/AnnotationConverter.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.serializers; import java.lang.reflect.Type; @@ -24,14 +23,15 @@ import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; - -public class AnnotationConverter implements JsonSerializer, JsonDeserializer { +public class AnnotationConverter + implements JsonSerializer, JsonDeserializer { public JsonElement serialize(Annotation src, Type typeOfSrc, JsonSerializationContext context) { - return JsonParser.parseString(src.toJson()); + return JsonParser.parseString(src.toJson()); } - public Annotation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + public Annotation deserialize( + JsonElement json, Type typeOfT, JsonDeserializationContext context) { return Annotation.fromJson(json.toString()); } } diff --git a/src/main/java/com/alvarium/serializers/AnnotatorConfigConverter.java b/src/main/java/com/alvarium/serializers/AnnotatorConfigConverter.java index 0b3fcea..859f6ec 100644 --- a/src/main/java/com/alvarium/serializers/AnnotatorConfigConverter.java +++ b/src/main/java/com/alvarium/serializers/AnnotatorConfigConverter.java @@ -1,23 +1,20 @@ - /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.serializers; import java.lang.reflect.Type; - import com.alvarium.annotators.AnnotatorConfig; import com.alvarium.annotators.MockAnnotatorConfig; import com.alvarium.annotators.sbom.SbomAnnotatorConfig; @@ -30,40 +27,32 @@ import com.google.gson.JsonObject; public class AnnotatorConfigConverter implements JsonDeserializer { - - public AnnotatorConfig deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context - ) { - JsonObject obj = json.getAsJsonObject(); - if (!obj.has("kind")) { - throw new IllegalArgumentException("Annotator config entry does not specify kind"); - } - Gson gson = new Gson(); - AnnotationType kind = gson.fromJson(obj.getAsJsonPrimitive("kind"), AnnotationType.class); - if (kind == null) { - throw new IllegalArgumentException("Invalid annotator kind provided in config"); - } - switch (kind) { - case MOCK: - MockAnnotatorConfig mockCfg = gson.fromJson(obj.toString(), MockAnnotatorConfig.class); - return mockCfg; - case VULNERABILITY: - VulnerabilityAnnotatorConfig vulnCfg = gson.fromJson( - obj, - VulnerabilityAnnotatorConfig.class - ); - return vulnCfg; - case SBOM: - SbomAnnotatorConfig sbomCfg = gson.fromJson( - obj, - SbomAnnotatorConfig.class - ); - return sbomCfg; - default: - return gson.fromJson(json, AnnotatorConfig.class); - } + + public AnnotatorConfig deserialize( + JsonElement json, Type typeOfT, JsonDeserializationContext context) { + JsonObject obj = json.getAsJsonObject(); + if (!obj.has("kind")) { + throw new IllegalArgumentException("Annotator config entry does not specify kind"); } + Gson gson = new Gson(); + AnnotationType kind = gson.fromJson(obj.getAsJsonPrimitive("kind"), AnnotationType.class); + if (kind == null) { + throw new IllegalArgumentException("Invalid annotator kind provided in config"); + } + switch (kind) { + case MOCK: + MockAnnotatorConfig mockCfg = + gson.fromJson(obj.toString(), MockAnnotatorConfig.class); + return mockCfg; + case VULNERABILITY: + VulnerabilityAnnotatorConfig vulnCfg = + gson.fromJson(obj, VulnerabilityAnnotatorConfig.class); + return vulnCfg; + case SBOM: + SbomAnnotatorConfig sbomCfg = gson.fromJson(obj, SbomAnnotatorConfig.class); + return sbomCfg; + default: + return gson.fromJson(json, AnnotatorConfig.class); + } + } } - diff --git a/src/main/java/com/alvarium/serializers/InstantConverter.java b/src/main/java/com/alvarium/serializers/InstantConverter.java index 614210a..8bf87cb 100644 --- a/src/main/java/com/alvarium/serializers/InstantConverter.java +++ b/src/main/java/com/alvarium/serializers/InstantConverter.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.serializers; import java.lang.reflect.Type; @@ -31,10 +30,10 @@ /** * A converter of Instant datatype to RFC3339 string representation and vice versa */ -public class InstantConverter implements JsonSerializer, JsonDeserializer{ +public class InstantConverter implements JsonSerializer, JsonDeserializer { public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) { - // a workaround to preserve the zone information + // a workaround to preserve the zone information DateTimeFormatter f = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()); ZonedDateTime zdt = ZonedDateTime.parse(DateTimeFormatter.ISO_INSTANT.format(src), f); String raw = zdt.toString(); diff --git a/src/main/java/com/alvarium/serializers/RetentionTypeConverter.java b/src/main/java/com/alvarium/serializers/RetentionTypeConverter.java index 273b2e5..ebbd388 100644 --- a/src/main/java/com/alvarium/serializers/RetentionTypeConverter.java +++ b/src/main/java/com/alvarium/serializers/RetentionTypeConverter.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.serializers; import java.lang.reflect.Type; @@ -29,15 +28,16 @@ * An adapter used to convert RetentionType enum to it's lowercase representation and vice versa. * It is used to to properly load config from json. */ -public class RetentionTypeConverter implements JsonSerializer, - JsonDeserializer { +public class RetentionTypeConverter + implements JsonSerializer, JsonDeserializer { - public JsonElement serialize(RetentionType src, Type typeOfSrc, JsonSerializationContext context) { - return new JsonPrimitive(src.name().toLowerCase()); + public JsonElement serialize( + RetentionType src, Type typeOfSrc, JsonSerializationContext context) { + return new JsonPrimitive(src.name().toLowerCase()); } - public RetentionType deserialize(JsonElement json, Type typeOfT, - JsonDeserializationContext context) { - return RetentionType.valueOf(json.getAsString().toUpperCase()); - } -} \ No newline at end of file + public RetentionType deserialize( + JsonElement json, Type typeOfT, JsonDeserializationContext context) { + return RetentionType.valueOf(json.getAsString().toUpperCase()); + } +} diff --git a/src/main/java/com/alvarium/serializers/StreamInfoConverter.java b/src/main/java/com/alvarium/serializers/StreamInfoConverter.java index 1c9211e..885a6c6 100644 --- a/src/main/java/com/alvarium/serializers/StreamInfoConverter.java +++ b/src/main/java/com/alvarium/serializers/StreamInfoConverter.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.serializers; import java.lang.reflect.Type; @@ -20,38 +19,35 @@ import com.alvarium.streams.PravegaConfig; import com.alvarium.streams.StreamInfo; import com.alvarium.streams.StreamType; -import com.google.gson.JsonDeserializer; import com.google.gson.Gson; import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** *

      Contains the logic for deserializing stream configs depending on their types

      - * + * *

      Any further stream implementations must have their config deserialization logic here

      - * + * *

      This is because the StreamInfo class must be able to pass down any different type of stream * config class (e.g. IotaConfig, MqttConfig, PravegaConfig).

      */ public class StreamInfoConverter implements JsonDeserializer { public StreamInfo deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context - ) { + JsonElement json, Type typeOfT, JsonDeserializationContext context) { Gson gson = new Gson(); JsonObject obj = json.getAsJsonObject(); StreamType type = gson.fromJson(obj.get("type"), StreamType.class); - switch(type){ - case MQTT: + switch (type) { + case MQTT: MqttConfig mqttConfig = MqttConfig.fromJson(obj.get("config").toString()); - return new StreamInfo(type,mqttConfig); + return new StreamInfo(type, mqttConfig); case PRAVEGA: PravegaConfig pravegaConfig = PravegaConfig.fromJson(obj.get("config").toString()); return new StreamInfo(type, pravegaConfig); - default: + default: return gson.fromJson(json, StreamInfo.class); - } + } } } diff --git a/src/main/java/com/alvarium/sign/Ed25519Provider.java b/src/main/java/com/alvarium/sign/Ed25519Provider.java index 86397d1..1bfc750 100644 --- a/src/main/java/com/alvarium/sign/Ed25519Provider.java +++ b/src/main/java/com/alvarium/sign/Ed25519Provider.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; import java.security.GeneralSecurityException; @@ -21,24 +20,23 @@ import com.google.crypto.tink.subtle.Ed25519Sign; import com.google.crypto.tink.subtle.Ed25519Verify; - public class Ed25519Provider implements SignProvider { protected Ed25519Provider() {} public String sign(byte[] key, byte[] content) throws SignException { - + // Private key passed as private key and public key appended to it - // so the private key of size 32-bytes is extracted + // so the private key of size 32-bytes is extracted final byte[] privateKey = Arrays.copyOfRange(key, 0, 32); final Ed25519Sign signer; try { signer = new Ed25519Sign(privateKey); - } catch(GeneralSecurityException e) { + } catch (GeneralSecurityException e) { throw new SignException("SHA-512 not defined in EngineFactory.MESSAGE_DIGEST", e); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new SignException("Invalid signing key", e); } catch (Exception e) { throw new SignException("Could not instantiate Ed25519Provider", e); @@ -48,9 +46,9 @@ public String sign(byte[] key, byte[] content) throws SignException { final byte[] signed = signer.sign(content); final String signedString = Encoder.bytesToHex(signed); return signedString; - } catch(GeneralSecurityException e) { + } catch (GeneralSecurityException e) { throw new SignException("Could not sign data", e); - } catch(Exception e) { + } catch (Exception e) { throw new SignException("Could not sign data", e); } } @@ -59,13 +57,12 @@ public void verify(byte[] key, byte[] content, byte[] signed) throws SignExcepti try { final Ed25519Verify verifier = new Ed25519Verify(key); verifier.verify(signed, content); - } catch(GeneralSecurityException e) { + } catch (GeneralSecurityException e) { throw new SignException("Verification did not pass", e); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new SignException("Invalid signing key", e); } catch (Exception e) { throw new SignException("Could not verify signature", e); } } - } diff --git a/src/main/java/com/alvarium/sign/KeyInfo.java b/src/main/java/com/alvarium/sign/KeyInfo.java index e559ae2..0b7e991 100644 --- a/src/main/java/com/alvarium/sign/KeyInfo.java +++ b/src/main/java/com/alvarium/sign/KeyInfo.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; import java.io.Serializable; @@ -23,7 +22,7 @@ */ public class KeyInfo implements Serializable { private final String path; - private final SignType type; + private final SignType type; public KeyInfo(String path, SignType type) { this.path = path; diff --git a/src/main/java/com/alvarium/sign/SignException.java b/src/main/java/com/alvarium/sign/SignException.java index 654be4c..ba18e1f 100644 --- a/src/main/java/com/alvarium/sign/SignException.java +++ b/src/main/java/com/alvarium/sign/SignException.java @@ -1,20 +1,19 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; -public class SignException extends Exception{ +public class SignException extends Exception { public SignException(String message, Exception e) { super(message, e, false, true); } diff --git a/src/main/java/com/alvarium/sign/SignProvider.java b/src/main/java/com/alvarium/sign/SignProvider.java index abe3468..4150c2d 100644 --- a/src/main/java/com/alvarium/sign/SignProvider.java +++ b/src/main/java/com/alvarium/sign/SignProvider.java @@ -1,27 +1,26 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; public interface SignProvider { /** * Uses a private key to sign content and returns the signature in hex format stored in a string - * - * The key parameter needs to be 64-byte in size where the private key is suffixed by + * + * The key parameter needs to be 64-byte in size where the private key is suffixed by * the public key (Some implementations will accept and use only the first 32-bytes of the * private key such as Ed25519) - * + * * @param key * @param content * @return signature @@ -37,4 +36,4 @@ public interface SignProvider { * @throws SignException when verification does not pass */ void verify(byte[] key, byte[] content, byte[] signed) throws SignException; -} +} diff --git a/src/main/java/com/alvarium/sign/SignProviderFactory.java b/src/main/java/com/alvarium/sign/SignProviderFactory.java index 1914901..d889cb1 100644 --- a/src/main/java/com/alvarium/sign/SignProviderFactory.java +++ b/src/main/java/com/alvarium/sign/SignProviderFactory.java @@ -1,28 +1,26 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; public class SignProviderFactory { public SignProvider getProvider(SignType type) throws SignException { - switch(type) { - case Ed25519: + switch (type) { + case Ed25519: return new Ed25519Provider(); default: throw new SignException("Concrete type not found: " + type.toString(), null); } } - -} \ No newline at end of file +} diff --git a/src/main/java/com/alvarium/sign/SignType.java b/src/main/java/com/alvarium/sign/SignType.java index e3ccc18..c661eec 100644 --- a/src/main/java/com/alvarium/sign/SignType.java +++ b/src/main/java/com/alvarium/sign/SignType.java @@ -1,21 +1,20 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; -import java.util.Map; import java.util.HashMap; +import java.util.Map; import com.google.gson.annotations.SerializedName; @@ -49,4 +48,4 @@ public static SignType fromString(String value) throws EnumConstantNotPresentExc } throw new EnumConstantNotPresentException(SignType.class, value); } -} \ No newline at end of file +} diff --git a/src/main/java/com/alvarium/sign/SignatureInfo.java b/src/main/java/com/alvarium/sign/SignatureInfo.java index 986f8d4..07fbca9 100644 --- a/src/main/java/com/alvarium/sign/SignatureInfo.java +++ b/src/main/java/com/alvarium/sign/SignatureInfo.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; import java.io.Serializable; @@ -24,7 +23,8 @@ */ public class SignatureInfo implements Serializable { @SerializedName(value = "public", alternate = "publicKey") - private final KeyInfo publicKey; + private final KeyInfo publicKey; + @SerializedName(value = "private", alternate = "privateKey") private final KeyInfo privateKey; diff --git a/src/main/java/com/alvarium/streams/MockStreamProvider.java b/src/main/java/com/alvarium/streams/MockStreamProvider.java index 98e8f5f..452be8b 100644 --- a/src/main/java/com/alvarium/streams/MockStreamProvider.java +++ b/src/main/java/com/alvarium/streams/MockStreamProvider.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import com.alvarium.PublishWrapper; @@ -24,11 +23,11 @@ class MockStreamProvider implements StreamProvider { public void connect() { System.out.println("stream connected"); } - + public void close() { System.out.println("stream closed"); } - + public void publish(PublishWrapper wrapper) { System.out.println(String.format("%s publish", wrapper.toJson())); } diff --git a/src/main/java/com/alvarium/streams/MqttConfig.java b/src/main/java/com/alvarium/streams/MqttConfig.java index 5e2c385..a6703c9 100644 --- a/src/main/java/com/alvarium/streams/MqttConfig.java +++ b/src/main/java/com/alvarium/streams/MqttConfig.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import java.io.Serializable; @@ -23,28 +22,29 @@ /** * Holds the configuration required to connect to an MQTT server and publish messages */ -public class MqttConfig implements Serializable { +public class MqttConfig implements Serializable { private final String clientId; private final String user; private final String password; private final int qos; + @SerializedName(value = "cleanness", alternate = "isClean") private final boolean isClean; + private final String[] topics; private final ServiceInfo provider; public MqttConfig( - String cliendId, - String user, - String password, - int qos, - boolean isClean, - String[] topics, - ServiceInfo provider - ) { + String cliendId, + String user, + String password, + int qos, + boolean isClean, + String[] topics, + ServiceInfo provider) { this.clientId = cliendId; this.user = user; - this.password= password; + this.password = password; this.qos = qos; this.isClean = isClean; this.topics = topics; @@ -62,7 +62,7 @@ public String getUser() { public String getPassword() { return this.password; } - + public int getQos() { return this.qos; } @@ -79,7 +79,6 @@ public ServiceInfo getProvider() { return this.provider; } - public String toJson() { Gson gson = new Gson(); return gson.toJson(this); @@ -89,5 +88,4 @@ public static MqttConfig fromJson(String json) { Gson gson = new Gson(); return gson.fromJson(json, MqttConfig.class); } - } diff --git a/src/main/java/com/alvarium/streams/MqttStreamProvider.java b/src/main/java/com/alvarium/streams/MqttStreamProvider.java index 34be620..ed7f3df 100644 --- a/src/main/java/com/alvarium/streams/MqttStreamProvider.java +++ b/src/main/java/com/alvarium/streams/MqttStreamProvider.java @@ -1,36 +1,34 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; - import com.alvarium.PublishWrapper; import org.eclipse.paho.client.mqttv3.IMqttClient; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; -import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.eclipse.paho.client.mqttv3.MqttPersistenceException; +import org.eclipse.paho.client.mqttv3.MqttSecurityException; /** * Responsible for connecting to an MQTT server and publishing messages to the provided topics */ public class MqttStreamProvider implements StreamProvider { - final private IMqttClient client; + private final IMqttClient client; final MqttConnectOptions options; - final private MqttConfig endpoint; + private final MqttConfig endpoint; final int publishTimeoutSeconds = 2; final int waitOnCloseMs = 250; @@ -43,53 +41,53 @@ public MqttStreamProvider(MqttConfig cfg) throws StreamException { this.options.setConnectionTimeout(publishTimeoutSeconds); try { this.client = new MqttClient(cfg.getProvider().uri(), cfg.getClientId()); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new StreamException("Invalid uri or cliendId", e); - } catch(MqttException e) { + } catch (MqttException e) { throw new StreamException("Could not instantiate client", e); } } public void connect() throws StreamException { - this.reconnect(); + this.reconnect(); } public void close() throws StreamException { try { client.disconnect(waitOnCloseMs); // Blocking till disconnect completes - } catch(MqttException e) { + } catch (MqttException e) { throw new StreamException("Could not close client", e); } } public void publish(PublishWrapper wrapper) throws StreamException { - if(!client.isConnected()) { + if (!client.isConnected()) { this.reconnect(); } - + final String payload = wrapper.toJson(); for (String topic : endpoint.getTopics()) { try { client.publish(topic, payload.getBytes(), endpoint.getQos(), false); - } catch(MqttPersistenceException e) { - throw new StreamException("Could not store message",e); - } catch(IllegalArgumentException e) { + } catch (MqttPersistenceException e) { + throw new StreamException("Could not store message", e); + } catch (IllegalArgumentException e) { throw new StreamException("Invalid QoS value", e); - } catch(MqttException e) { - throw new StreamException("Could not publish message",e); + } catch (MqttException e) { + throw new StreamException("Could not publish message", e); } + } } -} private void reconnect() throws StreamException { - if(!client.isConnected()) { + if (!client.isConnected()) { try { client.connect(options); - } catch(MqttSecurityException e) { + } catch (MqttSecurityException e) { throw new StreamException("Connection rejected: unsecure", e); - } catch(MqttException e) { + } catch (MqttException e) { throw new StreamException("Connection failed", e); - } + } } } } diff --git a/src/main/java/com/alvarium/streams/PravegaConfig.java b/src/main/java/com/alvarium/streams/PravegaConfig.java index 1cdb483..5fa284c 100644 --- a/src/main/java/com/alvarium/streams/PravegaConfig.java +++ b/src/main/java/com/alvarium/streams/PravegaConfig.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import java.io.Serializable; @@ -21,36 +20,40 @@ /** * A unit that encapsulates all of the important pravega related configuration. - * Most of the important fields are grabbed from here: + * Most of the important fields are grabbed from here: * https://pravega.io/docs/v0.6.0/basic-reader-and-writer/#creating-a-stream-and-the-streammanager-interface */ public class PravegaConfig implements Serializable { /** - * A field that determines how a Stream handles the varying changes in its load. + * A field that determines how a Stream handles the varying changes in its load. */ private final Integer scalingPolicy; + /** * The name of the scope under which the selected stream will live. */ - private final String scope; + private final String scope; + /** * The name of the stream under the chosen scope, which events will be written to. */ - private final String stream; + private final String stream; + /** * Used to group certain events together. */ private final String routingKey; + private final PravegaRetention retention; private final ServiceInfo provider; public PravegaConfig( - Integer scalingPolicy, - ServiceInfo provider, - String scope, - String stream, - String routingKey, - PravegaRetention retention) { + Integer scalingPolicy, + ServiceInfo provider, + String scope, + String stream, + String routingKey, + PravegaRetention retention) { this.scalingPolicy = scalingPolicy; this.provider = provider; this.scope = scope; @@ -75,11 +78,11 @@ public String getStream() { return this.stream; } - public String getRoutingKey(){ + public String getRoutingKey() { return this.routingKey; } - public PravegaRetention getRetention(){ + public PravegaRetention getRetention() { return this.retention; } diff --git a/src/main/java/com/alvarium/streams/PravegaRetention.java b/src/main/java/com/alvarium/streams/PravegaRetention.java index de81326..96eca03 100644 --- a/src/main/java/com/alvarium/streams/PravegaRetention.java +++ b/src/main/java/com/alvarium/streams/PravegaRetention.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import java.io.Serializable; @@ -30,33 +29,34 @@ class PravegaRetention implements Serializable { @JsonAdapter(RetentionTypeConverter.class) private final RetentionType type; - private final long min; - private final long max; - public PravegaRetention(RetentionType type, long min, long max){ + private final long min; + private final long max; + + public PravegaRetention(RetentionType type, long min, long max) { this.type = type; this.min = min; this.max = max; } - public RetentionType getType(){ + public RetentionType getType() { return this.type; } - public long getMin(){ + public long getMin() { return this.min; } - public long getMax(){ + public long getMax() { return this.max; } - public String toJson(){ + public String toJson() { Gson gson = new Gson(); return gson.toJson(this); } - public static PravegaRetention fromJson(String json){ + public static PravegaRetention fromJson(String json) { Gson gson = new Gson(); return gson.fromJson(json, PravegaRetention.class); } diff --git a/src/main/java/com/alvarium/streams/PravegaStreamProvider.java b/src/main/java/com/alvarium/streams/PravegaStreamProvider.java index e38a34c..582c398 100644 --- a/src/main/java/com/alvarium/streams/PravegaStreamProvider.java +++ b/src/main/java/com/alvarium/streams/PravegaStreamProvider.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import java.net.URI; @@ -31,7 +30,7 @@ import io.pravega.client.stream.impl.UTF8StringSerializer; /** - * A unit responsible for providing a pravega stream writer through the StreamProvider interface. + * A unit responsible for providing a pravega stream writer through the StreamProvider interface. */ class PravegaStreamProvider implements StreamProvider { private final PravegaConfig config; @@ -43,23 +42,25 @@ public PravegaStreamProvider(PravegaConfig config) { // build the depedencies required for the pravega stream configuration final PravegaRetention retention = config.getRetention(); final ScalingPolicy scalingPolicy = ScalingPolicy.fixed(config.getScalingPolicy()); - final RetentionPolicy retentionPolicy = RetentionPolicy.builder() - .retentionType(retention.getType()) - .retentionParam(retention.getMin()) - .retentionMax(retention.getMax()) - .build(); - this.streamConfig = StreamConfiguration.builder() - .scalingPolicy(scalingPolicy) - .retentionPolicy(retentionPolicy) - .build(); + final RetentionPolicy retentionPolicy = + RetentionPolicy.builder() + .retentionType(retention.getType()) + .retentionParam(retention.getMin()) + .retentionMax(retention.getMax()) + .build(); + this.streamConfig = + StreamConfiguration.builder() + .scalingPolicy(scalingPolicy) + .retentionPolicy(retentionPolicy) + .build(); } public void connect() throws StreamException { this.reconnect(); } - + private void reconnect() throws StreamException { - if(this.streamWriter != null){ + if (this.streamWriter != null) { return; } @@ -69,16 +70,21 @@ private void reconnect() throws StreamException { final URI controllerUri = URI.create(this.config.getProvider().uri()); // make sure that the selected scope & stream are created. - // this routine should check if the scope/stream exists before creating new ones. - final StreamManager streamManager = StreamManager.create(controllerUri); + // this routine should check if the scope/stream exists before creating new ones. + final StreamManager streamManager = StreamManager.create(controllerUri); streamManager.createScope(config.getScope()); streamManager.createStream(config.getScope(), config.getStream(), this.streamConfig); // Init the pravega stream writer using the specified scope/stream. - EventStreamClientFactory clientFactory = EventStreamClientFactory.withScope(config.getScope(), - ClientConfig.builder().controllerURI(controllerUri).build()); - this.streamWriter = clientFactory.createEventWriter(config.getStream(), - new UTF8StringSerializer(), EventWriterConfig.builder().build()); + EventStreamClientFactory clientFactory = + EventStreamClientFactory.withScope( + config.getScope(), + ClientConfig.builder().controllerURI(controllerUri).build()); + this.streamWriter = + clientFactory.createEventWriter( + config.getStream(), + new UTF8StringSerializer(), + EventWriterConfig.builder().build()); } catch (Exception e) { throw new StreamException("cannot connect to stream.", e); } @@ -92,13 +98,14 @@ public void publish(PublishWrapper wrapper) throws StreamException { this.reconnect(); try { - // writes the data to the stream, and waits on the completable future until it fully completes - this.streamWriter.writeEvent(this.config.getRoutingKey(),wrapper.toJson()).get(); + // writes the data to the stream, and waits on the completable future until it fully + // completes + this.streamWriter.writeEvent(this.config.getRoutingKey(), wrapper.toJson()).get(); } catch (CancellationException e) { throw new StreamException("publishing process was cancelled.", e); - } catch (ExecutionException e){ + } catch (ExecutionException e) { throw new StreamException("publishing process could not resolve.", e); - } catch (InterruptedException e){ + } catch (InterruptedException e) { throw new StreamException("publishing process was interrupted.", e); } } diff --git a/src/main/java/com/alvarium/streams/StreamException.java b/src/main/java/com/alvarium/streams/StreamException.java index a86d6b8..427b1eb 100644 --- a/src/main/java/com/alvarium/streams/StreamException.java +++ b/src/main/java/com/alvarium/streams/StreamException.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; /** diff --git a/src/main/java/com/alvarium/streams/StreamInfo.java b/src/main/java/com/alvarium/streams/StreamInfo.java index 111e6d9..fad7bd4 100644 --- a/src/main/java/com/alvarium/streams/StreamInfo.java +++ b/src/main/java/com/alvarium/streams/StreamInfo.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import java.io.Serializable; @@ -21,7 +20,7 @@ import com.google.gson.GsonBuilder; /** - * Contains the type of stream being used as well as the relevant configuration + * Contains the type of stream being used as well as the relevant configuration */ public class StreamInfo implements Serializable { private final StreamType type; @@ -30,7 +29,7 @@ public class StreamInfo implements Serializable { public StreamInfo(StreamType type, Object config) { this.type = type; this.config = config; - } + } public StreamType getType() { return this.type; @@ -44,11 +43,12 @@ public String toJson() { Gson gson = new Gson(); return gson.toJson(this); } - + public static StreamInfo fromJson(String json) { - Gson gson = new GsonBuilder().registerTypeAdapter(StreamInfo.class, new StreamInfoConverter()) - .create(); + Gson gson = + new GsonBuilder() + .registerTypeAdapter(StreamInfo.class, new StreamInfoConverter()) + .create(); return gson.fromJson(json, StreamInfo.class); - } } diff --git a/src/main/java/com/alvarium/streams/StreamProvider.java b/src/main/java/com/alvarium/streams/StreamProvider.java index 10a4b70..776fef8 100644 --- a/src/main/java/com/alvarium/streams/StreamProvider.java +++ b/src/main/java/com/alvarium/streams/StreamProvider.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import com.alvarium.PublishWrapper; @@ -37,5 +36,5 @@ public interface StreamProvider { * @param wrapper : data being published * @throws StreamException: thrown if the connection is closed or if the unit did not respond */ - public void publish(PublishWrapper wrapper) throws StreamException; + public void publish(PublishWrapper wrapper) throws StreamException; } diff --git a/src/main/java/com/alvarium/streams/StreamProviderFactory.java b/src/main/java/com/alvarium/streams/StreamProviderFactory.java index 481ac20..f36b813 100644 --- a/src/main/java/com/alvarium/streams/StreamProviderFactory.java +++ b/src/main/java/com/alvarium/streams/StreamProviderFactory.java @@ -1,20 +1,18 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; - /** * A factory that provides different implementations of the StreamProvider interface */ @@ -25,7 +23,7 @@ public StreamProvider getProvider(StreamInfo info) throws StreamException { try { MqttConfig config = MqttConfig.class.cast(info.getConfig()); return new MqttStreamProvider(config); - } catch(ClassCastException e) { + } catch (ClassCastException e) { throw new StreamException("Invalid stream config", e); } case PRAVEGA: @@ -39,6 +37,6 @@ public StreamProvider getProvider(StreamInfo info) throws StreamException { return new MockStreamProvider(); default: throw new StreamException(String.format("%s is not supported", info.getType())); - } + } } } diff --git a/src/main/java/com/alvarium/streams/StreamType.java b/src/main/java/com/alvarium/streams/StreamType.java index fb3eb97..26cc385 100644 --- a/src/main/java/com/alvarium/streams/StreamType.java +++ b/src/main/java/com/alvarium/streams/StreamType.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import com.google.gson.annotations.SerializedName; diff --git a/src/main/java/com/alvarium/utils/Encoder.java b/src/main/java/com/alvarium/utils/Encoder.java index d3e61c0..6d850aa 100644 --- a/src/main/java/com/alvarium/utils/Encoder.java +++ b/src/main/java/com/alvarium/utils/Encoder.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.utils; public class Encoder { @@ -33,7 +32,7 @@ public static String bytesToHex(byte[] data) { return hexString.toString(); } - + /** * Converts a hex string to a byte array * and will return the conversion of complete bytes (i.e. @@ -45,15 +44,17 @@ public static byte[] hexToBytes(String hex) { // Remove incomplete bytes if odd length int len = hex.length(); if (len % 2 != 0) { - hex = hex.substring(0, len-1); // Remove last element + hex = hex.substring(0, len - 1); // Remove last element } len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { - data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) - + Character.digit(hex.charAt(i+1), 16)); + data[i / 2] = + (byte) + ((Character.digit(hex.charAt(i), 16) << 4) + + Character.digit(hex.charAt(i + 1), 16)); } return data; -} + } } diff --git a/src/main/java/com/alvarium/utils/ImmutablePropertyBag.java b/src/main/java/com/alvarium/utils/ImmutablePropertyBag.java index 0bd0d25..38e896d 100644 --- a/src/main/java/com/alvarium/utils/ImmutablePropertyBag.java +++ b/src/main/java/com/alvarium/utils/ImmutablePropertyBag.java @@ -1,37 +1,36 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.utils; import java.util.HashMap; import java.util.Map; -public class ImmutablePropertyBag implements PropertyBag{ - private final HashMap bag; +public class ImmutablePropertyBag implements PropertyBag { + private final HashMap bag; - public ImmutablePropertyBag(Map map) { - this.bag = new HashMap(map); + public ImmutablePropertyBag(Map map) { + this.bag = new HashMap(map); } public T getProperty(String key, Class c) { - if(bag.containsKey(key)) { - return c.cast(bag.get(key)); + if (bag.containsKey(key)) { + return c.cast(bag.get(key)); } else { throw new IllegalArgumentException(String.format("Property %s not found", key)); } } - + public Map toMap() { return bag; } diff --git a/src/main/java/com/alvarium/utils/PropertyBag.java b/src/main/java/com/alvarium/utils/PropertyBag.java index 72628af..e33cf89 100644 --- a/src/main/java/com/alvarium/utils/PropertyBag.java +++ b/src/main/java/com/alvarium/utils/PropertyBag.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.utils; import java.util.Map; diff --git a/src/main/java/com/alvarium/utils/ServiceInfo.java b/src/main/java/com/alvarium/utils/ServiceInfo.java index 6e48e32..4342568 100644 --- a/src/main/java/com/alvarium/utils/ServiceInfo.java +++ b/src/main/java/com/alvarium/utils/ServiceInfo.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.utils; import java.io.Serializable; @@ -38,7 +37,7 @@ public ServiceInfo(String host, String protocol, int port) { */ public String uri() { return String.format("%s://%s:%d", protocol, host, port); - } + } public String toJson() { Gson gson = new Gson(); diff --git a/src/test/java/com/alvarium/PublishWrapperTest.java b/src/test/java/com/alvarium/PublishWrapperTest.java index 441bf89..7fcd976 100644 --- a/src/test/java/com/alvarium/PublishWrapperTest.java +++ b/src/test/java/com/alvarium/PublishWrapperTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium; import java.time.Instant; @@ -33,32 +32,29 @@ public class PublishWrapperTest { public void toJsonShouldReturnAppropriateRepresentation() { final SdkAction action = SdkAction.CREATE; final String messageType = "test type"; - final ArrayList content = new ArrayList(Arrays.asList(1,2,3,4)); + final ArrayList content = new ArrayList(Arrays.asList(1, 2, 3, 4)); - final PublishWrapper wrapper = new PublishWrapper(action,messageType, content); + final PublishWrapper wrapper = new PublishWrapper(action, messageType, content); System.out.println(wrapper.toJson()); - } + } @Test public void toJsonShouldParseAnnotationCorrectly() { final SdkAction action = SdkAction.CREATE; final String messageType = "test type"; - final Annotation annotation = new Annotation( - "key", - HashType.MD5Hash, - "host", - LayerType.Application, - AnnotationType.TPM, - "signature", - true, - Instant.now() - ); + final Annotation annotation = + new Annotation( + "key", + HashType.MD5Hash, + "host", + LayerType.Application, + AnnotationType.TPM, + "signature", + true, + Instant.now()); final List annotations = List.of(annotation, annotation); - final PublishWrapper wrapper = new PublishWrapper( - action, - messageType, - new AnnotationList(annotations) - ); + final PublishWrapper wrapper = + new PublishWrapper(action, messageType, new AnnotationList(annotations)); System.out.println(wrapper.toJson()); } } diff --git a/src/test/java/com/alvarium/SdkInfoTest.java b/src/test/java/com/alvarium/SdkInfoTest.java index 3b85392..a3450a6 100644 --- a/src/test/java/com/alvarium/SdkInfoTest.java +++ b/src/test/java/com/alvarium/SdkInfoTest.java @@ -1,20 +1,18 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium; - import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -38,7 +36,7 @@ public SdkInfoTest() throws IOException { } @Test - public void fromJsonShouldReturnSdkInfo(){ + public void fromJsonShouldReturnSdkInfo() { SdkInfo sdkInfo = SdkInfo.fromJson(this.testJson); assert sdkInfo.getAnnotators().length == 3; @@ -46,28 +44,28 @@ public void fromJsonShouldReturnSdkInfo(){ assert sdkInfo.getAnnotators()[0].getKind() == AnnotationType.TPM; assert sdkInfo.getAnnotators()[1].getKind() == AnnotationType.MOCK; - assert MockAnnotatorConfig.class.cast(sdkInfo.getAnnotators()[1]).getShouldSatisfy() == false; - + assert MockAnnotatorConfig.class.cast(sdkInfo.getAnnotators()[1]).getShouldSatisfy() + == false; assert sdkInfo.getAnnotators()[2].getKind() == AnnotationType.VULNERABILITY; - assert VulnerabilityAnnotatorConfig.class.cast(sdkInfo.getAnnotators()[2]) - .getProvider() - .uri() - .equals("https://example.com:80"); - - assert VulnerabilityAnnotatorConfig.class.cast(sdkInfo.getAnnotators()[2]) - .getQueryBatchPath() - .equals("https://example.com:80/v1/querybatch"); + assert VulnerabilityAnnotatorConfig.class + .cast(sdkInfo.getAnnotators()[2]) + .getProvider() + .uri() + .equals("https://example.com:80"); + + assert VulnerabilityAnnotatorConfig.class + .cast(sdkInfo.getAnnotators()[2]) + .getQueryBatchPath() + .equals("https://example.com:80/v1/querybatch"); + + assert VulnerabilityAnnotatorConfig.class + .cast(sdkInfo.getAnnotators()[2]) + .getQueryPath() + .equals("https://example.com:80/v1/query"); - assert VulnerabilityAnnotatorConfig.class.cast(sdkInfo.getAnnotators()[2]) - .getQueryPath() - .equals("https://example.com:80/v1/query"); - - - assert sdkInfo.getHash().getType() == HashType.SHA256Hash; assert sdkInfo.getSignature().getPrivateKey().getType() == SignType.Ed25519; assert sdkInfo.getStream().getConfig().getClass() == MqttConfig.class; - - } + } } diff --git a/src/test/java/com/alvarium/SdkTest.java b/src/test/java/com/alvarium/SdkTest.java index d6c84a7..82f8e0e 100644 --- a/src/test/java/com/alvarium/SdkTest.java +++ b/src/test/java/com/alvarium/SdkTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium; import java.io.IOException; @@ -20,12 +19,12 @@ import java.nio.file.Paths; import java.util.HashMap; -import com.alvarium.utils.PropertyBag; import com.alvarium.annotators.Annotator; import com.alvarium.annotators.AnnotatorException; import com.alvarium.annotators.AnnotatorFactory; import com.alvarium.streams.StreamException; import com.alvarium.utils.ImmutablePropertyBag; +import com.alvarium.utils.PropertyBag; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; @@ -35,29 +34,38 @@ class MockSdk implements Sdk { public void create(PropertyBag properties, byte[] data) {} + public void create(byte[] data) { final PropertyBag properties = new ImmutablePropertyBag(new HashMap()); this.create(properties, data); } + public void mutate(PropertyBag properties, byte[] oldData, byte[] newData) {} + public void mutate(byte[] oldData, byte[] newData) { final PropertyBag properties = new ImmutablePropertyBag(new HashMap()); this.mutate(properties, oldData, newData); } + public void transit(PropertyBag properties, byte[] data) {} + public void transit(byte[] data) { final PropertyBag properties = new ImmutablePropertyBag(new HashMap()); this.transit(properties, data); } + public void publish(PropertyBag properties, byte[] data) {} + public void publish(byte[] data) { final PropertyBag properties = new ImmutablePropertyBag(new HashMap()); this.publish(properties, data); } + public void close() { System.out.println("Connections closed"); - } + } } + public class SdkTest { private final String testJson; @@ -71,7 +79,7 @@ public void instantiateSdkShouldNotThrow() throws AnnotatorException, StreamExce final SdkInfo sdkInfo = SdkInfo.fromJson(this.testJson); // init annotators - final Annotator[] annotators = new Annotator[sdkInfo.getAnnotators().length]; + final Annotator[] annotators = new Annotator[sdkInfo.getAnnotators().length]; final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); // init logger @@ -79,7 +87,8 @@ public void instantiateSdkShouldNotThrow() throws AnnotatorException, StreamExce Configurator.setRootLevel(Level.DEBUG); for (int i = 0; i < annotators.length; i++) { - annotators[i] = annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); + annotators[i] = + annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); } final Sdk sdk = new DefaultSdk(annotators, sdkInfo, logger); @@ -109,7 +118,8 @@ public void defaultSdkShouldCreateAnnotations() throws AnnotatorException, Strea Configurator.setRootLevel(Level.DEBUG); for (int i = 0; i < annotators.length; i++) { - annotators[i] = annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); + annotators[i] = + annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); } final Sdk sdk = new DefaultSdk(annotators, sdkInfo, logger); @@ -121,20 +131,21 @@ public void defaultSdkShouldCreateAnnotations() throws AnnotatorException, Strea } @Test - public void defaultSdkShouldCreateTransitionAnnotations() throws AnnotatorException, - StreamException { + public void defaultSdkShouldCreateTransitionAnnotations() + throws AnnotatorException, StreamException { final SdkInfo sdkInfo = SdkInfo.fromJson(this.testJson); // init annotators final Annotator[] annotators = new Annotator[sdkInfo.getAnnotators().length]; final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); for (int i = 0; i < annotators.length; i++) { - annotators[i] = annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); + annotators[i] = + annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); } final Sdk sdk = new DefaultSdk(annotators, sdkInfo, logger); @@ -158,12 +169,12 @@ public void defaultSdkShouldMutateData() throws AnnotatorException, StreamExcept Configurator.setRootLevel(Level.DEBUG); for (int i = 0; i < annotators.length; i++) { - annotators[i] = annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); + annotators[i] = + annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); } final Sdk sdk = new DefaultSdk(annotators, sdkInfo, logger); - final byte[] oldData = "old data".getBytes(); final byte[] newData = "new data".getBytes(); @@ -172,8 +183,8 @@ public void defaultSdkShouldMutateData() throws AnnotatorException, StreamExcept } @Test - public void defaultSdkShouldCreatePublishedAnnotations() throws AnnotatorException, - StreamException { + public void defaultSdkShouldCreatePublishedAnnotations() + throws AnnotatorException, StreamException { final SdkInfo sdkInfo = SdkInfo.fromJson(this.testJson); // init annotators @@ -185,7 +196,8 @@ public void defaultSdkShouldCreatePublishedAnnotations() throws AnnotatorExcepti Configurator.setRootLevel(Level.DEBUG); for (int i = 0; i < annotators.length; i++) { - annotators[i] = annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); + annotators[i] = + annotatorFactory.getAnnotator(sdkInfo.getAnnotators()[i], sdkInfo, logger); } final Sdk sdk = new DefaultSdk(annotators, sdkInfo, logger); diff --git a/src/test/java/com/alvarium/annotators/AnnotatorTest.java b/src/test/java/com/alvarium/annotators/AnnotatorTest.java index 3a36430..a2405cd 100644 --- a/src/test/java/com/alvarium/annotators/AnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/AnnotatorTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.util.HashMap; @@ -43,22 +42,22 @@ public void mockAnnotatorShouldReturnSatisfiedAnnotation() throws AnnotatorExcep final KeyInfo keyInfo = new KeyInfo("path", SignType.none); final SignatureInfo signature = new SignatureInfo(keyInfo, keyInfo); final HashInfo hash = new HashInfo(HashType.NoHash); - - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); - + + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); + final String satisfiedMockConfig = "{\"kind\": \"mock\",\n\"shouldSatisfy\":true}"; final String unsatisfiedMockConfig = "{\"kind\": \"mock\",\n\"shouldSatisfy\":false}"; - - + final String badConfig1 = "{\"kind\": \"invalid\",\n\"shouldSatisfy\":true}"; final String badConfig2 = "{\"invalid\": \"mock\",\n\"shouldSatisfy\":true}"; - - final AnnotatorConfig satisfiedAnnotatorInfo = gson.fromJson(satisfiedMockConfig, AnnotatorConfig.class); - final AnnotatorConfig unsatisfiedAnnotatorInfo = gson.fromJson(unsatisfiedMockConfig, AnnotatorConfig.class); - + final AnnotatorConfig satisfiedAnnotatorInfo = + gson.fromJson(satisfiedMockConfig, AnnotatorConfig.class); + final AnnotatorConfig unsatisfiedAnnotatorInfo = + gson.fromJson(unsatisfiedMockConfig, AnnotatorConfig.class); try { gson.fromJson(badConfig1, AnnotatorConfig.class); @@ -73,16 +72,19 @@ public void mockAnnotatorShouldReturnSatisfiedAnnotation() throws AnnotatorExcep } catch (IllegalArgumentException e) { assert true; } - + final AnnotatorConfig[] annotators = {satisfiedAnnotatorInfo, unsatisfiedAnnotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, hash, signature, null, LayerType.Application); + final SdkInfo config = + new SdkInfo(annotators, hash, signature, null, LayerType.Application); final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); final AnnotatorFactory factory = new AnnotatorFactory(); - final Annotator satisfiedAnnotator = factory.getAnnotator(satisfiedAnnotatorInfo, config, logger); - final Annotator unsatisfiedAnnotator = factory.getAnnotator(unsatisfiedAnnotatorInfo, config, logger); + final Annotator satisfiedAnnotator = + factory.getAnnotator(satisfiedAnnotatorInfo, config, logger); + final Annotator unsatisfiedAnnotator = + factory.getAnnotator(unsatisfiedAnnotatorInfo, config, logger); final byte[] data = "test data".getBytes(); final PropertyBag ctx = new ImmutablePropertyBag(new HashMap<>()); @@ -92,7 +94,7 @@ public void mockAnnotatorShouldReturnSatisfiedAnnotation() throws AnnotatorExcep assert satisfiedAnnotation.getIsSatisfied(); assert !unsatisfiedAnnotation.getIsSatisfied(); - } + } @Test public void mockAnnotatorShouldReturnTag() throws AnnotatorException { @@ -100,16 +102,18 @@ public void mockAnnotatorShouldReturnTag() throws AnnotatorException { final SignatureInfo signature = new SignatureInfo(keyInfo, keyInfo); final HashInfo noHash = new HashInfo(HashType.NoHash); - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); final String mockConfig = "{\"kind\": \"mock\"}"; final AnnotatorConfig annotatorInfo = gson.fromJson(mockConfig, AnnotatorConfig.class); final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo noHashConfig = new SdkInfo(annotators, noHash, signature, null, LayerType.Application); + final SdkInfo noHashConfig = + new SdkInfo(annotators, noHash, signature, null, LayerType.Application); final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); @@ -131,16 +135,18 @@ public void mockAnnotatorShouldReturnLayer() throws AnnotatorException { final SignatureInfo signature = new SignatureInfo(keyInfo, keyInfo); final HashInfo noHash = new HashInfo(HashType.NoHash); - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); final String mockConfig = "{\"kind\": \"mock\"}"; final AnnotatorConfig annotatorInfo = gson.fromJson(mockConfig, AnnotatorConfig.class); final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo noHashConfig = new SdkInfo(annotators, noHash, signature, null, LayerType.Application); + final SdkInfo noHashConfig = + new SdkInfo(annotators, noHash, signature, null, LayerType.Application); final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); diff --git a/src/test/java/com/alvarium/annotators/ChecksumAnnotatorTest.java b/src/test/java/com/alvarium/annotators/ChecksumAnnotatorTest.java index 576ad8b..8036cba 100644 --- a/src/test/java/com/alvarium/annotators/ChecksumAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/ChecksumAnnotatorTest.java @@ -1,16 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.File; @@ -18,14 +18,6 @@ import java.nio.file.Files; import java.util.Map; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.config.Configurator; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - import com.alvarium.SdkInfo; import com.alvarium.contracts.Annotation; import com.alvarium.contracts.AnnotationType; @@ -44,76 +36,78 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; -public class ChecksumAnnotatorTest { - @Rule - public TemporaryFolder dir = new TemporaryFolder(); - - @Test - public void executeShouldReturnAnnotation() throws AnnotatorException, HashTypeException, IOException { - - AnnotatorFactory factory = new AnnotatorFactory(); - KeyInfo privateKey = new KeyInfo( - "./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - KeyInfo publicKey = new KeyInfo( - "./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - SignatureInfo sign = new SignatureInfo(publicKey, privateKey); - - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); - final String cfgJson = "{\"kind\": \"checksum\"}"; - final AnnotatorConfig checksumCfg = gson.fromJson( - cfgJson, - AnnotatorConfig.class - ); - - final AnnotatorConfig[] annotators = {checksumCfg}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.MD5Hash), sign, null, LayerType.Application); - - // init logger - final Logger logger = LogManager.getRootLogger(); - Configurator.setRootLevel(Level.DEBUG); - Annotator annotator = factory.getAnnotator(checksumCfg, config, logger); - - // Generate dummy artifact and generate checksum - - final File artifactFile = dir.newFile("artifact"); - Files.write(artifactFile.toPath(), "foo".getBytes()); - - final File checksumFile = dir.newFile("checksum"); - - final HashProvider hash = new HashProviderFactory().getProvider(config.getHash().getType()); - final String checksum = hash.derive( - Files.readAllBytes(artifactFile.toPath()) - ); - - Files.write(checksumFile.toPath(), checksum.getBytes()); - - System.out.println(checksum); - final ChecksumAnnotatorProps props = new ChecksumAnnotatorProps( - artifactFile.toPath().toString(), - checksumFile.toPath().toString() - ); - - PropertyBag ctx = new ImmutablePropertyBag( - Map.of(AnnotationType.CHECKSUM.name(), props) - ); - - byte[] data = "pipeline1/1".getBytes(); - Annotation annotation = annotator.execute(ctx, data); - System.out.println(annotation.toJson()); - assert annotation.getIsSatisfied(); - - // change artifact checksum - Files.write(checksumFile.toPath(), "bar".getBytes()); - - annotation = annotator.execute(ctx, data); - System.out.println(annotation.toJson()); - assert !annotation.getIsSatisfied(); - - - } +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.config.Configurator; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +public class ChecksumAnnotatorTest { + @Rule public TemporaryFolder dir = new TemporaryFolder(); + + @Test + public void executeShouldReturnAnnotation() + throws AnnotatorException, HashTypeException, IOException { + + AnnotatorFactory factory = new AnnotatorFactory(); + KeyInfo privateKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + KeyInfo publicKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + SignatureInfo sign = new SignatureInfo(publicKey, privateKey); + + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); + final String cfgJson = "{\"kind\": \"checksum\"}"; + final AnnotatorConfig checksumCfg = gson.fromJson(cfgJson, AnnotatorConfig.class); + + final AnnotatorConfig[] annotators = {checksumCfg}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.MD5Hash), + sign, + null, + LayerType.Application); + + // init logger + final Logger logger = LogManager.getRootLogger(); + Configurator.setRootLevel(Level.DEBUG); + Annotator annotator = factory.getAnnotator(checksumCfg, config, logger); + + // Generate dummy artifact and generate checksum + + final File artifactFile = dir.newFile("artifact"); + Files.write(artifactFile.toPath(), "foo".getBytes()); + + final File checksumFile = dir.newFile("checksum"); + + final HashProvider hash = new HashProviderFactory().getProvider(config.getHash().getType()); + final String checksum = hash.derive(Files.readAllBytes(artifactFile.toPath())); + + Files.write(checksumFile.toPath(), checksum.getBytes()); + + System.out.println(checksum); + final ChecksumAnnotatorProps props = + new ChecksumAnnotatorProps( + artifactFile.toPath().toString(), checksumFile.toPath().toString()); + + PropertyBag ctx = new ImmutablePropertyBag(Map.of(AnnotationType.CHECKSUM.name(), props)); + + byte[] data = "pipeline1/1".getBytes(); + Annotation annotation = annotator.execute(ctx, data); + System.out.println(annotation.toJson()); + assert annotation.getIsSatisfied(); + + // change artifact checksum + Files.write(checksumFile.toPath(), "bar".getBytes()); + + annotation = annotator.execute(ctx, data); + System.out.println(annotation.toJson()); + assert !annotation.getIsSatisfied(); + } } diff --git a/src/test/java/com/alvarium/annotators/PkiAnnotatorTest.java b/src/test/java/com/alvarium/annotators/PkiAnnotatorTest.java index 0fe642d..782a3d7 100644 --- a/src/test/java/com/alvarium/annotators/PkiAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/PkiAnnotatorTest.java @@ -1,19 +1,21 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import java.util.HashMap; import com.alvarium.SdkInfo; @@ -36,38 +38,40 @@ import org.apache.logging.log4j.core.config.Configurator; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class PkiAnnotatorTest { - - @Test public void executeShouldGetSatisfiedAnnotation() throws AnnotatorException { final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - // init logger + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); final PropertyBag ctx = new ImmutablePropertyBag(new HashMap()); - final String signature = "B9E41596541933DB7144CFBF72105E4E53F9493729CA66331A658B1B18AC6DF5DA991" - +"AD9720FD46A664918DFC745DE2F4F1F8C29FF71209B2DA79DFD1A34F50C"; - - final byte[] data = String.format("{seed: \"helloo\", signature: \"%s\"}", signature) - .getBytes(); + final String signature = + "B9E41596541933DB7144CFBF72105E4E53F9493729CA66331A658B1B18AC6DF5DA991" + + "AD9720FD46A664918DFC745DE2F4F1F8C29FF71209B2DA79DFD1A34F50C"; + final byte[] data = + String.format("{seed: \"helloo\", signature: \"%s\"}", signature).getBytes(); final AnnotatorConfig pkiCfg = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {pkiCfg}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig[] annotators = {pkiCfg}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); final Annotator annotator = annotatorFactory.getAnnotator(pkiCfg, config, logger); final Annotation annotation = annotator.execute(ctx, data); assertTrue("isSatisfied should be true", annotation.getIsSatisfied()); @@ -76,27 +80,35 @@ public void executeShouldGetSatisfiedAnnotation() throws AnnotatorException { @Test public void executeShouldGetUnsatisfiedAnnotation() throws AnnotatorException { final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - // init logger + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); final PropertyBag ctx = new ImmutablePropertyBag(new HashMap()); - final String signature = "A9E41596541933DB7144CFBF72105E4E53F9493729CA66331A658B1B18AC6DF5DA991" - +"AD9720FD46A664918DFC745DE2F4F1F8C29FF71209B2DA79DFD1A34F50C"; + final String signature = + "A9E41596541933DB7144CFBF72105E4E53F9493729CA66331A658B1B18AC6DF5DA991" + + "AD9720FD46A664918DFC745DE2F4F1F8C29FF71209B2DA79DFD1A34F50C"; - final byte[] data = String.format("{seed: \"helloo\", signature: \"%s\"}", signature) - .getBytes(); + final byte[] data = + String.format("{seed: \"helloo\", signature: \"%s\"}", signature).getBytes(); final AnnotatorConfig pkiCfg = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {pkiCfg}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig[] annotators = {pkiCfg}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); final Annotator annotator = annotatorFactory.getAnnotator(pkiCfg, config, logger); final Annotation annotation = annotator.execute(ctx, data); @@ -104,13 +116,11 @@ public void executeShouldGetUnsatisfiedAnnotation() throws AnnotatorException { } public AnnotatorConfig getAnnotatorCfg() { - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); final String json = "{\"kind\": \"pki\"}"; - return gson.fromJson( - json, - AnnotatorConfig.class - ); + return gson.fromJson(json, AnnotatorConfig.class); } } diff --git a/src/test/java/com/alvarium/annotators/PkiHttpAnnotatorTest.java b/src/test/java/com/alvarium/annotators/PkiHttpAnnotatorTest.java index 5c7eff6..1d8f9f6 100644 --- a/src/test/java/com/alvarium/annotators/PkiHttpAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/PkiHttpAnnotatorTest.java @@ -1,24 +1,25 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; -import java.util.HashMap; -import java.util.Date; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import java.io.UnsupportedEncodingException; import java.net.URI; +import java.util.Date; +import java.util.HashMap; import com.alvarium.SdkInfo; import com.alvarium.annotators.http.Ed2551RequestHandler; @@ -48,15 +49,12 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class PkiHttpAnnotatorTest { final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + final KeyInfo privKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); final byte[] data = String.format("{key: \"test\"}").getBytes(); @@ -66,22 +64,24 @@ HttpPost getRequest(SignatureInfo sigInfo) throws RequestHandlerException { request.setHeader("Date", date.toString()); request.setHeader("Content-Type", "application/json"); request.setHeader("Content-Length", "18"); - String[] fields = { DerivedComponent.METHOD.getValue(), - DerivedComponent.PATH.getValue(), - DerivedComponent.AUTHORITY.getValue(), - "Content-Type", "Content-Length" }; + String[] fields = { + DerivedComponent.METHOD.getValue(), + DerivedComponent.PATH.getValue(), + DerivedComponent.AUTHORITY.getValue(), + "Content-Type", + "Content-Length" + }; Ed2551RequestHandler requestHandler = new Ed2551RequestHandler(request); requestHandler.addSignatureHeaders(date, fields, sigInfo); return request; } - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); + @Rule public ExpectedException exceptionRule = ExpectedException.none(); @Test // Tests the Signature signed by the assembler public void testAnnotationOK() throws AnnotatorException, RequestHandlerException { - // init logger + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); HttpPost request = getRequest(sigInfo); @@ -96,8 +96,14 @@ public void testAnnotationOK() throws AnnotatorException, RequestHandlerExceptio final PropertyBag ctx = new ImmutablePropertyBag(map); final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); final Annotation annotation = annotator.execute(ctx, data); assertTrue("isSatisfied should be true", annotation.getIsSatisfied()); @@ -105,10 +111,11 @@ public void testAnnotationOK() throws AnnotatorException, RequestHandlerExceptio @Test public void testInvalidKeyType() throws AnnotatorException, RequestHandlerException { - final String signatureInput = "\"@method\" \"@path\" \"@authority\" \"Content-Type\" " + - "\"Content-Length\";created=1646146637;keyid=\"public.key\";alg=\"invalid\""; + final String signatureInput = + "\"@method\" \"@path\" \"@authority\" \"Content-Type\" " + + "\"Content-Length\";created=1646146637;keyid=\"public.key\";alg=\"invalid\""; - // init logger + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); HttpPost request = getRequest(sigInfo); @@ -116,7 +123,6 @@ public void testInvalidKeyType() throws AnnotatorException, RequestHandlerExcept request.setEntity(new StringEntity("{key: \"test\"}")); } catch (UnsupportedEncodingException e) { throw new AnnotatorException("Unsupported Character Encoding", e); - } request.setHeader("Signature-Input", signatureInput); @@ -128,17 +134,24 @@ public void testInvalidKeyType() throws AnnotatorException, RequestHandlerExcept exceptionRule.expectMessage("Invalid key type invalid"); final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); annotator.execute(ctx, data); } @Test public void testKeyNotFound() throws AnnotatorException, RequestHandlerException { - final String signatureInput = "\"@method\" \"@path\" \"@authority\" \"Content-Type\" " + - "\"Content-Length\";created=1646146637;keyid=\"invalid\";alg=\"ed25519\""; - // init logger + final String signatureInput = + "\"@method\" \"@path\" \"@authority\" \"Content-Type\" " + + "\"Content-Length\";created=1646146637;keyid=\"invalid\";alg=\"ed25519\""; + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); @@ -147,7 +160,6 @@ public void testKeyNotFound() throws AnnotatorException, RequestHandlerException request.setEntity(new StringEntity("{key: \"test\"}")); } catch (UnsupportedEncodingException e) { throw new AnnotatorException("Unsupported Character Encoding", e); - } request.setHeader("Signature-Input", signatureInput); @@ -155,10 +167,15 @@ public void testKeyNotFound() throws AnnotatorException, RequestHandlerException map.put(AnnotationType.PKIHttp.name(), request); final PropertyBag ctx = new ImmutablePropertyBag(map); - final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); Annotation annotation = annotator.execute(ctx, data); assertFalse("isSatisfied should be false", annotation.getIsSatisfied()); @@ -167,7 +184,7 @@ public void testKeyNotFound() throws AnnotatorException, RequestHandlerException @Test public void testEmptySignature() throws AnnotatorException, RequestHandlerException { final String signature = ""; - // init logger + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); @@ -176,17 +193,22 @@ public void testEmptySignature() throws AnnotatorException, RequestHandlerExcept request.setEntity(new StringEntity("{key: \"test\"}")); } catch (UnsupportedEncodingException e) { throw new AnnotatorException("Unsupported Character Encoding", e); - } request.setHeader("Signature", signature); HashMap map = new HashMap<>(); map.put(AnnotationType.PKIHttp.name(), request); final PropertyBag ctx = new ImmutablePropertyBag(map); - + final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); final Annotation annotation = annotator.execute(ctx, data); assertFalse("isSatisfied should be false", annotation.getIsSatisfied()); @@ -197,14 +219,13 @@ public void testInvalidSignature() throws AnnotatorException, RequestHandlerExce final String signature = "invalid"; HttpPost request = getRequest(sigInfo); - // init logger + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); try { request.setEntity(new StringEntity("{key: \"test\"}")); } catch (UnsupportedEncodingException e) { throw new AnnotatorException("Unsupported Character Encoding", e); - } request.setHeader("Signature", signature); @@ -213,21 +234,25 @@ public void testInvalidSignature() throws AnnotatorException, RequestHandlerExce final PropertyBag ctx = new ImmutablePropertyBag(map); final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); final Annotation annotation = annotator.execute(ctx, data); assertFalse("isSatisfied should be false", annotation.getIsSatisfied()); } public AnnotatorConfig getAnnotatorCfg() { - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); final String json = "{\"kind\": \"pki-http\"}"; - return gson.fromJson( - json, - AnnotatorConfig.class - ); + return gson.fromJson(json, AnnotatorConfig.class); } } diff --git a/src/test/java/com/alvarium/annotators/SbomAnnotatorTest.java b/src/test/java/com/alvarium/annotators/SbomAnnotatorTest.java index 8812615..91cf403 100644 --- a/src/test/java/com/alvarium/annotators/SbomAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/SbomAnnotatorTest.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.util.HashMap; @@ -48,11 +47,10 @@ public void executeShouldReturnSatisfiedAnnotation() throws Exception { final byte[] data = "test data".getBytes(); HashMap map = new HashMap(); map.put( - AnnotationType.SBOM.name(), - "./src/test/java/com/alvarium/annotators/sbom/spdx-valid.json" - ); + AnnotationType.SBOM.name(), + "./src/test/java/com/alvarium/annotators/sbom/spdx-valid.json"); final PropertyBag ctx = new ImmutablePropertyBag(map); - final Annotation annotation = annotator.execute(ctx, data); + final Annotation annotation = annotator.execute(ctx, data); assert annotation.getIsSatisfied(); } @@ -60,37 +58,41 @@ public void executeShouldReturnSatisfiedAnnotation() throws Exception { public void executeShouldReturnUnsatisfiedAnnotation() throws Exception { // provided spdx is version SPDX-2.3, config provides SPDX-2.2 so annotation should fail final String json = "{\"kind\":\"sbom\",\"type\":\"spdx\",\"version\":\"SPDX-2.3\"}"; - final Annotator annotator = this.getAnnotator(json); final byte[] data = "test data".getBytes(); + final Annotator annotator = this.getAnnotator(json); + final byte[] data = "test data".getBytes(); HashMap map = new HashMap(); map.put( - AnnotationType.SBOM.name(), - "./src/test/java/com/alvarium/annotators/sbom/spdx-valid.json" - ); + AnnotationType.SBOM.name(), + "./src/test/java/com/alvarium/annotators/sbom/spdx-valid.json"); final PropertyBag ctx = new ImmutablePropertyBag(map); - final Annotation annotation = annotator.execute(ctx, data); + final Annotation annotation = annotator.execute(ctx, data); assert !annotation.getIsSatisfied(); } private Annotator getAnnotator(String cfg) throws AnnotatorException { final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); - - - final AnnotatorConfig annotatorInfo = gson.fromJson( - cfg, - AnnotatorConfig.class - ); + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig annotatorInfo = gson.fromJson(cfg, AnnotatorConfig.class); + + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); // init logger final Logger logger = LogManager.getRootLogger(); @@ -99,5 +101,4 @@ private Annotator getAnnotator(String cfg) throws AnnotatorException { final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); return annotator; } - -} \ No newline at end of file +} diff --git a/src/test/java/com/alvarium/annotators/SourceAnnotatorTest.java b/src/test/java/com/alvarium/annotators/SourceAnnotatorTest.java index 20dbb88..10da85f 100644 --- a/src/test/java/com/alvarium/annotators/SourceAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/SourceAnnotatorTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.IOException; @@ -42,25 +41,30 @@ public class SourceAnnotatorTest { public void executeShouldReturnAnnotation() throws AnnotatorException, IOException { // construct annotator final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); final String json = "{\"kind\": \"src\"}"; - final AnnotatorConfig annotatorInfo = gson.fromJson( - json, - AnnotatorConfig.class - ); + final AnnotatorConfig annotatorInfo = gson.fromJson(json, AnnotatorConfig.class); System.out.println("hello " + annotatorInfo.getKind()); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); - // init logger + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); @@ -73,5 +77,4 @@ public void executeShouldReturnAnnotation() throws AnnotatorException, IOExcepti final Annotation annotation = annotator.execute(ctx, data); System.out.println(annotation.toJson()); } - } diff --git a/src/test/java/com/alvarium/annotators/SourceCodeAnnotatorTest.java b/src/test/java/com/alvarium/annotators/SourceCodeAnnotatorTest.java index 767be8b..4e1d8bf 100644 --- a/src/test/java/com/alvarium/annotators/SourceCodeAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/SourceCodeAnnotatorTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.File; @@ -19,16 +18,6 @@ import java.nio.file.Files; import java.util.Map; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.config.Configurator; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - - - import com.alvarium.SdkInfo; import com.alvarium.contracts.Annotation; import com.alvarium.contracts.AnnotationType; @@ -47,80 +36,91 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.config.Configurator; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + public class SourceCodeAnnotatorTest { - @Rule - public TemporaryFolder dir = new TemporaryFolder(); - - @Test - public void executeShouldReturnAnnotation() throws AnnotatorException, IOException, HashTypeException { - AnnotatorFactory factory = new AnnotatorFactory(); - KeyInfo privateKey = new KeyInfo( - "./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - KeyInfo publicKey = new KeyInfo( - "./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - - SignatureInfo sign = new SignatureInfo(publicKey, privateKey); - - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); - final String json = "{\"kind\": \"source-code\"}"; - final AnnotatorConfig annotatorInfo = gson.fromJson( - json, - AnnotatorConfig.class - ); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.MD5Hash), sign, null, LayerType.Application); - // init logger - final Logger logger = LogManager.getRootLogger(); - Configurator.setRootLevel(Level.DEBUG); - Annotator annotator = factory.getAnnotator(annotatorInfo, config, logger); - - final File sourceCodeDir = dir.newFolder("sourceCode"); - final File f1 = new File(sourceCodeDir, "file1"); - final File subDirectory = new File(sourceCodeDir, "sub"); - final File f2 = new File(subDirectory, "file2"); - subDirectory.mkdir(); - f1.createNewFile(); - f2.createNewFile(); - Files.write(f1.toPath(), "foo".getBytes()); - Files.write(f2.toPath(), "boo".getBytes()); - - final File checksumFile = dir.newFile("checksum"); - - final HashProvider hash = new HashProviderFactory().getProvider(config.getHash().getType()); - String hashAndPath = hash.derive(Files.readAllBytes(f1.toPath())) + " " + f1.toPath().toString() + "\n"; - hashAndPath = hashAndPath + hash.derive(Files.readAllBytes(f2.toPath())) + " " + f2.toPath().toString() + "\n"; - final String checksum = hash.derive(hashAndPath.getBytes()); - - Files.write(checksumFile.toPath(), checksum.getBytes()); - - final SourceCodeAnnotatorProps props = - new SourceCodeAnnotatorProps( - sourceCodeDir.toPath().toString(), - checksumFile.toPath().toString() - ); - - PropertyBag ctx = new ImmutablePropertyBag( - Map.of(AnnotationType.SourceCode.name(), props) - ); - - byte[] data = "pipeline1/1".getBytes(); - - Annotation annotation = annotator.execute(ctx, data); - System.out.println(annotation.toJson()); - assert annotation.getIsSatisfied(); - - // tamper with existing file in source code - Files.write(f1.toPath(), "tampered".getBytes()); - - annotation = annotator.execute(ctx, data); - System.out.println(annotation.toJson()); - - assert !annotation.getIsSatisfied(); - - } + @Rule public TemporaryFolder dir = new TemporaryFolder(); + + @Test + public void executeShouldReturnAnnotation() + throws AnnotatorException, IOException, HashTypeException { + AnnotatorFactory factory = new AnnotatorFactory(); + KeyInfo privateKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + KeyInfo publicKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + + SignatureInfo sign = new SignatureInfo(publicKey, privateKey); + + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); + final String json = "{\"kind\": \"source-code\"}"; + final AnnotatorConfig annotatorInfo = gson.fromJson(json, AnnotatorConfig.class); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.MD5Hash), + sign, + null, + LayerType.Application); + // init logger + final Logger logger = LogManager.getRootLogger(); + Configurator.setRootLevel(Level.DEBUG); + Annotator annotator = factory.getAnnotator(annotatorInfo, config, logger); + + final File sourceCodeDir = dir.newFolder("sourceCode"); + final File f1 = new File(sourceCodeDir, "file1"); + final File subDirectory = new File(sourceCodeDir, "sub"); + final File f2 = new File(subDirectory, "file2"); + subDirectory.mkdir(); + f1.createNewFile(); + f2.createNewFile(); + Files.write(f1.toPath(), "foo".getBytes()); + Files.write(f2.toPath(), "boo".getBytes()); + + final File checksumFile = dir.newFile("checksum"); + + final HashProvider hash = new HashProviderFactory().getProvider(config.getHash().getType()); + String hashAndPath = + hash.derive(Files.readAllBytes(f1.toPath())) + " " + f1.toPath().toString() + "\n"; + hashAndPath = + hashAndPath + + hash.derive(Files.readAllBytes(f2.toPath())) + + " " + + f2.toPath().toString() + + "\n"; + final String checksum = hash.derive(hashAndPath.getBytes()); + + Files.write(checksumFile.toPath(), checksum.getBytes()); + + final SourceCodeAnnotatorProps props = + new SourceCodeAnnotatorProps( + sourceCodeDir.toPath().toString(), checksumFile.toPath().toString()); + + PropertyBag ctx = new ImmutablePropertyBag(Map.of(AnnotationType.SourceCode.name(), props)); + + byte[] data = "pipeline1/1".getBytes(); + + Annotation annotation = annotator.execute(ctx, data); + System.out.println(annotation.toJson()); + assert annotation.getIsSatisfied(); + + // tamper with existing file in source code + Files.write(f1.toPath(), "tampered".getBytes()); + + annotation = annotator.execute(ctx, data); + System.out.println(annotation.toJson()); + + assert !annotation.getIsSatisfied(); + } } diff --git a/src/test/java/com/alvarium/annotators/TlsAnnotatorTest.java b/src/test/java/com/alvarium/annotators/TlsAnnotatorTest.java index 1a6cd3a..f451820 100644 --- a/src/test/java/com/alvarium/annotators/TlsAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/TlsAnnotatorTest.java @@ -1,23 +1,21 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.io.IOException; import java.net.UnknownHostException; import java.util.HashMap; - import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; @@ -44,31 +42,36 @@ public class TlsAnnotatorTest { @Test - public void executeShouldReturnAnnotation() throws AnnotatorException, IOException, - UnknownHostException { - // init logger + public void executeShouldReturnAnnotation() + throws AnnotatorException, IOException, UnknownHostException { + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); // construct annotator final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); + + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); final String json = "{\"kind\": \"tls\"}"; - final AnnotatorConfig annotatorInfo = gson.fromJson( - json, - AnnotatorConfig.class - ); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); - final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); - + final AnnotatorConfig annotatorInfo = gson.fromJson(json, AnnotatorConfig.class); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); + final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); + // dummy data final byte[] data = "test data".getBytes(); @@ -82,5 +85,5 @@ public void executeShouldReturnAnnotation() throws AnnotatorException, IOExcepti final Annotation annotation = annotator.execute(bag, data); System.out.println(annotation.toJson()); - } + } } diff --git a/src/test/java/com/alvarium/annotators/TpmAnnotatorTest.java b/src/test/java/com/alvarium/annotators/TpmAnnotatorTest.java index 7b99ca3..8d72d9a 100644 --- a/src/test/java/com/alvarium/annotators/TpmAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/TpmAnnotatorTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators; import java.util.HashMap; @@ -37,39 +36,40 @@ import org.junit.Test; public class TpmAnnotatorTest { - + @Test public void executeShouldCreateAnnotation() throws AnnotatorException { - // init logger + // init logger final Logger logger = LogManager.getRootLogger(); Configurator.setRootLevel(Level.DEBUG); AnnotatorFactory factory = new AnnotatorFactory(); - KeyInfo privateKey = new KeyInfo( - "./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - KeyInfo publicKey = new KeyInfo( - "./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); + KeyInfo privateKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + KeyInfo publicKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); SignatureInfo sign = new SignatureInfo(publicKey, privateKey); - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); - + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); + final String json = "{\"kind\": \"tpm\"}"; - final AnnotatorConfig annotatorInfo = gson.fromJson( - json, - AnnotatorConfig.class - ); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.MD5Hash), sign, null, LayerType.Application); + final AnnotatorConfig annotatorInfo = gson.fromJson(json, AnnotatorConfig.class); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.MD5Hash), + sign, + null, + LayerType.Application); Annotator tpm = factory.getAnnotator(annotatorInfo, config, logger); - + PropertyBag ctx = new ImmutablePropertyBag(new HashMap()); - + byte[] data = {0x1, 0x2}; Annotation annotation = tpm.execute(ctx, data); System.out.println(annotation.toJson()); } - } diff --git a/src/test/java/com/alvarium/annotators/VulnerabilityAnnotatorTest.java b/src/test/java/com/alvarium/annotators/VulnerabilityAnnotatorTest.java index cf216f5..40cbbc5 100644 --- a/src/test/java/com/alvarium/annotators/VulnerabilityAnnotatorTest.java +++ b/src/test/java/com/alvarium/annotators/VulnerabilityAnnotatorTest.java @@ -1,161 +1,175 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.HashMap; - -import com.alvarium.SdkInfo; -import com.alvarium.contracts.Annotation; -import com.alvarium.contracts.AnnotationType; -import com.alvarium.contracts.LayerType; -import com.alvarium.hash.HashInfo; -import com.alvarium.hash.HashType; -import com.alvarium.serializers.AnnotatorConfigConverter; -import com.alvarium.sign.KeyInfo; -import com.alvarium.sign.SignType; -import com.alvarium.sign.SignatureInfo; -import com.alvarium.utils.ImmutablePropertyBag; -import com.alvarium.utils.PropertyBag; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.config.Configurator; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; - -public class VulnerabilityAnnotatorTest { - - @Rule - public TemporaryFolder dir = new TemporaryFolder(); - - public void executeShouldReturnAnnotation() throws AnnotatorException, IOException { - // init logger - final Logger logger = LogManager.getRootLogger(); - Configurator.setRootLevel(Level.DEBUG); - // construct annotator - final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); - final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - - final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); - - final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); - - //Writing pom.xml file with a dependency that has a known vulnerability - //Therefore a non satisfied annotation should be returned - final File pomXmlFile = dir.newFile("pom.xml"); - try (FileWriter writer = new FileWriter(pomXmlFile)) { - writer.write("\n"); - writer.write(" 4.0.0\n"); - writer.write(" com.example\n"); - writer.write(" my-project\n"); - writer.write(" 1.0.0\n"); - writer.write("\n"); - writer.write(" \n"); - writer.write(" \n"); - writer.write(" junit\n"); - writer.write(" junit\n"); - writer.write(" 4.12\n"); - writer.write(" test\n"); - writer.write(" \n"); - writer.write(" \n"); - writer.write("\n"); - } - - // dummy data and empty prop bag - final byte[] data = "test data".getBytes(); - HashMap map = new HashMap(); - map.put(AnnotationType.VULNERABILITY.name(), pomXmlFile.toPath().getParent().toString()); - final PropertyBag ctx = new ImmutablePropertyBag(map); - - final Annotation annotation = annotator.execute(ctx, data); - - assert !annotation.getIsSatisfied(); - } - - public void executeShouldReturnSatisfiedAnnotation() throws AnnotatorException, IOException { - // init logger - final Logger logger = LogManager.getRootLogger(); - Configurator.setRootLevel(Level.DEBUG); - // construct annotator - final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); - final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); - final AnnotatorConfig[] annotators = {annotatorInfo}; - final SdkInfo config = new SdkInfo(annotators, new HashInfo(HashType.SHA256Hash), sigInfo, null, LayerType.Application); - - final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); - - //Writing pom.xml file with a non existing dependency so there will be no exisitng vurnerabilities - //Therefore a satisifed annotation should be returned - final File pomXmlFile = dir.newFile("pom.xml"); - try (FileWriter writer = new FileWriter(pomXmlFile)) { - writer.write("\n"); - writer.write(" 4.0.0\n"); - writer.write(" com.example\n"); - writer.write(" my-project\n"); - writer.write(" 1.0.0\n"); - writer.write("\n"); - writer.write(" \n"); - writer.write(" \n"); - writer.write(" testgroupId\n"); - writer.write(" testartifactId\n"); - writer.write(" 9.99\n"); - writer.write(" test\n"); - writer.write(" \n"); - writer.write(" \n"); - writer.write("\n"); - } - - // dummy data and empty prop bag - final byte[] data = "test data".getBytes(); - HashMap map = new HashMap(); - map.put(AnnotationType.VULNERABILITY.name(), pomXmlFile.toPath().getParent().toString()); - final PropertyBag ctx = new ImmutablePropertyBag(map); - - final Annotation annotation = annotator.execute(ctx, data); - - assert annotation.getIsSatisfied(); - } - - public AnnotatorConfig getAnnotatorCfg() { - final Gson gson = new GsonBuilder() - .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) - .create(); - - final String json = "{\"kind\": \"vulnerability\", \"type\": \"osv\"," - + "\"provider\":{\"host\":\"api.osv.dev\", \"protocol\": \"https\", \"port\": \"443\"}," - + "\"paths\": {\"queryBatch\": \"/v1/querybatch\", \"query\": \"/v1/query\"} }"; - - return gson.fromJson( - json, - AnnotatorConfig.class - ); - } -} +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.HashMap; + +import com.alvarium.SdkInfo; +import com.alvarium.contracts.Annotation; +import com.alvarium.contracts.AnnotationType; +import com.alvarium.contracts.LayerType; +import com.alvarium.hash.HashInfo; +import com.alvarium.hash.HashType; +import com.alvarium.serializers.AnnotatorConfigConverter; +import com.alvarium.sign.KeyInfo; +import com.alvarium.sign.SignType; +import com.alvarium.sign.SignatureInfo; +import com.alvarium.utils.ImmutablePropertyBag; +import com.alvarium.utils.PropertyBag; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.config.Configurator; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; + +public class VulnerabilityAnnotatorTest { + + @Rule public TemporaryFolder dir = new TemporaryFolder(); + + public void executeShouldReturnAnnotation() throws AnnotatorException, IOException { + // init logger + final Logger logger = LogManager.getRootLogger(); + Configurator.setRootLevel(Level.DEBUG); + // construct annotator + final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); + final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); + + final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); + + final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); + + // Writing pom.xml file with a dependency that has a known vulnerability + // Therefore a non satisfied annotation should be returned + final File pomXmlFile = dir.newFile("pom.xml"); + try (FileWriter writer = new FileWriter(pomXmlFile)) { + writer.write("\n"); + writer.write(" 4.0.0\n"); + writer.write(" com.example\n"); + writer.write(" my-project\n"); + writer.write(" 1.0.0\n"); + writer.write("\n"); + writer.write(" \n"); + writer.write(" \n"); + writer.write(" junit\n"); + writer.write(" junit\n"); + writer.write(" 4.12\n"); + writer.write(" test\n"); + writer.write(" \n"); + writer.write(" \n"); + writer.write("\n"); + } + + // dummy data and empty prop bag + final byte[] data = "test data".getBytes(); + HashMap map = new HashMap(); + map.put(AnnotationType.VULNERABILITY.name(), pomXmlFile.toPath().getParent().toString()); + final PropertyBag ctx = new ImmutablePropertyBag(map); + + final Annotation annotation = annotator.execute(ctx, data); + + assert !annotation.getIsSatisfied(); + } + + public void executeShouldReturnSatisfiedAnnotation() throws AnnotatorException, IOException { + // init logger + final Logger logger = LogManager.getRootLogger(); + Configurator.setRootLevel(Level.DEBUG); + // construct annotator + final AnnotatorFactory annotatorFactory = new AnnotatorFactory(); + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); + final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); + final AnnotatorConfig annotatorInfo = this.getAnnotatorCfg(); + final AnnotatorConfig[] annotators = {annotatorInfo}; + final SdkInfo config = + new SdkInfo( + annotators, + new HashInfo(HashType.SHA256Hash), + sigInfo, + null, + LayerType.Application); + + final Annotator annotator = annotatorFactory.getAnnotator(annotatorInfo, config, logger); + + // Writing pom.xml file with a non existing dependency so there will be no exisitng + // vurnerabilities + // Therefore a satisifed annotation should be returned + final File pomXmlFile = dir.newFile("pom.xml"); + try (FileWriter writer = new FileWriter(pomXmlFile)) { + writer.write("\n"); + writer.write(" 4.0.0\n"); + writer.write(" com.example\n"); + writer.write(" my-project\n"); + writer.write(" 1.0.0\n"); + writer.write("\n"); + writer.write(" \n"); + writer.write(" \n"); + writer.write(" testgroupId\n"); + writer.write(" testartifactId\n"); + writer.write(" 9.99\n"); + writer.write(" test\n"); + writer.write(" \n"); + writer.write(" \n"); + writer.write("\n"); + } + + // dummy data and empty prop bag + final byte[] data = "test data".getBytes(); + HashMap map = new HashMap(); + map.put(AnnotationType.VULNERABILITY.name(), pomXmlFile.toPath().getParent().toString()); + final PropertyBag ctx = new ImmutablePropertyBag(map); + + final Annotation annotation = annotator.execute(ctx, data); + + assert annotation.getIsSatisfied(); + } + + public AnnotatorConfig getAnnotatorCfg() { + final Gson gson = + new GsonBuilder() + .registerTypeAdapter(AnnotatorConfig.class, new AnnotatorConfigConverter()) + .create(); + + final String json = + "{\"kind\": \"vulnerability\", \"type\":" + + " \"osv\",\"provider\":{\"host\":\"api.osv.dev\", \"protocol\": \"https\"," + + " \"port\": \"443\"},\"paths\": {\"queryBatch\": \"/v1/querybatch\"," + + " \"query\": \"/v1/query\"} }"; + + return gson.fromJson(json, AnnotatorConfig.class); + } +} diff --git a/src/test/java/com/alvarium/annotators/http/Ed2551RequestHandlerTest.java b/src/test/java/com/alvarium/annotators/http/Ed2551RequestHandlerTest.java index dab790e..92c92f0 100644 --- a/src/test/java/com/alvarium/annotators/http/Ed2551RequestHandlerTest.java +++ b/src/test/java/com/alvarium/annotators/http/Ed2551RequestHandlerTest.java @@ -1,95 +1,100 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; -import java.util.Date; +import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URI; import java.nio.file.Paths; +import java.util.Date; import com.alvarium.contracts.DerivedComponent; - import com.alvarium.sign.KeyInfo; import com.alvarium.sign.SignType; import com.alvarium.sign.SignatureInfo; -import org.apache.http.entity.StringEntity; - import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; import org.junit.Test; -import static org.junit.Assert.assertEquals; - public class Ed2551RequestHandlerTest { - HttpPost getRequest() { - HttpPost request = new HttpPost(URI.create("http://example.com/foo?var1=&var2=2")); - request.setHeader("Date", "Tue, 20 Apr 2021 02:07:55 GMT"); - request.setHeader("Content-Type", "application/json"); - request.setHeader("Content-Length", "10"); - return request; - } - - @Test - public void addSignatureHeadersShouldExecuteCorrectly() throws IOException, RequestHandlerException { - - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); - - final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - - Date date = new Date(); - HttpPost request = getRequest(); - request.setEntity(new StringEntity("{key: \"test\"}")); - - String[] fields = { DerivedComponent.METHOD.getValue(), - DerivedComponent.PATH.getValue(), - DerivedComponent.AUTHORITY.getValue(), - "Content-Type", "Content-Length" }; - - Ed2551RequestHandler requestHandler = new Ed2551RequestHandler(request); - requestHandler.addSignatureHeaders(date, fields, sigInfo); - assertEquals(requestHandler.request.getHeaders("Signature-Input")[0].getValue(), - String.format( - "\"@method\" \"@path\" \"@authority\" \"Content-Type\" \"Content-Length\";created=%s;keyid=\"%s\";alg=\"%s\";", - Long.toString((date.getTime() / 1000)), - Paths.get(sigInfo.getPublicKey().getPath()).getFileName(), - sigInfo.getPublicKey().getType().getValue())); - - } - - @Test(expected = RequestHandlerException.class) - public void addSignatureHeadersShouldThrowException() throws IOException, RequestHandlerException { - - final KeyInfo pubKey = new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", - SignType.Ed25519); - - final KeyInfo privKey = new KeyInfo("./src/test/java/com/alvarium/annotators/private.key", - SignType.Ed25519); - - final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); - - Date date = new Date(); - HttpPost request = getRequest(); - request.setEntity(new StringEntity("{key: \"test\"}")); - - String[] fields = {}; - - Ed2551RequestHandler requestHandler = new Ed2551RequestHandler(request); - requestHandler.addSignatureHeaders(date, fields, sigInfo); - } + HttpPost getRequest() { + HttpPost request = new HttpPost(URI.create("http://example.com/foo?var1=&var2=2")); + request.setHeader("Date", "Tue, 20 Apr 2021 02:07:55 GMT"); + request.setHeader("Content-Type", "application/json"); + request.setHeader("Content-Length", "10"); + return request; + } + + @Test + public void addSignatureHeadersShouldExecuteCorrectly() + throws IOException, RequestHandlerException { + + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); + + final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); + + Date date = new Date(); + HttpPost request = getRequest(); + request.setEntity(new StringEntity("{key: \"test\"}")); + + String[] fields = { + DerivedComponent.METHOD.getValue(), + DerivedComponent.PATH.getValue(), + DerivedComponent.AUTHORITY.getValue(), + "Content-Type", + "Content-Length" + }; + + Ed2551RequestHandler requestHandler = new Ed2551RequestHandler(request); + requestHandler.addSignatureHeaders(date, fields, sigInfo); + assertEquals( + requestHandler.request.getHeaders("Signature-Input")[0].getValue(), + String.format( + "\"@method\" \"@path\" \"@authority\" \"Content-Type\"" + + " \"Content-Length\";created=%s;keyid=\"%s\";alg=\"%s\";", + Long.toString((date.getTime() / 1000)), + Paths.get(sigInfo.getPublicKey().getPath()).getFileName(), + sigInfo.getPublicKey().getType().getValue())); + } + + @Test(expected = RequestHandlerException.class) + public void addSignatureHeadersShouldThrowException() + throws IOException, RequestHandlerException { + + final KeyInfo pubKey = + new KeyInfo("./src/test/java/com/alvarium/annotators/public.key", SignType.Ed25519); + + final KeyInfo privKey = + new KeyInfo( + "./src/test/java/com/alvarium/annotators/private.key", SignType.Ed25519); + + final SignatureInfo sigInfo = new SignatureInfo(pubKey, privKey); + + Date date = new Date(); + HttpPost request = getRequest(); + request.setEntity(new StringEntity("{key: \"test\"}")); + + String[] fields = {}; + + Ed2551RequestHandler requestHandler = new Ed2551RequestHandler(request); + requestHandler.addSignatureHeaders(date, fields, sigInfo); + } } diff --git a/src/test/java/com/alvarium/annotators/http/ParseResultTest.java b/src/test/java/com/alvarium/annotators/http/ParseResultTest.java index f63f192..f260064 100644 --- a/src/test/java/com/alvarium/annotators/http/ParseResultTest.java +++ b/src/test/java/com/alvarium/annotators/http/ParseResultTest.java @@ -1,29 +1,28 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; -import org.apache.http.client.methods.HttpPost; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - import static org.junit.Assert.assertEquals; import java.net.URI; import java.net.URISyntaxException; +import org.apache.http.client.methods.HttpPost; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + public class ParseResultTest { HttpPost getRequest() { @@ -36,15 +35,28 @@ HttpPost getRequest() { return request; } - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); + @Rule public ExpectedException exceptionRule = ExpectedException.none(); @Test public void testIntegrationAllFields() throws URISyntaxException, ParseResultException { HttpPost request = getRequest(); - request.setHeader("Signature-Input", - "\"date\" \"@method\" \"@path\" \"@authority\" \"content-type\" \"content-length\" \"@query-params\" \"@query\" \"@target-uri\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); - String expectedSeed = "\"date\" Tue, 20 Apr 2021 02:07:55 GMT\n\"@method\" POST\n\"@path\" /foo\n\"@authority\" example.com\n\"content-type\" application/json\n\"content-length\" 18\n\"@query-params\";name=\"var1\": \n\"@query-params\";name=\"var2\": 2\n\"@query\" ?var1=&var2=2\n\"@target-uri\" http://example.com/foo?var1=&var2=2\n;created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"; + request.setHeader( + "Signature-Input", + "\"date\" \"@method\" \"@path\" \"@authority\" \"content-type\" \"content-length\"" + + " \"@query-params\" \"@query\"" + + " \"@target-uri\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); + String expectedSeed = + "\"date\" Tue, 20 Apr 2021 02:07:55 GMT\n" + + "\"@method\" POST\n" + + "\"@path\" /foo\n" + + "\"@authority\" example.com\n" + + "\"content-type\" application/json\n" + + "\"content-length\" 18\n" + + "\"@query-params\";name=\"var1\": \n" + + "\"@query-params\";name=\"var2\": 2\n" + + "\"@query\" ?var1=&var2=2\n" + + "\"@target-uri\" http://example.com/foo?var1=&var2=2\n" + + ";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"; ParseResult parsed = new ParseResult(request); assertEquals(expectedSeed, parsed.getSeed()); } @@ -53,8 +65,12 @@ public void testIntegrationAllFields() throws URISyntaxException, ParseResultExc public void testExtraSpaces() throws URISyntaxException, ParseResultException { HttpPost request = getRequest(); request.setHeader("Date", " Tue, 20 Apr 2021 02:07:55 GMT "); - request.setHeader("Signature-Input", "\"date\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); - String expectedSeed = "\"date\" Tue, 20 Apr 2021 02:07:55 GMT\n;created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"; + request.setHeader( + "Signature-Input", + "\"date\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); + String expectedSeed = + "\"date\" Tue, 20 Apr 2021 02:07:55 GMT\n" + + ";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"; ParseResult parsed = new ParseResult(request); assertEquals(expectedSeed, parsed.getSeed()); } @@ -117,13 +133,15 @@ public void testQueryField() throws URISyntaxException, ParseResultException { public void testQueryParamsField() throws URISyntaxException, ParseResultException { HttpPost request = getRequest(); request.setHeader("Signature-Input", "\"@query-params\";"); - String expectedSeed = "\"@query-params\";name=\"var1\": \n\"@query-params\";name=\"var2\": 2\n;"; + String expectedSeed = + "\"@query-params\";name=\"var1\": \n\"@query-params\";name=\"var2\": 2\n;"; ParseResult parsed = new ParseResult(request); assertEquals(expectedSeed, parsed.getSeed()); } @Test - public void testNonExistantSpecialityComponent() throws URISyntaxException, ParseResultException { + public void testNonExistantSpecialityComponent() + throws URISyntaxException, ParseResultException { HttpPost request = getRequest(); request.setHeader("Signature-Input", "\"@x-test\";"); exceptionRule.expect(ParseResultException.class); @@ -143,7 +161,9 @@ public void testNonExistantHeaderField() throws URISyntaxException, ParseResultE @Test public void testSignature() throws URISyntaxException, ParseResultException { HttpPost request = getRequest(); - request.setHeader("Signature-Input", "\"@query\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); + request.setHeader( + "Signature-Input", + "\"@query\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); ParseResult parsed = new ParseResult(request); assertEquals("whatever", parsed.getSignature()); } @@ -151,7 +171,9 @@ public void testSignature() throws URISyntaxException, ParseResultException { @Test public void testKeyid() throws URISyntaxException, ParseResultException { HttpPost request = getRequest(); - request.setHeader("Signature-Input", "\"@query\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); + request.setHeader( + "Signature-Input", + "\"@query\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); ParseResult parsed = new ParseResult(request); assertEquals("public.key", parsed.getKeyid()); } @@ -159,7 +181,9 @@ public void testKeyid() throws URISyntaxException, ParseResultException { @Test public void testAlgorithm() throws URISyntaxException, ParseResultException { HttpPost request = getRequest(); - request.setHeader("Signature-Input", "\"@query\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); + request.setHeader( + "Signature-Input", + "\"@query\";created=1644758607;keyid=\"public.key\";alg=\"ed25519\";"); ParseResult parsed = new ParseResult(request); assertEquals("ed25519", parsed.getAlgorithm()); } diff --git a/src/test/java/com/alvarium/annotators/http/RequestHandlerTest.java b/src/test/java/com/alvarium/annotators/http/RequestHandlerTest.java index f204dd1..3577218 100644 --- a/src/test/java/com/alvarium/annotators/http/RequestHandlerTest.java +++ b/src/test/java/com/alvarium/annotators/http/RequestHandlerTest.java @@ -1,27 +1,26 @@ /******************************************************************************* - * Copyright 2022 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.http; -import org.junit.Test; +import static org.junit.Assert.assertEquals; + import java.net.URI; import com.alvarium.sign.SignType; import org.apache.http.client.methods.HttpPost; - -import static org.junit.Assert.assertEquals; +import org.junit.Test; public class RequestHandlerTest { diff --git a/src/test/java/com/alvarium/annotators/sbom/SbomProviderFactoryTest.java b/src/test/java/com/alvarium/annotators/sbom/SbomProviderFactoryTest.java index bdb3753..26dc4a8 100644 --- a/src/test/java/com/alvarium/annotators/sbom/SbomProviderFactoryTest.java +++ b/src/test/java/com/alvarium/annotators/sbom/SbomProviderFactoryTest.java @@ -1,23 +1,22 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.sbom; import org.junit.Test; public class SbomProviderFactoryTest { - + @Test public void factoryShouldInstantiateSpdxProvider() throws Exception { SbomAnnotatorConfig cfg = new SbomAnnotatorConfig(SbomType.SPDX, "SPDX-2.2"); diff --git a/src/test/java/com/alvarium/annotators/sbom/SpdxSbomProviderTest.java b/src/test/java/com/alvarium/annotators/sbom/SpdxSbomProviderTest.java index 1ee33b8..8868416 100644 --- a/src/test/java/com/alvarium/annotators/sbom/SpdxSbomProviderTest.java +++ b/src/test/java/com/alvarium/annotators/sbom/SpdxSbomProviderTest.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2024 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.sbom; import org.junit.Test; @@ -20,16 +19,17 @@ public class SpdxSbomProviderTest { // Valid spdx file with version 2.2 final String validSpdxPath = "./src/test/java/com/alvarium/annotators/sbom/spdx-valid.json"; - + // Path points to invalid spdx file final String invalidSpdxPath = "./src/test/java/com/alvarium/annotators/sbom/spdx-invalid.json"; // File path points to does not exist - final String nonExistantSpdxPath = "./src/test/java/com/alvarium/annotators/sbom/spdx-does-not-exist.json"; + final String nonExistantSpdxPath = + "./src/test/java/com/alvarium/annotators/sbom/spdx-does-not-exist.json"; // Path to an spdx file with a different sbom than `validSpdxPath` - final String differentSpdxFilePath = "./src/test/java/com/alvarium/annotators/sbom/spdx-different.json"; - + final String differentSpdxFilePath = + "./src/test/java/com/alvarium/annotators/sbom/spdx-different.json"; @Test public void existsShouldCheckSpdxOnFileSystem() throws Exception { @@ -38,7 +38,6 @@ public void existsShouldCheckSpdxOnFileSystem() throws Exception { assert spdx.exists(validSpdxPath); assert !spdx.exists(nonExistantSpdxPath); - } @Test @@ -60,16 +59,16 @@ public void validateShouldThrowOnBadSpdx() throws Exception { assert spdx.validate(validSpdxPath); try { spdx.validate(invalidSpdxPath); - } catch(Exception e) { + } catch (Exception e) { assert e instanceof SbomException; } } /* - * This tests an existing SPDX sbom file against the current project. any changes to the - * packages in the pom.xml file will result in this test failing and would require a new - * SPDX file be generated and replace spdx-valid.json - */ + * This tests an existing SPDX sbom file against the current project. any changes to the + * packages in the pom.xml file will result in this test failing and would require a new + * SPDX file be generated and replace spdx-valid.json + */ @Test public void matchesBuildShouldFailOnDifferentComposition() throws Exception { SbomAnnotatorConfig cfg = new SbomAnnotatorConfig(SbomType.SPDX, "SPDX-2.2"); @@ -77,5 +76,4 @@ public void matchesBuildShouldFailOnDifferentComposition() throws Exception { assert spdx.matchesBuild(validSpdxPath, "."); assert !spdx.matchesBuild(differentSpdxFilePath, "."); } - } diff --git a/src/test/java/com/alvarium/annotators/vulnerability/GoModHandlerTest.java b/src/test/java/com/alvarium/annotators/vulnerability/GoModHandlerTest.java index 2846927..0888e64 100644 --- a/src/test/java/com/alvarium/annotators/vulnerability/GoModHandlerTest.java +++ b/src/test/java/com/alvarium/annotators/vulnerability/GoModHandlerTest.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; import java.io.File; @@ -22,217 +21,220 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; - public class GoModHandlerTest { - @Rule - public TemporaryFolder dir = new TemporaryFolder(); - - @Test - public void testGetPackagesWtihRequireBlock() throws Exception { - File project = dir.newFolder("project"); - File gomodFile = new File(project.toPath() + "/go.mod"); - - String artifactId1 = "pkg1/v1"; - String version1 = "v1.0"; - String artifactId2 = "pkg2/v2"; - String version2 = "v2.0"; - - StringBuilder goModContent = new StringBuilder(); - goModContent.append("module github.com/edgexfoundry/edgex-go\n"); - goModContent.append("\n"); - goModContent.append("go 1.20\n"); - goModContent.append("\n"); - goModContent.append("require (\n"); - goModContent.append(artifactId1 + " " + version1 +"\n"); - goModContent.append(artifactId2 + " " + version2 +"\n"); - goModContent.append(")"); - - Files.writeString(gomodFile.toPath(), goModContent.toString()); - - GoModHandler handler = new GoModHandler(project.getAbsolutePath()); - - assert handler.getFileName().equals(gomodFile.getName()); - - Map packages = handler.getPackages(); - - assert packages.keySet().size() == 2; - assert packages.get(artifactId1).equals(version1); - assert packages.get(artifactId2).equals(version2); - } - - @Test - public void testGetPackagesWithoutRequireBlock() throws Exception { - File project = dir.newFolder("project"); - File gomodFile = new File(project.toPath() + "/go.mod"); - - String artifactId1 = "pkg1/v1"; - String version1 = "v1.0"; - String artifactId2 = "pkg2/v2"; - String version2 = "v2.0"; - - StringBuilder goModContent = new StringBuilder(); - goModContent.append("module github.com/edgexfoundry/edgex-go\n"); - goModContent.append("\n"); - goModContent.append("go 1.20\n"); - goModContent.append("\n"); - goModContent.append("require " + artifactId1 + " " + version1 +"\n"); - goModContent.append("require " + artifactId2 + " " + version2 +"\n"); - - Files.writeString(gomodFile.toPath(), goModContent.toString()); - - GoModHandler handler = new GoModHandler(project.getAbsolutePath()); - - assert handler.getFileName().equals(gomodFile.getName()); - - Map packages = handler.getPackages(); - - assert packages.keySet().size() == 2; - assert packages.get(artifactId1).equals(version1); - assert packages.get(artifactId2).equals(version2); - } - - @Test - public void testGetPackagesWithMixedRequireLines() throws Exception { - File project = dir.newFolder("project"); - File gomodFile = new File(project.toPath() + "/go.mod"); - - String artifactId1 = "pkg1/v1"; - String version1 = "v1.0"; - String artifactId2 = "pkg2/v2"; - String version2 = "v2.0"; - String artifactId3 = "pkg3/v3"; - String version3 = "v3.0"; - String artifactId4 = "pkg4/v4"; - String version4 = "v4.0"; - - - - StringBuilder goModContent = new StringBuilder(); - goModContent.append("module github.com/edgexfoundry/edgex-go\n"); - goModContent.append("\n"); - goModContent.append("go 1.20\n"); - goModContent.append("\n"); - - goModContent.append("require " + artifactId1 + " " + version1 +"\n"); - goModContent.append("exclude example.com/old/thing v1.2.3\n"); - goModContent.append("require (\n"); - goModContent.append(artifactId2 + " " + version2 +"\n"); - goModContent.append(artifactId3 + " " + version3 +"\n"); - goModContent.append(")\n"); - goModContent.append("require " + artifactId4 + " " + version4 +"\n"); - goModContent.append("retract [v1.9.0, v1.9.5]\n"); - - Files.writeString(gomodFile.toPath(), goModContent.toString()); - - GoModHandler handler = new GoModHandler(project.getAbsolutePath()); - - assert handler.getFileName().equals(gomodFile.getName()); - - Map packages = handler.getPackages(); - - assert packages.keySet().size() == 4; - assert packages.get(artifactId1).equals(version1); - assert packages.get(artifactId2).equals(version2); - assert packages.get(artifactId3).equals(version3); - assert packages.get(artifactId4).equals(version4); - - } - - @Test - public void testGetPackagesWithoutReplaceBlock() throws Exception { - File project = dir.newFolder("project"); - File gomodFile = new File(project.toPath() + "/go.mod"); - - String artifactId1 = "pkg1/v1"; - String version1 = "v1.0"; - String artifactId2 = "pkg2/v2"; - String version2 = "v2.0"; - String artifactId3 = "pkg3/v3"; - String version3 = "v3.0"; - String artifactId4 = "pkg4/v4"; - String version4 = "v4.0"; - String artifactId5 = "pkg5/v5"; - String version5 = "v5.0"; - - - StringBuilder goModContent = new StringBuilder(); - goModContent.append("module github.com/edgexfoundry/edgex-go\n"); - goModContent.append("\n"); - goModContent.append("go 1.20\n"); - goModContent.append("\n"); - - goModContent.append("require " + artifactId1 + " " + version1 +"\n"); - goModContent.append("exclude example.com/old/thing v1.2.3\n"); - goModContent.append("require (\n"); - goModContent.append(artifactId2 + " " + version2 +"\n"); - goModContent.append(artifactId3 + " " + version3 +"\n"); - goModContent.append(")\n"); - goModContent.append("replace " + artifactId3 + " " + version3 + " => " + artifactId5 + " " + version5 +"\n"); - goModContent.append("require " + artifactId4 + " " + version4 +"\n"); - goModContent.append("retract [v1.9.0, v1.9.5]\n"); - - Files.writeString(gomodFile.toPath(), goModContent.toString()); - - GoModHandler handler = new GoModHandler(project.getAbsolutePath()); - - assert handler.getFileName().equals(gomodFile.getName()); - - Map packages = handler.getPackages(); - - assert packages.keySet().size() == 4; - assert packages.get(artifactId1).equals(version1); - assert packages.get(artifactId2).equals(version2); - assert packages.get(artifactId4).equals(version4); - assert packages.get(artifactId5).equals(version5); - } - - @Test - public void testGetPackagesWithReplaceBlock() throws Exception { - File project = dir.newFolder("project"); - File gomodFile = new File(project.toPath() + "/go.mod"); - - String artifactId1 = "pkg1/v1"; - String version1 = "v1.0"; - String artifactId2 = "pkg2/v2"; - String version2 = "v2.0"; - String artifactId3 = "pkg3/v3"; - String version3 = "v3.0"; - String artifactId4 = "pkg4/v4"; - String version4 = "v4.0"; - String artifactId5 = "pkg5/v5"; - String version5 = "v5.0"; - - - StringBuilder goModContent = new StringBuilder(); - goModContent.append("module github.com/edgexfoundry/edgex-go\n"); - goModContent.append("\n"); - goModContent.append("go 1.20\n"); - goModContent.append("\n"); - - goModContent.append("require " + artifactId1 + " " + version1 +"\n"); - goModContent.append("exclude example.com/old/thing v1.2.3\n"); - goModContent.append("require (\n"); - goModContent.append(artifactId2 + " " + version2 +"\n"); - goModContent.append(artifactId3 + " " + version3 +"\n"); - goModContent.append(")\n"); - goModContent.append("replace (\n"); - goModContent.append(artifactId2 + " " + version2 + " => " + artifactId4 + " " + version4 +"\n"); - goModContent.append(artifactId3 + " " + version3 + " => " + artifactId5 + " " + version5 +"\n"); - goModContent.append(")\n"); - goModContent.append("retract [v1.9.0, v1.9.5]\n"); - - Files.writeString(gomodFile.toPath(), goModContent.toString()); - - GoModHandler handler = new GoModHandler(project.getAbsolutePath()); - - assert handler.getFileName().equals(gomodFile.getName()); - - Map packages = handler.getPackages(); - - assert packages.keySet().size() == 3; - assert packages.get(artifactId1).equals(version1); - assert packages.get(artifactId4).equals(version4); - assert packages.get(artifactId5).equals(version5); - } - + @Rule public TemporaryFolder dir = new TemporaryFolder(); + + @Test + public void testGetPackagesWtihRequireBlock() throws Exception { + File project = dir.newFolder("project"); + File gomodFile = new File(project.toPath() + "/go.mod"); + + String artifactId1 = "pkg1/v1"; + String version1 = "v1.0"; + String artifactId2 = "pkg2/v2"; + String version2 = "v2.0"; + + StringBuilder goModContent = new StringBuilder(); + goModContent.append("module github.com/edgexfoundry/edgex-go\n"); + goModContent.append("\n"); + goModContent.append("go 1.20\n"); + goModContent.append("\n"); + goModContent.append("require (\n"); + goModContent.append(artifactId1 + " " + version1 + "\n"); + goModContent.append(artifactId2 + " " + version2 + "\n"); + goModContent.append(")"); + + Files.writeString(gomodFile.toPath(), goModContent.toString()); + + GoModHandler handler = new GoModHandler(project.getAbsolutePath()); + + assert handler.getFileName().equals(gomodFile.getName()); + + Map packages = handler.getPackages(); + + assert packages.keySet().size() == 2; + assert packages.get(artifactId1).equals(version1); + assert packages.get(artifactId2).equals(version2); + } + + @Test + public void testGetPackagesWithoutRequireBlock() throws Exception { + File project = dir.newFolder("project"); + File gomodFile = new File(project.toPath() + "/go.mod"); + + String artifactId1 = "pkg1/v1"; + String version1 = "v1.0"; + String artifactId2 = "pkg2/v2"; + String version2 = "v2.0"; + + StringBuilder goModContent = new StringBuilder(); + goModContent.append("module github.com/edgexfoundry/edgex-go\n"); + goModContent.append("\n"); + goModContent.append("go 1.20\n"); + goModContent.append("\n"); + goModContent.append("require " + artifactId1 + " " + version1 + "\n"); + goModContent.append("require " + artifactId2 + " " + version2 + "\n"); + + Files.writeString(gomodFile.toPath(), goModContent.toString()); + + GoModHandler handler = new GoModHandler(project.getAbsolutePath()); + + assert handler.getFileName().equals(gomodFile.getName()); + + Map packages = handler.getPackages(); + + assert packages.keySet().size() == 2; + assert packages.get(artifactId1).equals(version1); + assert packages.get(artifactId2).equals(version2); + } + + @Test + public void testGetPackagesWithMixedRequireLines() throws Exception { + File project = dir.newFolder("project"); + File gomodFile = new File(project.toPath() + "/go.mod"); + + String artifactId1 = "pkg1/v1"; + String version1 = "v1.0"; + String artifactId2 = "pkg2/v2"; + String version2 = "v2.0"; + String artifactId3 = "pkg3/v3"; + String version3 = "v3.0"; + String artifactId4 = "pkg4/v4"; + String version4 = "v4.0"; + + StringBuilder goModContent = new StringBuilder(); + goModContent.append("module github.com/edgexfoundry/edgex-go\n"); + goModContent.append("\n"); + goModContent.append("go 1.20\n"); + goModContent.append("\n"); + + goModContent.append("require " + artifactId1 + " " + version1 + "\n"); + goModContent.append("exclude example.com/old/thing v1.2.3\n"); + goModContent.append("require (\n"); + goModContent.append(artifactId2 + " " + version2 + "\n"); + goModContent.append(artifactId3 + " " + version3 + "\n"); + goModContent.append(")\n"); + goModContent.append("require " + artifactId4 + " " + version4 + "\n"); + goModContent.append("retract [v1.9.0, v1.9.5]\n"); + + Files.writeString(gomodFile.toPath(), goModContent.toString()); + + GoModHandler handler = new GoModHandler(project.getAbsolutePath()); + + assert handler.getFileName().equals(gomodFile.getName()); + + Map packages = handler.getPackages(); + + assert packages.keySet().size() == 4; + assert packages.get(artifactId1).equals(version1); + assert packages.get(artifactId2).equals(version2); + assert packages.get(artifactId3).equals(version3); + assert packages.get(artifactId4).equals(version4); + } + + @Test + public void testGetPackagesWithoutReplaceBlock() throws Exception { + File project = dir.newFolder("project"); + File gomodFile = new File(project.toPath() + "/go.mod"); + + String artifactId1 = "pkg1/v1"; + String version1 = "v1.0"; + String artifactId2 = "pkg2/v2"; + String version2 = "v2.0"; + String artifactId3 = "pkg3/v3"; + String version3 = "v3.0"; + String artifactId4 = "pkg4/v4"; + String version4 = "v4.0"; + String artifactId5 = "pkg5/v5"; + String version5 = "v5.0"; + + StringBuilder goModContent = new StringBuilder(); + goModContent.append("module github.com/edgexfoundry/edgex-go\n"); + goModContent.append("\n"); + goModContent.append("go 1.20\n"); + goModContent.append("\n"); + + goModContent.append("require " + artifactId1 + " " + version1 + "\n"); + goModContent.append("exclude example.com/old/thing v1.2.3\n"); + goModContent.append("require (\n"); + goModContent.append(artifactId2 + " " + version2 + "\n"); + goModContent.append(artifactId3 + " " + version3 + "\n"); + goModContent.append(")\n"); + goModContent.append( + "replace " + + artifactId3 + + " " + + version3 + + " => " + + artifactId5 + + " " + + version5 + + "\n"); + goModContent.append("require " + artifactId4 + " " + version4 + "\n"); + goModContent.append("retract [v1.9.0, v1.9.5]\n"); + + Files.writeString(gomodFile.toPath(), goModContent.toString()); + + GoModHandler handler = new GoModHandler(project.getAbsolutePath()); + + assert handler.getFileName().equals(gomodFile.getName()); + + Map packages = handler.getPackages(); + + assert packages.keySet().size() == 4; + assert packages.get(artifactId1).equals(version1); + assert packages.get(artifactId2).equals(version2); + assert packages.get(artifactId4).equals(version4); + assert packages.get(artifactId5).equals(version5); + } + + @Test + public void testGetPackagesWithReplaceBlock() throws Exception { + File project = dir.newFolder("project"); + File gomodFile = new File(project.toPath() + "/go.mod"); + + String artifactId1 = "pkg1/v1"; + String version1 = "v1.0"; + String artifactId2 = "pkg2/v2"; + String version2 = "v2.0"; + String artifactId3 = "pkg3/v3"; + String version3 = "v3.0"; + String artifactId4 = "pkg4/v4"; + String version4 = "v4.0"; + String artifactId5 = "pkg5/v5"; + String version5 = "v5.0"; + + StringBuilder goModContent = new StringBuilder(); + goModContent.append("module github.com/edgexfoundry/edgex-go\n"); + goModContent.append("\n"); + goModContent.append("go 1.20\n"); + goModContent.append("\n"); + + goModContent.append("require " + artifactId1 + " " + version1 + "\n"); + goModContent.append("exclude example.com/old/thing v1.2.3\n"); + goModContent.append("require (\n"); + goModContent.append(artifactId2 + " " + version2 + "\n"); + goModContent.append(artifactId3 + " " + version3 + "\n"); + goModContent.append(")\n"); + goModContent.append("replace (\n"); + goModContent.append( + artifactId2 + " " + version2 + " => " + artifactId4 + " " + version4 + "\n"); + goModContent.append( + artifactId3 + " " + version3 + " => " + artifactId5 + " " + version5 + "\n"); + goModContent.append(")\n"); + goModContent.append("retract [v1.9.0, v1.9.5]\n"); + + Files.writeString(gomodFile.toPath(), goModContent.toString()); + + GoModHandler handler = new GoModHandler(project.getAbsolutePath()); + + assert handler.getFileName().equals(gomodFile.getName()); + + Map packages = handler.getPackages(); + + assert packages.keySet().size() == 3; + assert packages.get(artifactId1).equals(version1); + assert packages.get(artifactId4).equals(version4); + assert packages.get(artifactId5).equals(version5); + } } diff --git a/src/test/java/com/alvarium/annotators/vulnerability/MavenHandlerTest.java b/src/test/java/com/alvarium/annotators/vulnerability/MavenHandlerTest.java index 747fa64..1069172 100644 --- a/src/test/java/com/alvarium/annotators/vulnerability/MavenHandlerTest.java +++ b/src/test/java/com/alvarium/annotators/vulnerability/MavenHandlerTest.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; import java.io.File; @@ -22,56 +21,52 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; - public class MavenHandlerTest { - @Rule - public TemporaryFolder dir = new TemporaryFolder(); - - @Test - public void shouldReturnAllPomDependencies() throws Exception { - File project = dir.newFolder("project"); - File pom = new File(project.toPath() + "/pom.xml"); - - StringBuilder pomContent = new StringBuilder(); - pomContent.append(""); - pomContent.append(" "); - pomContent.append(" 11"); - pomContent.append(" "); - pomContent.append(" "); - - String groupId1 = "org.alvarium.sdk"; - String artifactId1 = "java-sdk"; - String version1 = "1.2.3"; - pomContent.append(" "); - pomContent.append(" " + groupId1 + ""); - pomContent.append(" " + artifactId1 + ""); - pomContent.append(" " + version1 + ""); - pomContent.append(" "); - - String groupId2 = "org.foo.bar"; - String artifactId2 = "example"; - String version2 = "1.0.3a"; - pomContent.append(" "); - pomContent.append(" " + groupId2 + ""); - pomContent.append(" " + artifactId2 + ""); - pomContent.append(" " + version2 + ""); - pomContent.append(" "); - - pomContent.append(" "); - pomContent.append(""); - - Files.writeString(pom.toPath(), pomContent.toString()); - MavenHandler handler = new MavenHandler(project.getAbsolutePath()); - - assert handler.getFileName().equals(pom.getName()); - - Map packages = handler.getPackages(); - - assert packages.get(groupId1 + ":" + artifactId1).equals(version1); - assert packages.get(groupId2 + ":" + artifactId2).equals(version2); - - assert packages.keySet().size() == 2; - - } - + @Rule public TemporaryFolder dir = new TemporaryFolder(); + + @Test + public void shouldReturnAllPomDependencies() throws Exception { + File project = dir.newFolder("project"); + File pom = new File(project.toPath() + "/pom.xml"); + + StringBuilder pomContent = new StringBuilder(); + pomContent.append(""); + pomContent.append(" "); + pomContent.append(" 11"); + pomContent.append(" "); + pomContent.append(" "); + + String groupId1 = "org.alvarium.sdk"; + String artifactId1 = "java-sdk"; + String version1 = "1.2.3"; + pomContent.append(" "); + pomContent.append(" " + groupId1 + ""); + pomContent.append(" " + artifactId1 + ""); + pomContent.append(" " + version1 + ""); + pomContent.append(" "); + + String groupId2 = "org.foo.bar"; + String artifactId2 = "example"; + String version2 = "1.0.3a"; + pomContent.append(" "); + pomContent.append(" " + groupId2 + ""); + pomContent.append(" " + artifactId2 + ""); + pomContent.append(" " + version2 + ""); + pomContent.append(" "); + + pomContent.append(" "); + pomContent.append(""); + + Files.writeString(pom.toPath(), pomContent.toString()); + MavenHandler handler = new MavenHandler(project.getAbsolutePath()); + + assert handler.getFileName().equals(pom.getName()); + + Map packages = handler.getPackages(); + + assert packages.get(groupId1 + ":" + artifactId1).equals(version1); + assert packages.get(groupId2 + ":" + artifactId2).equals(version2); + + assert packages.keySet().size() == 2; + } } diff --git a/src/test/java/com/alvarium/annotators/vulnerability/OsvApiHandlerTest.java b/src/test/java/com/alvarium/annotators/vulnerability/OsvApiHandlerTest.java index de915af..bdf44e5 100644 --- a/src/test/java/com/alvarium/annotators/vulnerability/OsvApiHandlerTest.java +++ b/src/test/java/com/alvarium/annotators/vulnerability/OsvApiHandlerTest.java @@ -1,45 +1,43 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -import com.alvarium.utils.ServiceInfo; - -public class OsvApiHandlerTest { - // @Test - public void testGetVulnerabilityIds() throws VulnerabilityException { - final ServiceInfo osvApi = new ServiceInfo("api.osv.dev", "https", 443); - - OsvApiHandler batchResponse = new OsvApiHandler( - new VulnerabilityAnnotatorConfig( - osvApi, - VulnerabilityProviderType.OSV, - new VulnerabilityAnnotatorConfig.EndpointPaths("/v1/querybatch", "/v1/query") - ) - ); - - Map packages = new HashMap(); - packages.put("org.eclipse.jetty:jetty-server","7.0.0.M0"); - - List vulnerabilities = batchResponse.getVulnerabilityIds(packages); - System.out.println(vulnerabilities); - assert vulnerabilities != null; - assert vulnerabilities.size() > 0; - } - -} +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alvarium.utils.ServiceInfo; + +public class OsvApiHandlerTest { + // @Test + public void testGetVulnerabilityIds() throws VulnerabilityException { + final ServiceInfo osvApi = new ServiceInfo("api.osv.dev", "https", 443); + + OsvApiHandler batchResponse = + new OsvApiHandler( + new VulnerabilityAnnotatorConfig( + osvApi, + VulnerabilityProviderType.OSV, + new VulnerabilityAnnotatorConfig.EndpointPaths( + "/v1/querybatch", "/v1/query"))); + + Map packages = new HashMap(); + packages.put("org.eclipse.jetty:jetty-server", "7.0.0.M0"); + + List vulnerabilities = batchResponse.getVulnerabilityIds(packages); + System.out.println(vulnerabilities); + assert vulnerabilities != null; + assert vulnerabilities.size() > 0; + } +} diff --git a/src/test/java/com/alvarium/annotators/vulnerability/OsvBatchRequestTest.java b/src/test/java/com/alvarium/annotators/vulnerability/OsvBatchRequestTest.java index 0c4e96b..9684948 100644 --- a/src/test/java/com/alvarium/annotators/vulnerability/OsvBatchRequestTest.java +++ b/src/test/java/com/alvarium/annotators/vulnerability/OsvBatchRequestTest.java @@ -1,46 +1,47 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -import org.junit.Test; - -import com.google.gson.Gson; - -import static org.junit.Assert.*; -import java.util.HashMap; -import java.util.Map; - -public class OsvBatchRequestTest { - @Test - public void testOsvBatchRequest() { - Map packages = new HashMap(); - packages.put("com.google.guava", "30.1.1-jre"); - packages.put("com.fasterxml.jackson.core", "2.12.3"); - - OsvBatchRequest batchRequest = new OsvBatchRequest(packages); - System.out.println(new Gson().toJson(batchRequest)); - assertNotNull(batchRequest.queries); - assertEquals(batchRequest.queries.size(), 2); - - OsvBatchRequest.Query query1 = batchRequest.queries.get(0); - assertEquals(query1.version, "30.1.1-jre"); - assertEquals(query1.packageInfo.name, "com.google.guava"); - assertEquals(query1.packageInfo.ecosystem, "Maven"); - - OsvBatchRequest.Query query2 = batchRequest.queries.get(1); - assertEquals(query2.version, "2.12.3"); - assertEquals(query2.packageInfo.name, "com.fasterxml.jackson.core"); - assertEquals(query2.packageInfo.ecosystem, "Maven"); - } -} \ No newline at end of file +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; + +import org.junit.Test; + +public class OsvBatchRequestTest { + @Test + public void testOsvBatchRequest() { + Map packages = new HashMap(); + packages.put("com.google.guava", "30.1.1-jre"); + packages.put("com.fasterxml.jackson.core", "2.12.3"); + + OsvBatchRequest batchRequest = new OsvBatchRequest(packages); + System.out.println(new Gson().toJson(batchRequest)); + assertNotNull(batchRequest.queries); + assertEquals(batchRequest.queries.size(), 2); + + OsvBatchRequest.Query query1 = batchRequest.queries.get(0); + assertEquals(query1.version, "30.1.1-jre"); + assertEquals(query1.packageInfo.name, "com.google.guava"); + assertEquals(query1.packageInfo.ecosystem, "Maven"); + + OsvBatchRequest.Query query2 = batchRequest.queries.get(1); + assertEquals(query2.version, "2.12.3"); + assertEquals(query2.packageInfo.name, "com.fasterxml.jackson.core"); + assertEquals(query2.packageInfo.ecosystem, "Maven"); + } +} diff --git a/src/test/java/com/alvarium/annotators/vulnerability/OsvBatchResponseTest.java b/src/test/java/com/alvarium/annotators/vulnerability/OsvBatchResponseTest.java index e917922..a7882e4 100644 --- a/src/test/java/com/alvarium/annotators/vulnerability/OsvBatchResponseTest.java +++ b/src/test/java/com/alvarium/annotators/vulnerability/OsvBatchResponseTest.java @@ -1,34 +1,36 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -import java.util.List; - -import org.junit.Test; - -import com.google.gson.Gson; - -public class OsvBatchResponseTest { - private final Gson gson = new Gson(); - @Test - public void testGetVulnerabilityIds() { - String responseBody = "{\"results\":[{\"vulns\":[{\"id\":\"CVE-2021-1234\",\"modified\":\"2021-01-01T00:00:00Z\"},{\"id\":\"CVE-2021-5678\",\"modified\":\"2021-01-02T00:00:00Z\"}]}]}"; - OsvBatchResponse response = gson.fromJson(responseBody, OsvBatchResponse.class); - List vulnerabilityIds = response.getVulnerabilityIds(); - - assert vulnerabilityIds.size() == 2; - assert vulnerabilityIds.contains("CVE-2021-1234"); - assert vulnerabilityIds.contains("CVE-2021-5678"); - } -} +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +import java.util.List; + +import com.google.gson.Gson; + +import org.junit.Test; + +public class OsvBatchResponseTest { + private final Gson gson = new Gson(); + + @Test + public void testGetVulnerabilityIds() { + String responseBody = + "{\"results\":[{\"vulns\":[{\"id\":\"CVE-2021-1234\",\"modified\":\"2021-01-01T00:00:00Z\"},{\"id\":\"CVE-2021-5678\",\"modified\":\"2021-01-02T00:00:00Z\"}]}]}"; + OsvBatchResponse response = gson.fromJson(responseBody, OsvBatchResponse.class); + List vulnerabilityIds = response.getVulnerabilityIds(); + + assert vulnerabilityIds.size() == 2; + assert vulnerabilityIds.contains("CVE-2021-1234"); + assert vulnerabilityIds.contains("CVE-2021-5678"); + } +} diff --git a/src/test/java/com/alvarium/annotators/vulnerability/PackageFileHandlerFactoryTest.java b/src/test/java/com/alvarium/annotators/vulnerability/PackageFileHandlerFactoryTest.java index 8308ac4..f2c062b 100644 --- a/src/test/java/com/alvarium/annotators/vulnerability/PackageFileHandlerFactoryTest.java +++ b/src/test/java/com/alvarium/annotators/vulnerability/PackageFileHandlerFactoryTest.java @@ -1,17 +1,16 @@ /******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ - +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.annotators.vulnerability; import java.io.File; @@ -21,22 +20,21 @@ import org.junit.rules.TemporaryFolder; public class PackageFileHandlerFactoryTest { - @Rule - public TemporaryFolder dir = new TemporaryFolder(); + @Rule public TemporaryFolder dir = new TemporaryFolder(); - @Test - public void shouldReturnMavenHandler() throws Exception { - File pom = dir.newFile("pom.xml"); - PackageFileHandlerFactory factory = new PackageFileHandlerFactory(); - PackageFileHandler handler = factory.getHandler(pom.toPath().getParent().toString()); - assert handler instanceof MavenHandler; - } + @Test + public void shouldReturnMavenHandler() throws Exception { + File pom = dir.newFile("pom.xml"); + PackageFileHandlerFactory factory = new PackageFileHandlerFactory(); + PackageFileHandler handler = factory.getHandler(pom.toPath().getParent().toString()); + assert handler instanceof MavenHandler; + } - @Test - public void shouldReturnGoModHandler() throws Exception { - File gomod = dir.newFile("go.mod"); - PackageFileHandlerFactory factory = new PackageFileHandlerFactory(); - PackageFileHandler handler = factory.getHandler(gomod.toPath().getParent().toString()); - assert handler instanceof GoModHandler; - } + @Test + public void shouldReturnGoModHandler() throws Exception { + File gomod = dir.newFile("go.mod"); + PackageFileHandlerFactory factory = new PackageFileHandlerFactory(); + PackageFileHandler handler = factory.getHandler(gomod.toPath().getParent().toString()); + assert handler instanceof GoModHandler; + } } diff --git a/src/test/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandlerFactoryTest.java b/src/test/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandlerFactoryTest.java index 9fc1036..f23e777 100644 --- a/src/test/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandlerFactoryTest.java +++ b/src/test/java/com/alvarium/annotators/vulnerability/VulnerabilityApiHandlerFactoryTest.java @@ -1,35 +1,35 @@ -/******************************************************************************* - * Copyright 2023 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ -package com.alvarium.annotators.vulnerability; - -import org.junit.Test; - -import com.alvarium.utils.ServiceInfo; - -public class VulnerabilityApiHandlerFactoryTest { - - @Test - public void shouldReturnOsvApiHandler() throws Exception { - VulnerabilityProviderType apiProvider = VulnerabilityProviderType.OSV; - VulnerabilityApiHandlerFactory factory = new VulnerabilityApiHandlerFactory(); - VulnerabilityApiHandler apiHandler = factory.getHandler( - new VulnerabilityAnnotatorConfig( - new ServiceInfo("example.com", "hhttps", 80), - apiProvider, - new VulnerabilityAnnotatorConfig.EndpointPaths("/v1/querybatch", "/v1/query") - ) - ); - assert apiHandler instanceof OsvApiHandler; - } -} +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ +package com.alvarium.annotators.vulnerability; + +import com.alvarium.utils.ServiceInfo; + +import org.junit.Test; + +public class VulnerabilityApiHandlerFactoryTest { + + @Test + public void shouldReturnOsvApiHandler() throws Exception { + VulnerabilityProviderType apiProvider = VulnerabilityProviderType.OSV; + VulnerabilityApiHandlerFactory factory = new VulnerabilityApiHandlerFactory(); + VulnerabilityApiHandler apiHandler = + factory.getHandler( + new VulnerabilityAnnotatorConfig( + new ServiceInfo("example.com", "hhttps", 80), + apiProvider, + new VulnerabilityAnnotatorConfig.EndpointPaths( + "/v1/querybatch", "/v1/query"))); + assert apiHandler instanceof OsvApiHandler; + } +} diff --git a/src/test/java/com/alvarium/contracts/AnnotationListTest.java b/src/test/java/com/alvarium/contracts/AnnotationListTest.java index 2a11159..90c2b1a 100644 --- a/src/test/java/com/alvarium/contracts/AnnotationListTest.java +++ b/src/test/java/com/alvarium/contracts/AnnotationListTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.contracts; import static org.junit.Assert.assertEquals; @@ -26,19 +25,19 @@ import org.junit.Test; public class AnnotationListTest { - + @Test public void toJsonShouldParseCorrectly() { - final Annotation annotation = new Annotation( - "key", - HashType.NoHash, - "host", - LayerType.Application, - AnnotationType.MOCK, - "signature", - true, - Instant.now() - ); + final Annotation annotation = + new Annotation( + "key", + HashType.NoHash, + "host", + LayerType.Application, + AnnotationType.MOCK, + "signature", + true, + Instant.now()); final AnnotationList annotations = new AnnotationList(List.of(annotation, annotation)); System.out.println(annotations.toJson()); } @@ -46,25 +45,26 @@ public void toJsonShouldParseCorrectly() { @Test public void fromJsonShouldPraseCorrectly() throws IOException { - final String annotation = "{\"id\":\"01FHX2DH740WQB4WQS6A6X21QP\","+ - "\"key\":\"key\"," + - "\"hash\":\"md5\"," + - "\"host\":\"host\"," + - "\"kind\":\"tpm\"," + - "\"tag\":\"9c0f17daa5cfefb0302d6f8650899b0863120e4c\"," + - "\"layer\":\"app\"," + - "\"signature\":\"signature\"," + - "\"isSatisfied\":true," + - "\"timestamp\":\"2021-10-13T07:55:33.585017-07:00\"}"; + final String annotation = + "{\"id\":\"01FHX2DH740WQB4WQS6A6X21QP\"," + + "\"key\":\"key\"," + + "\"hash\":\"md5\"," + + "\"host\":\"host\"," + + "\"kind\":\"tpm\"," + + "\"tag\":\"9c0f17daa5cfefb0302d6f8650899b0863120e4c\"," + + "\"layer\":\"app\"," + + "\"signature\":\"signature\"," + + "\"isSatisfied\":true," + + "\"timestamp\":\"2021-10-13T07:55:33.585017-07:00\"}"; - final String annotationsJson = String.format("{\"items\": [%s,%s]}", annotation, annotation); + final String annotationsJson = + String.format("{\"items\": [%s,%s]}", annotation, annotation); final AnnotationList annotationList = AnnotationList.fromJson(annotationsJson); assertNotNull(annotationList); assertNotNull(annotationList.getAnnotations()); assertEquals( - "AnnotationList initialized with incorrect items length", - annotationList.getAnnotations().size(), - 2 - ); + "AnnotationList initialized with incorrect items length", + annotationList.getAnnotations().size(), + 2); } } diff --git a/src/test/java/com/alvarium/contracts/AnnotationTest.java b/src/test/java/com/alvarium/contracts/AnnotationTest.java index b079072..e05c21d 100644 --- a/src/test/java/com/alvarium/contracts/AnnotationTest.java +++ b/src/test/java/com/alvarium/contracts/AnnotationTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.contracts; import static org.junit.Assert.assertEquals; @@ -32,27 +31,36 @@ public class AnnotationTest { private final Instant testTimestamp; private final String testId; - public AnnotationTest() throws IOException{ + public AnnotationTest() throws IOException { String path = "./src/test/java/com/alvarium/contracts/data.json"; testJson = Files.readString(Paths.get(path), StandardCharsets.US_ASCII); testId = "01FE0RFFJY94R1ER2AM9BG63E2"; - testTimestamp = DateTimeFormatter.ISO_ZONED_DATE_TIME - .parse("2021-08-24T12:22:33.334070489-05:00", Instant::from); + testTimestamp = + DateTimeFormatter.ISO_ZONED_DATE_TIME.parse( + "2021-08-24T12:22:33.334070489-05:00", Instant::from); } @Test public void toJsonShouldReturnTheRightRepresentation() { - Annotation annotation = new Annotation("key", HashType.MD5Hash, "host", LayerType.Application, AnnotationType.TPM, - "signature", true, testTimestamp); + Annotation annotation = + new Annotation( + "key", + HashType.MD5Hash, + "host", + LayerType.Application, + AnnotationType.TPM, + "signature", + true, + testTimestamp); String result = annotation.toJson(); System.out.println(result); } - + @Test public void fromJsonShouldReturnAnObjectWithTheRightProps() { - Annotation annotation = Annotation.fromJson(this.testJson); + Annotation annotation = Annotation.fromJson(this.testJson); assertEquals(this.testId, annotation.getId()); assertEquals("320", annotation.getKey()); assertEquals(HashType.MD5Hash, annotation.getHash()); diff --git a/src/test/java/com/alvarium/hash/HashProviderTest.java b/src/test/java/com/alvarium/hash/HashProviderTest.java index a5064f0..0047c72 100644 --- a/src/test/java/com/alvarium/hash/HashProviderTest.java +++ b/src/test/java/com/alvarium/hash/HashProviderTest.java @@ -1,31 +1,33 @@ -// /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.hash; +import static org.junit.Assert.assertEquals; + import java.util.Random; -import static org.junit.Assert.assertEquals; import org.junit.Test; public class HashProviderTest { private final String[] testCases = {"alvarium is the best", "foo bar"}; private final String[] sha256Hashes = { - "DD22AA6A8CF771E812349DA134CB266471DEBB549B0E2908091C61B1C47FA853", - "FBC1A9F858EA9E177916964BD88C3D37B91A1E84412765E29950777F265C4B75"}; - private final String[] md5Hashes = { "8F907CCF83C58F0D8E84BABA9DF0DBB7", - "327B6F07435811239BC47E1544353273" }; + "DD22AA6A8CF771E812349DA134CB266471DEBB549B0E2908091C61B1C47FA853", + "FBC1A9F858EA9E177916964BD88C3D37B91A1E84412765E29950777F265C4B75" + }; + private final String[] md5Hashes = { + "8F907CCF83C58F0D8E84BABA9DF0DBB7", "327B6F07435811239BC47E1544353273" + }; @Test public void noneProviderShouldReturnTheSameString() throws HashTypeException { @@ -54,9 +56,9 @@ public void sha256ProviderShouldGenerateAppropriateHashes() throws HashTypeExcep public void md5ProviderShouldGenerateAppropriateHashes() throws HashTypeException { HashProviderFactory hashProviderFactory = new HashProviderFactory(); HashProvider sut = hashProviderFactory.getProvider(HashType.MD5Hash); - + for (int i = 0; i < testCases.length; i++) { - final String result = sut.derive(testCases[i].getBytes()); + final String result = sut.derive(testCases[i].getBytes()); assertEquals(md5Hashes[i], result); } } @@ -65,7 +67,7 @@ public void md5ProviderShouldGenerateAppropriateHashes() throws HashTypeExceptio public void md5ProviderUpdateReturnsSameAsDerive() throws Exception { HashProviderFactory hashProviderFactory = new HashProviderFactory(); HashProvider provider = hashProviderFactory.getProvider(HashType.MD5Hash); - + final String exampleString = "foo"; provider.update(exampleString.getBytes()); String hash1 = provider.getValue(); @@ -91,9 +93,14 @@ String generateRandomString(int length) { int lowerLimit = 97; int upperLimit = 122; Random random = new Random(); - String generatedString = random.ints(lowerLimit, upperLimit + 1).limit(length) - .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) - .toString(); + String generatedString = + random.ints(lowerLimit, upperLimit + 1) + .limit(length) + .collect( + StringBuilder::new, + StringBuilder::appendCodePoint, + StringBuilder::append) + .toString(); return generatedString; } } diff --git a/src/test/java/com/alvarium/sign/KeyInfoTest.java b/src/test/java/com/alvarium/sign/KeyInfoTest.java index 8bb1bae..2160973 100644 --- a/src/test/java/com/alvarium/sign/KeyInfoTest.java +++ b/src/test/java/com/alvarium/sign/KeyInfoTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; import static org.junit.Assert.assertEquals; @@ -28,7 +27,7 @@ public class KeyInfoTest { public void toJsonShouldReturnAppropriateRepresentation() { final KeyInfo keyInfo = new KeyInfo("./key.json", SignType.Ed25519); System.out.println(keyInfo.toJson()); - } + } @Test public void fromJsonShouldReturnAnObjectWithTheRightProps() throws IOException { diff --git a/src/test/java/com/alvarium/sign/SignProviderTest.java b/src/test/java/com/alvarium/sign/SignProviderTest.java index 7cfcc49..528c753 100644 --- a/src/test/java/com/alvarium/sign/SignProviderTest.java +++ b/src/test/java/com/alvarium/sign/SignProviderTest.java @@ -1,21 +1,18 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; - -import org.junit.Test; import static org.junit.Assert.*; import java.nio.charset.StandardCharsets; @@ -25,12 +22,14 @@ import com.alvarium.utils.Encoder; import com.google.crypto.tink.subtle.Ed25519Sign; +import org.junit.Test; + public class SignProviderTest { @Test(expected = SignException.class) public void factoryShouldReturnNoConcreteTypesError() throws SignException { final SignProviderFactory factory = new SignProviderFactory(); - factory.getProvider(SignType.none); + factory.getProvider(SignType.none); } @Test @@ -41,11 +40,11 @@ public void factoryShouldReturnEd25519() throws SignException { } @Test - public void signAndVerifyShouldVerifyTrue() throws Exception { + public void signAndVerifyShouldVerifyTrue() throws Exception { final Ed25519Sign.KeyPair keyPair = Ed25519Sign.KeyPair.newKeyPair(); final byte[] privateKey = keyPair.getPrivateKey(); final byte[] publicKey = keyPair.getPublicKey(); - + byte[] content = "hello".getBytes(); final SignProviderFactory factory = new SignProviderFactory(); @@ -70,17 +69,19 @@ public void signAndVerifyShouldVerifyFalse() throws Exception { final String signedString = signProvider.sign(privateKey, content); final byte[] signed = Encoder.hexToBytes(signedString); - signProvider.verify(wrongPublicKey, content, signed); + signProvider.verify(wrongPublicKey, content, signed); } @Test public void signWithProvidedKeyFilesShouldVerifyTrue() throws Exception { - + // Load keys from files String pirvateKeyPath = "./src/test/java/com/alvarium/sign/private.key"; String publicKeyPath = "./src/test/java/com/alvarium/sign/public.key"; - final String privateKey = Files.readString(Paths.get(pirvateKeyPath), StandardCharsets.US_ASCII); - final String publicKey = Files.readString(Paths.get(publicKeyPath), StandardCharsets.US_ASCII); + final String privateKey = + Files.readString(Paths.get(pirvateKeyPath), StandardCharsets.US_ASCII); + final String publicKey = + Files.readString(Paths.get(publicKeyPath), StandardCharsets.US_ASCII); // Decode keys into bytes final byte[] privateKeyDecoded = Encoder.hexToBytes(privateKey); @@ -95,5 +96,4 @@ public void signWithProvidedKeyFilesShouldVerifyTrue() throws Exception { final byte[] signed = Encoder.hexToBytes(signedString); signProvider.verify(publicKeyDecoded, content, signed); } - } diff --git a/src/test/java/com/alvarium/sign/SignatureInfoTest.java b/src/test/java/com/alvarium/sign/SignatureInfoTest.java index 07f0c38..b30f058 100644 --- a/src/test/java/com/alvarium/sign/SignatureInfoTest.java +++ b/src/test/java/com/alvarium/sign/SignatureInfoTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.sign; import static org.junit.Assert.assertEquals; @@ -28,12 +27,12 @@ public class SignatureInfoTest { public void toJsonShouldReturnAppropriateRepresentation() { final KeyInfo keyInfo = new KeyInfo("./key.json", SignType.Ed25519); final SignatureInfo sig = new SignatureInfo(keyInfo, keyInfo); - + System.out.println(sig.toJson()); } @Test - public void fromJsonShouldReturnAnObjectWithTheRightProps() throws IOException{ + public void fromJsonShouldReturnAnObjectWithTheRightProps() throws IOException { String path = "./src/test/java/com/alvarium/sign/signatureInfoData.json"; final String testJson = Files.readString(Paths.get(path), StandardCharsets.US_ASCII); diff --git a/src/test/java/com/alvarium/streams/MqttStreamProviderTest.java b/src/test/java/com/alvarium/streams/MqttStreamProviderTest.java index 0186d4f..e4fd8b4 100644 --- a/src/test/java/com/alvarium/streams/MqttStreamProviderTest.java +++ b/src/test/java/com/alvarium/streams/MqttStreamProviderTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import static org.junit.Assert.assertNotNull; @@ -27,22 +26,22 @@ import org.junit.Test; /** - * Tests for connecting with the MQTT broker are not annotated with `@Test` so these tests do not + * Tests for connecting with the MQTT broker are not annotated with `@Test` so these tests do not * run during unit testing. This is because no MQTT endpoint is guranteed in the build pipeline for * the SDK. - * + * * This class does include tests for loading MQTT configuration */ public class MqttStreamProviderTest { - + // Test that the config-loaded configuration can actually be casted to MqttConfig type @Test public void mqttShouldLoadConfig() throws StreamException { final String path = "./src/test/java/com/alvarium/streams/mqtt-config.json"; final String testJson; try { - testJson = Files.readString(Paths.get(path), StandardCharsets.US_ASCII); - } catch(IOException e) { + testJson = Files.readString(Paths.get(path), StandardCharsets.US_ASCII); + } catch (IOException e) { throw new StreamException("Could not read configuration file", e); } final StreamInfo info = StreamInfo.fromJson(testJson); @@ -55,7 +54,7 @@ public void mqttShouldPublish() throws Exception { String testJson = Files.readString(Paths.get(path), StandardCharsets.US_ASCII); StreamInfo info = StreamInfo.fromJson(testJson); StreamProviderFactory factory = new StreamProviderFactory(); - StreamProvider mqttProvider = factory.getProvider(info); + StreamProvider mqttProvider = factory.getProvider(info); String msg = "hello"; PublishWrapper wrapper = new PublishWrapper(SdkAction.CREATE, String.class.toString(), msg); mqttProvider.publish(wrapper); @@ -66,7 +65,7 @@ public void mqttShouldConnect() throws Exception { String testJson = Files.readString(Paths.get(path), StandardCharsets.US_ASCII); StreamInfo info = StreamInfo.fromJson(testJson); StreamProviderFactory factory = new StreamProviderFactory(); - StreamProvider mqttProvider = factory.getProvider(info); + StreamProvider mqttProvider = factory.getProvider(info); mqttProvider.connect(); } @@ -75,7 +74,7 @@ public void mqttShouldClose() throws Exception { String testJson = Files.readString(Paths.get(path), StandardCharsets.US_ASCII); StreamInfo info = StreamInfo.fromJson(testJson); StreamProviderFactory factory = new StreamProviderFactory(); - StreamProvider mqttProvider = factory.getProvider(info); + StreamProvider mqttProvider = factory.getProvider(info); mqttProvider.connect(); String msg = "hello"; PublishWrapper wrapper = new PublishWrapper(SdkAction.CREATE, String.class.toString(), msg); diff --git a/src/test/java/com/alvarium/streams/PravegaStreamProviderTest.java b/src/test/java/com/alvarium/streams/PravegaStreamProviderTest.java index 2d3b841..63afa45 100644 --- a/src/test/java/com/alvarium/streams/PravegaStreamProviderTest.java +++ b/src/test/java/com/alvarium/streams/PravegaStreamProviderTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import static org.junit.Assert.assertNotNull; @@ -27,15 +26,15 @@ import org.junit.Test; /** - * The @Test annotation is removed from some of the methods in this class as they are considered + * The @Test annotation is removed from some of the methods in this class as they are considered * integration tests rather than unit tests. This lives here for local testing purposes only. - * + * * To be able to run the tests, you'll have to setup a local Pravega controller on your machine. * more info on deployment can be found here: * https://github.com/pravega/pravega/blob/master/documentation/src/docs/deployment/run-local.md - * + * * To be able to read from the stream, you'll have to use the pravega cli tool to subscribe - * to a specific stream. + * to a specific stream. * more info here: * https://pravega.io/docs/nightly/getting-started/quick-start/ */ @@ -60,7 +59,7 @@ public void pravegaStreamProviderShouldConnect() throws StreamException, IOExcep StreamProvider pravega = factory.getProvider(info); pravega.connect(); pravega.close(); - } + } public void pravegaStreamProviderShouldPublish() throws StreamException, IOException { final String path = "./src/test/java/com/alvarium/streams/pravega-config.json"; @@ -71,10 +70,10 @@ public void pravegaStreamProviderShouldPublish() throws StreamException, IOExcep StreamProvider pravega = factory.getProvider(info); pravega.connect(); - PublishWrapper wrapper = new PublishWrapper(SdkAction.CREATE, String.class.getSimpleName(), - "test"); + PublishWrapper wrapper = + new PublishWrapper(SdkAction.CREATE, String.class.getSimpleName(), "test"); pravega.publish(wrapper); pravega.close(); - } + } } diff --git a/src/test/java/com/alvarium/streams/StreamProviderTest.java b/src/test/java/com/alvarium/streams/StreamProviderTest.java index 5d0a43a..5af7193 100644 --- a/src/test/java/com/alvarium/streams/StreamProviderTest.java +++ b/src/test/java/com/alvarium/streams/StreamProviderTest.java @@ -1,17 +1,16 @@ - /******************************************************************************* - * Copyright 2021 Dell Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - *******************************************************************************/ +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.streams; import com.alvarium.PublishWrapper; @@ -25,12 +24,11 @@ public void mockStreamProviderShouldNotThrow() throws StreamException { final StreamProviderFactory factory = new StreamProviderFactory(); final StreamInfo info = new StreamInfo(StreamType.MOCK, null); final StreamProvider provider = factory.getProvider(info); - final PublishWrapper wrapper = new PublishWrapper(SdkAction.CREATE, "test type", - "test content"); - + final PublishWrapper wrapper = + new PublishWrapper(SdkAction.CREATE, "test type", "test content"); provider.connect(); provider.publish(wrapper); provider.close(); - } + } } diff --git a/src/test/java/com/alvarium/utils/EncoderTest.java b/src/test/java/com/alvarium/utils/EncoderTest.java index c9cd29d..65ecb51 100644 --- a/src/test/java/com/alvarium/utils/EncoderTest.java +++ b/src/test/java/com/alvarium/utils/EncoderTest.java @@ -1,14 +1,28 @@ +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.utils; -import java.security.SecureRandom; - import static org.junit.Assert.assertEquals; +import java.security.SecureRandom; + import org.junit.Test; public class EncoderTest { - private final byte[][] bytes = { { (byte) 0xAA, (byte) 0xFF, (byte) 0x1 }, - {(byte) 0xB, (byte) 0x0, (byte) 0x11, (byte)0x4F} }; + private final byte[][] bytes = { + {(byte) 0xAA, (byte) 0xFF, (byte) 0x1}, {(byte) 0xB, (byte) 0x0, (byte) 0x11, (byte) 0x4F} + }; private final String[] hex = {"AAFF01", "0B00114F"}; @Test @@ -16,7 +30,7 @@ public void bytesToHexShouldReturnDoubleLength() { for (int i = 0; i < 20; i++) { byte[] data = new byte[i]; - new SecureRandom().nextBytes(data); + new SecureRandom().nextBytes(data); String hexResult = Encoder.bytesToHex(data); assertEquals(data.length * 2, hexResult.length()); } @@ -42,7 +56,7 @@ public void hexToBytesShouldRemoveIncompleteByte() { public void hexToBytesShouldConvertToByte() { final String data = "111F"; final byte[] expectedBytes = {0x11, 0x1F}; - final byte[] bytesResult = Encoder.hexToBytes(data); + final byte[] bytesResult = Encoder.hexToBytes(data); assertEquals(new String(expectedBytes), new String(bytesResult)); } } diff --git a/src/test/java/com/alvarium/utils/PropertyBagTest.java b/src/test/java/com/alvarium/utils/PropertyBagTest.java index eab1e1c..654ec3c 100644 --- a/src/test/java/com/alvarium/utils/PropertyBagTest.java +++ b/src/test/java/com/alvarium/utils/PropertyBagTest.java @@ -1,3 +1,16 @@ +/******************************************************************************* +* Copyright 2024 Dell Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*******************************************************************************/ package com.alvarium.utils; import static org.junit.Assert.assertEquals; @@ -9,19 +22,19 @@ public class PropertyBagTest { @Test public void getPropertyShouldGetValue() { - final HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("foo", "bar"); final PropertyBag properties = new ImmutablePropertyBag(map); assertEquals(map.get("foo"), properties.getProperty("foo", String.class)); - assertEquals(map.get("foo").getClass(), properties.getProperty("foo", String.class).getClass()); + assertEquals( + map.get("foo").getClass(), properties.getProperty("foo", String.class).getClass()); } @Test(expected = IllegalArgumentException.class) public void getPropertyShouldThrowException() throws IllegalArgumentException { - final HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("foo", "bar"); final PropertyBag properties = new ImmutablePropertyBag(map); properties.getProperty("hello", String.class); - } }