From 64c74eae5c2d7891e618b8bd1bb4573ef2687367 Mon Sep 17 00:00:00 2001 From: TheSilentCoder <184309164+ThatSilentCoder@users.noreply.github.com> Date: Tue, 22 Oct 2024 17:16:50 -0400 Subject: [PATCH] issue_847: Applied formatting changes to entire CA module_portal module. Reduced errors in CA module to less than 180 --- .../persist/OrderedListQuerier.java | 9 +- .../persist/entity/userdefined/Device.java | 34 +- .../entity/userdefined/ReferenceManifest.java | 20 +- .../IssuedAttestationCertificate.java | 4 +- .../attributes/V2/package-info.java | 2 +- .../record/TPMMeasurementRecord.java | 1 + .../userdefined/record/package-info.java | 1 + .../userdefined/report/DeviceInfoReport.java | 47 +- .../userdefined/report/package-info.java | 1 + .../userdefined/result/package-info.java | 1 + .../rim/BaseReferenceManifest.java | 77 +- .../userdefined/rim/EventLogMeasurements.java | 25 +- .../userdefined/rim/ReferenceDigestValue.java | 38 +- .../entity/userdefined/rim/package-info.java | 2 +- .../persist/enums/HealthStatus.java | 25 +- .../persist/exceptions/package-info.java | 1 + .../provision/IdentityClaimProcessor.java | 43 +- .../provision/helper/ProvisionUtils.java | 98 ++- .../provision/helper/package-info.java | 1 + .../persist/provision/package-info.java | 1 + .../persist/service/ValidationService.java | 186 ++-- .../persist/service/package-info.java | 1 + .../service/selector/CertificateSelector.java | 10 +- .../service/selector/package-info.java | 1 + .../persist/tpm/package-info.java | 1 + .../persist/type/package-info.java | 1 + .../persist/util/CredentialHelper.java | 2 +- .../persist/util/package-info.java | 1 + .../CertificateAttributeScvValidator.java | 27 +- .../validation/CredentialValidator.java | 8 +- .../validation/FirmwareScvValidator.java | 38 +- .../persist/validation/PcrValidator.java | 30 +- .../SupplyChainCredentialValidator.java | 4 +- .../persist/validation/package-info.java | 1 + .../entity/tpm/TPM2ProvisionerStateTest.java | 88 +- HIRS_AttestationCAPortal/build.gradle | 58 +- .../config/spotbugs/spotbugs-exclude.xml | 4 +- .../attestationca/portal/HIRSApplication.java | 10 - .../portal/HIRSDbInitializer.java | 12 +- .../portal/PersistenceJPAConfig.java | 9 +- .../portal/datatables/DataTableInput.java | 132 ++- .../portal/datatables/DataTableResponse.java | 6 +- .../portal/datatables/DataTableView.java | 11 +- .../portal/datatables/Order.java | 36 +- .../OrderedListQueryDataTableAdapter.java | 33 +- .../portal/datatables/Search.java | 18 +- .../hirs/attestationca/portal/page/Page.java | 24 +- .../portal/page/PageController.java | 14 +- .../CertificateDetailsPageController.java | 9 +- .../CertificatePageController.java | 194 ++-- .../controllers/DevicePageController.java | 7 +- .../page/controllers/HelpPageController.java | 5 +- .../page/controllers/IndexPageController.java | 2 +- .../controllers/PolicyPageController.java | 113 ++- ...eferenceManifestDetailsPageController.java | 175 ++-- .../ReferenceManifestPageController.java | 44 +- .../RimDatabasePageController.java | 16 +- .../ValidationReportsPageController.java | 48 +- .../portal/page/params/NoPageParams.java | 1 + .../ReferenceManifestDetailsPageParams.java | 3 +- .../params/ReferenceManifestPageParams.java | 2 +- .../utils/CertificateStringMapBuilder.java | 76 +- .../src/main/resources/log4j2-spring.win.xml | 16 +- .../src/main/resources/log4j2-spring.xml | 18 +- .../src/main/webapp/WEB-INF/web.xml | 4 +- .../fonts/glyphicons-halflings-regular.svg | 825 ++++++++++++------ .../portal/page/PageControllerTest.java | 126 +-- .../portal/page/PageTestConfiguration.java | 31 +- .../controllers/DevicePageControllerTest.java | 33 +- ...ementKeyCredentialsPageControllerTest.java | 35 +- .../IssuedCertificatesPageControllerTest.java | 48 +- ...PlatformCredentialsPageControllerTest.java | 30 +- .../controllers/PolicyPageControllerTest.java | 19 +- ...rustChainManagementPageControllerTest.java | 34 +- .../utils/rim/ReferenceManifestValidator.java | 2 +- 75 files changed, 1730 insertions(+), 1383 deletions(-) create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/exceptions/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/package-info.java create mode 100644 HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/package-info.java diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/OrderedListQuerier.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/OrderedListQuerier.java index 6eeb8de3..63e93515 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/OrderedListQuerier.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/OrderedListQuerier.java @@ -23,8 +23,8 @@ public interface OrderedListQuerier { * @param maxResults total number we want returned for display in table * @param search string of criteria to be matched to visible columns * @param searchableColumns Map of String and boolean values with column - * headers and whether they should be searched. Boolean is true if field provides a - * typical String that can be searched by Hibernate without transformation. + * headers and whether they should be searched. Boolean is true if field provides + * a typical String that can be searched by Hibernate without transformation. * @return FilteredRecordsList object with query data * @throws DBManagerException if unable to create the list */ @@ -50,13 +50,12 @@ public interface OrderedListQuerier { * @param maxResults total number we want returned for display in table * @param search string of criteria to be matched to visible columns * @param searchableColumns Map of String and boolean values with column - * headers and whether they should be searched. Boolean is true if field provides a - * typical String that can be searched by Hibernate without transformation. + * headers and whether they should be searched. Boolean is true if field provides + * a typical String that can be searched by Hibernate without transformation. * @param criteriaModifier a way to modify the criteria used in the query * @return FilteredRecordsList object with query data * @throws DBManagerException if unable to create the list */ - @SuppressWarnings("checkstyle:parameternumber") FilteredRecordsList getOrderedList( Class clazz, String columnToOrder, boolean ascending, int firstResult, diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Device.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Device.java index d3f26d4a..ed3d1ffc 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Device.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/Device.java @@ -14,19 +14,20 @@ import jakarta.persistence.OneToOne; import jakarta.persistence.Table; import lombok.AccessLevel; import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.sql.Timestamp; import java.time.LocalDateTime; -import java.util.Objects; @Entity @Table(name = "Device") @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor +@EqualsAndHashCode(callSuper = false) public class Device extends AbstractEntity { @Getter @@ -34,7 +35,7 @@ public class Device extends AbstractEntity { private String name; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, - optional = true, orphanRemoval = true) + orphanRemoval = true) private DeviceInfoReport deviceInfo; @Getter @@ -113,7 +114,7 @@ public class Device extends AbstractEntity { /** * Setter for the report time stamp. * - * @param lastReportTimestamp + * @param lastReportTimestamp last reported time */ public void setLastReportTimestamp(final Timestamp lastReportTimestamp) { this.lastReportTimestamp = (Timestamp) lastReportTimestamp.clone(); @@ -122,32 +123,7 @@ public class Device extends AbstractEntity { @Override public String toString() { return String.format("Device Name: %s%nStatus: %s%nSummary: %s%n", - name, (healthStatus == null ? "N/A" : healthStatus.getStatus()), + name, (healthStatus == null ? "N/A" : healthStatus.getHealthStatus()), (supplyChainValidationStatus == null ? "N/A" : supplyChainValidationStatus.toString())); } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Device device)) { - return false; - } - - return isStateOverridden == device.isStateOverridden - && Objects.equals(name, device.name) - && healthStatus == device.healthStatus - && supplyChainValidationStatus == device.supplyChainValidationStatus - && Objects.equals(lastReportTimestamp, device.lastReportTimestamp) - && Objects.equals(overrideReason, device.overrideReason) - && Objects.equals(summaryId, device.summaryId); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), name, healthStatus, - supplyChainValidationStatus, lastReportTimestamp, - isStateOverridden, overrideReason, summaryId); - } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ReferenceManifest.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ReferenceManifest.java index 4388451a..572dd153 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ReferenceManifest.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/ReferenceManifest.java @@ -10,6 +10,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @@ -29,6 +30,7 @@ import java.util.UUID; * loaded into the DB and displayed in the ACA. */ @Getter +@Setter @ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false) @Log4j2 @@ -73,73 +75,59 @@ public class ReferenceManifest extends ArchivableEntity { */ public static final String SCHEMA_PACKAGE = "hirs.utils.xjc"; + @Setter(AccessLevel.NONE) @EqualsAndHashCode.Include @Column(columnDefinition = "mediumblob", nullable = false) private final byte[] rimBytes; - @Setter + @EqualsAndHashCode.Include @Column(nullable = false) private String rimType = "Base"; - @Setter @Column private String tagId = null; - @Setter @Column private boolean swidPatch = false; - @Setter @Column private boolean swidSupplemental = false; - @Setter @Column private String platformManufacturer = null; - @Setter @Column private String platformManufacturerId = null; - @Setter @Column private String swidTagVersion = null; - @Setter @Column private String swidVersion = null; - @Setter @Column private String platformModel = null; - @Setter @Column(nullable = false) private String fileName = null; - @Setter @JdbcTypeCode(java.sql.Types.VARCHAR) @Column private UUID associatedRim; - @Setter @Column private String deviceName; - @Setter @Column private String hexDecHash = ""; - @Setter @Column private String eventLogHash = ""; - @Setter @Column @JsonIgnore private String base64Hash = ""; - /** * Default constructor necessary for Hibernate. */ diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IssuedAttestationCertificate.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IssuedAttestationCertificate.java index dd219ff0..4202362f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IssuedAttestationCertificate.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/IssuedAttestationCertificate.java @@ -45,11 +45,13 @@ public class IssuedAttestationCertificate extends DeviceAssociatedCertificate { * @param certificateBytes the issued certificate bytes * @param endorsementCredential the endorsement credential * @param platformCredentials the platform credentials + * @param isLDevID is LDevId * @throws IOException if there is a problem extracting information from the certificate */ public IssuedAttestationCertificate(final byte[] certificateBytes, final EndorsementCredential endorsementCredential, - final List platformCredentials, boolean isLDevID) + final List platformCredentials, + final boolean isLDevID) throws IOException { super(certificateBytes); this.endorsementCredential = endorsementCredential; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/package-info.java index 59110856..12ec500e 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/package-info.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/certificate/attributes/V2/package-info.java @@ -1 +1 @@ -package hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2; \ No newline at end of file +package hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecord.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecord.java index c74d93a8..16dc27a6 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecord.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/TPMMeasurementRecord.java @@ -55,6 +55,7 @@ public final class TPMMeasurementRecord extends ExaminableRecord { @Column(name = "pcr", nullable = false) @XmlAttribute(name = "PcrNumber", required = true) private final int pcrId; + @Embedded @XmlElement private final Digest hash; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/package-info.java new file mode 100644 index 00000000..a297fc9c --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/record/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.userdefined.record; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReport.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReport.java index 74bbdec8..a589dbbe 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReport.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/DeviceInfoReport.java @@ -13,6 +13,8 @@ import jakarta.persistence.Embedded; import jakarta.persistence.Entity; import jakarta.persistence.Transient; import jakarta.xml.bind.annotation.XmlElement; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -20,16 +22,15 @@ import lombok.extern.log4j.Log4j2; import java.io.Serializable; import java.net.InetAddress; -import java.util.Objects; /** * A DeviceInfoReport is a Report used to transfer the * information about the device. This Report includes the network, * OS, and TPM information. */ -@Log4j2 @NoArgsConstructor -@Getter +@EqualsAndHashCode(callSuper = false) +@Log4j2 @Entity public class DeviceInfoReport extends AbstractEntity implements Serializable { @@ -49,14 +50,18 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { @Embedded private HardwareInfo hardwareInfo; + @Setter(AccessLevel.PRIVATE) + @Getter @XmlElement @Embedded private TPMInfo tpmInfo; + @Getter @XmlElement @Column(nullable = false) private String clientApplicationVersion; + @Getter @Setter @XmlElement @Transient @@ -91,8 +96,8 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { * @param hardwareInfo HardwareInfo object, cannot be null * @param tpmInfo TPMInfo object, may be null if a TPM is not available on the * device - * @param clientApplicationVersion string representing the version of the client that submitted this report, - * cannot be null + * @param clientApplicationVersion string representing the version of the client that submitted this + * report, cannot be null */ public DeviceInfoReport(final NetworkInfo networkInfo, final OSInfo osInfo, final FirmwareInfo firmwareInfo, final HardwareInfo hardwareInfo, @@ -101,7 +106,7 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { setOSInfo(osInfo); setFirmwareInfo(firmwareInfo); setHardwareInfo(hardwareInfo); - setTPMInfo(tpmInfo); + setTpmInfo(tpmInfo); this.clientApplicationVersion = clientApplicationVersion; } @@ -216,32 +221,6 @@ public class DeviceInfoReport extends AbstractEntity implements Serializable { } this.hardwareInfo = hardwareInfo; } - - private void setTPMInfo(final TPMInfo tpmInfo) { - this.tpmInfo = tpmInfo; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof DeviceInfoReport that)) { - return false; - } - return Objects.equals(networkInfo, that.networkInfo) - && Objects.equals(osInfo, that.osInfo) - && Objects.equals(firmwareInfo, that.firmwareInfo) - && Objects.equals(hardwareInfo, that.hardwareInfo) - && Objects.equals(tpmInfo, that.tpmInfo) - && Objects.equals(clientApplicationVersion, that.clientApplicationVersion) - && Objects.equals(paccorOutputString, that.paccorOutputString); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), networkInfo, osInfo, - firmwareInfo, hardwareInfo, tpmInfo, - clientApplicationVersion, paccorOutputString); - } } + + diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/package-info.java new file mode 100644 index 00000000..fca94e7e --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/report/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.userdefined.report; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/package-info.java new file mode 100644 index 00000000..3ad7260f --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/result/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.entity.userdefined.result; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/BaseReferenceManifest.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/BaseReferenceManifest.java index 95e8e714..6c993795 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/BaseReferenceManifest.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/BaseReferenceManifest.java @@ -10,6 +10,7 @@ import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.UnmarshalException; import jakarta.xml.bind.Unmarshaller; import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -33,7 +34,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; -import java.util.Objects; /** * @@ -42,6 +42,7 @@ import java.util.Objects; @Getter @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) +@EqualsAndHashCode @Entity public class BaseReferenceManifest extends ReferenceManifest { /** @@ -53,43 +54,60 @@ public class BaseReferenceManifest extends ReferenceManifest { @Column private String swidName = null; + @Column private int swidCorpus = 0; + @Column private String colloquialVersion = null; + @Column private String product = null; + @Column private String revision = null; + @Column private String edition = null; + @Column private String rimLinkHash = null; + @Column private String bindingSpec = null; + @Column private String bindingSpecVersion = null; + @Column private String platformVersion = null; + @Column private String payloadType = null; + @Column private String pcURIGlobal = null; + @Column private String pcURILocal = null; private String entityName = null; + private String entityRegId = null; + private String entityRole = null; + private String entityThumbprint = null; + private String linkHref = null; + private String linkRel = null; /** * Support constructor for the RIM object. * * @param rimBytes - the file content of the uploaded file. - * @throws IOException - thrown if the file is invalid. + * @throws UnmarshalException - thrown if the file is invalid. */ public BaseReferenceManifest(final byte[] rimBytes) throws UnmarshalException { this("", rimBytes); @@ -101,9 +119,8 @@ public class BaseReferenceManifest extends ReferenceManifest { * * @param fileName - string representation of the uploaded file. * @param rimBytes byte array representation of the RIM - * @throws IOException if unable to unmarshal the string + * @throws UnmarshalException if unable to unmarshal the string */ - @SuppressWarnings("checkstyle:AvoidInlineConditionals") public BaseReferenceManifest(final String fileName, final byte[] rimBytes) throws UnmarshalException { super(rimBytes); @@ -206,6 +223,9 @@ public class BaseReferenceManifest extends ReferenceManifest { * This method validates the .swidtag file at the given filepath against the * schema. A successful validation results in the output of the tag's name * and tagId attributes, otherwise a generic error message is printed. + * + * @param rimBytes byte array representation of the RIM + * @return an element */ private Element getDirectoryTag(final byte[] rimBytes) { if (rimBytes == null || rimBytes.length == 0) { @@ -221,6 +241,7 @@ public class BaseReferenceManifest extends ReferenceManifest { * and tagId attributes, otherwise a generic error message is printed. * * @param byteArrayInputStream the location of the file to be validated + * @return an element */ private Element getDirectoryTag(final ByteArrayInputStream byteArrayInputStream) { Document document = null; @@ -247,7 +268,9 @@ public class BaseReferenceManifest extends ReferenceManifest { } /** - * This method iterates over the list of File elements under the directory. * + * This method iterates over the list of File elements under the directory. + * + * @return a list of swid resources */ public List getFileResources() { return getFileResources(getRimBytes()); @@ -257,6 +280,7 @@ public class BaseReferenceManifest extends ReferenceManifest { * This method iterates over the list of File elements under the directory. * * @param rimBytes the bytes to find the files + * @return a list of swid resources */ public List getFileResources(final byte[] rimBytes) { Element directoryTag = getDirectoryTag(rimBytes); @@ -353,49 +377,6 @@ public class BaseReferenceManifest extends ReferenceManifest { return document; } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - if (!super.equals(o)) { - return false; - } - BaseReferenceManifest that = (BaseReferenceManifest) o; - return swidCorpus == that.swidCorpus && Objects.equals(swidName, that.swidName) - && Objects.equals(colloquialVersion, that.colloquialVersion) - && Objects.equals(product, that.product) - && Objects.equals(revision, that.revision) - && Objects.equals(edition, that.edition) - && Objects.equals(rimLinkHash, that.rimLinkHash) - && Objects.equals(bindingSpec, that.bindingSpec) - && Objects.equals(bindingSpecVersion, that.bindingSpecVersion) - && Objects.equals(platformVersion, that.platformVersion) - && Objects.equals(payloadType, that.payloadType) - && Objects.equals(pcURIGlobal, that.pcURIGlobal) - && Objects.equals(pcURILocal, that.pcURILocal) - && Objects.equals(entityName, that.entityName) - && Objects.equals(entityRegId, that.entityRegId) - && Objects.equals(entityRole, that.entityRole) - && Objects.equals(entityThumbprint, that.entityThumbprint) - && Objects.equals(linkHref, that.linkHref) - && Objects.equals(linkRel, that.linkRel); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), swidName, - swidCorpus, colloquialVersion, product, - revision, edition, rimLinkHash, bindingSpec, - bindingSpecVersion, platformVersion, - payloadType, pcURIGlobal, pcURILocal, - entityName, entityRegId, entityRole, - entityThumbprint, linkHref, linkRel); - } - @Override public String toString() { return String.format("ReferenceManifest{swidName=%s," diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/EventLogMeasurements.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/EventLogMeasurements.java index a77bfe44..57607c72 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/EventLogMeasurements.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/EventLogMeasurements.java @@ -24,18 +24,17 @@ import java.util.Collection; * Similar to {@link SupportReferenceManifest} * however this is the live log from the client. */ +@Getter +@Setter @Log4j2 @Entity public class EventLogMeasurements extends SupportReferenceManifest { @Column @JsonIgnore - @Getter - @Setter private int pcrHash = 0; + @Enumerated(EnumType.STRING) - @Getter - @Setter private AppraisalStatus.Status overallValidationResult = AppraisalStatus.Status.FAIL; /** @@ -83,12 +82,8 @@ public class EventLogMeasurements extends SupportReferenceManifest { TCGEventLog logProcessor = new TCGEventLog(this.getRimBytes()); this.pcrHash = Arrays.hashCode(logProcessor.getExpectedPCRValues()); return logProcessor.getExpectedPCRValues(); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } return new String[0]; @@ -104,12 +99,8 @@ public class EventLogMeasurements extends SupportReferenceManifest { try { logProcessor = new TCGEventLog(this.getRimBytes()); return logProcessor.getEventList(); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } return new ArrayList<>(); @@ -132,4 +123,4 @@ public class EventLogMeasurements extends SupportReferenceManifest { public int hashCode() { return super.hashCode(); } -} \ No newline at end of file +} diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/ReferenceDigestValue.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/ReferenceDigestValue.java index 323be11f..0240c351 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/ReferenceDigestValue.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/ReferenceDigestValue.java @@ -6,6 +6,7 @@ import jakarta.persistence.AccessType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Table; +import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; @@ -21,6 +22,7 @@ import java.util.UUID; * Digest Value, Event Type, index, RIM Tagid */ @Getter +@Setter @Builder @AllArgsConstructor @Entity @@ -28,41 +30,42 @@ import java.util.UUID; @Table(name = "ReferenceDigestValue") @Access(AccessType.FIELD) public class ReferenceDigestValue extends AbstractEntity { - @Setter @JdbcTypeCode(java.sql.Types.VARCHAR) @Column private UUID baseRimId; - @Setter + @JdbcTypeCode(java.sql.Types.VARCHAR) @Column private UUID supportRimId; - @Setter + @Column(nullable = false) private String manufacturer; - @Setter + @Column(nullable = false) private String model; - @Setter + @Column(nullable = false) private int pcrIndex; - @Setter + @Column(nullable = false) private String digestValue; - @Setter + @Column(nullable = false) private String supportRimHash; - @Setter + @Column(nullable = false) private String eventType; - @Column(columnDefinition = "blob", nullable = true) + + @Setter(AccessLevel.NONE) + @Column(columnDefinition = "blob") private byte[] contentBlob; - @Setter + @Column(nullable = false) private boolean matchFail; - @Setter + @Column(nullable = false) private boolean patched; - @Setter + @Column(nullable = false) private boolean updated; @@ -108,6 +111,8 @@ public class ReferenceDigestValue extends AbstractEntity { final String eventType, final boolean matchFail, final boolean patched, final boolean updated, final byte[] contentBlob) { + + this.baseRimId = baseRimId; this.supportRimId = supportRimId; this.manufacturer = manufacturer; @@ -122,15 +127,6 @@ public class ReferenceDigestValue extends AbstractEntity { this.contentBlob = Arrays.clone(contentBlob); } - /** - * the object that contains the raw bytes for this RDV. - * - * @return the raw bytes - */ - public byte[] getContentBlob() { - return Arrays.clone(contentBlob); - } - /** * Helper method to update the attributes of this object. * diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/package-info.java index 85a64fc8..aa634383 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/package-info.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/entity/userdefined/rim/package-info.java @@ -1 +1 @@ -package hirs.attestationca.persist.entity.userdefined.rim; \ No newline at end of file +package hirs.attestationca.persist.entity.userdefined.rim; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/HealthStatus.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/HealthStatus.java index b922a230..c9bff06f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/HealthStatus.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/enums/HealthStatus.java @@ -1,11 +1,16 @@ package hirs.attestationca.persist.enums; +import lombok.AllArgsConstructor; +import lombok.Getter; + import java.util.Arrays; import java.util.stream.Collectors; /** * HealthStatus is used to represent the health of a device. */ +@Getter +@AllArgsConstructor public enum HealthStatus { /** * The trusted state, no issues with the device. @@ -24,15 +29,6 @@ public enum HealthStatus { private final String healthStatus; - /** - * Creates a new HealthStatus object given a String. - * - * @param healthStatus "trusted", "untrusted", or "unknown" - */ - HealthStatus(final String healthStatus) { - this.healthStatus = healthStatus; - } - public static boolean isValidStatus(final String healthStatus) { return Arrays.stream(HealthStatus.values()) .map(HealthStatus::name) @@ -40,17 +36,8 @@ public enum HealthStatus { .contains(healthStatus); } - /** - * Returns the health status. - * - * @return the status - */ - public String getStatus() { - return this.healthStatus; - } - @Override public String toString() { - return getStatus(); + return getHealthStatus(); } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/exceptions/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/exceptions/package-info.java new file mode 100644 index 00000000..4bc1b624 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/exceptions/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.exceptions; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/IdentityClaimProcessor.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/IdentityClaimProcessor.java index f3446c26..1c6baf6c 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/IdentityClaimProcessor.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/IdentityClaimProcessor.java @@ -88,6 +88,16 @@ public class IdentityClaimProcessor extends AbstractProcessor { /** * Constructor. + * + * @param supplyChainValidationService supply chain validation service + * @param certificateRepository certificate repository + * @param componentResultRepository component result repository + * @param componentInfoRepository component info repository + * @param referenceManifestRepository reference manifest repository + * @param referenceDigestValueRepository reference digest value repository + * @param deviceRepository device repository + * @param tpm2ProvisionerStateRepository tpm2 provisioner state repository + * @param policyRepository policy repository */ public IdentityClaimProcessor( final SupplyChainValidationService supplyChainValidationService, @@ -155,8 +165,8 @@ public class IdentityClaimProcessor extends AbstractProcessor { String pcrQuoteMask = PCR_QUOTE_MASK; String strNonce = HexUtils.byteArrayToHexString(nonce); - log.info("Sending nonce: " + strNonce); - log.info("Persisting claim of length: " + identityClaim.length); + log.info("Sending nonce: {}", strNonce); + log.info("Persisting claim of length: {}", identityClaim.length); tpm2ProvisionerStateRepository.save(new TPM2ProvisionerState(nonce, identityClaim)); @@ -171,8 +181,7 @@ public class IdentityClaimProcessor extends AbstractProcessor { .build(); return response.toByteArray(); } else { - log.error("Supply chain validation did not succeed. Result is: " - + validationResult); + log.error("Supply chain validation did not succeed. Result is: {}", validationResult); // empty response ProvisionerTpm2.IdentityClaimResponse response = ProvisionerTpm2.IdentityClaimResponse.newBuilder() @@ -393,8 +402,8 @@ public class IdentityClaimProcessor extends AbstractProcessor { */ List rims = referenceManifestRepository.findByArchiveFlag(false); for (ReferenceManifest rim : rims) { - if (rim.isBase() && rim.getTagId().equals(dbBaseRim.getTagId()) && - rim.getCreateTime().after(dbBaseRim.getCreateTime())) { + if (rim.isBase() && rim.getTagId().equals(dbBaseRim.getTagId()) + && rim.getCreateTime().after(dbBaseRim.getCreateTime())) { dbBaseRim.setDeviceName(null); dbBaseRim = (BaseReferenceManifest) rim; dbBaseRim.setDeviceName(dv.getNw().getHostname()); @@ -413,12 +422,11 @@ public class IdentityClaimProcessor extends AbstractProcessor { } catch (UnmarshalException e) { log.error(e); } catch (Exception ex) { - log.error(String.format("Failed to load base rim: %s", ex.getMessage())); + log.error("Failed to load base rim: {}", ex.getMessage()); } } } else { - log.warn(String.format("%s did not send swid tag file...", - dv.getNw().getHostname())); + log.warn("{} did not send swid tag file...", dv.getNw().getHostname()); } if (dv.getLogfileCount() > 0) { @@ -466,9 +474,9 @@ public class IdentityClaimProcessor extends AbstractProcessor { */ List rims = referenceManifestRepository.findByArchiveFlag(false); for (ReferenceManifest rim : rims) { - if (rim.isSupport() && - rim.getTagId().equals(support.getTagId()) && - rim.getCreateTime().after(support.getCreateTime())) { + if (rim.isSupport() + && rim.getTagId().equals(support.getTagId()) + && rim.getCreateTime().after(support.getCreateTime())) { support.setDeviceName(null); support = (SupportReferenceManifest) rim; support.setDeviceName(dv.getNw().getHostname()); @@ -486,12 +494,11 @@ public class IdentityClaimProcessor extends AbstractProcessor { } catch (IOException ioEx) { log.error(ioEx); } catch (Exception ex) { - log.error(String.format("Failed to load support rim: %s", ex.getMessage())); + log.error("Failed to load support rim: {}", ex.getMessage()); } } } else { - log.warn(String.format("%s did not send support RIM file...", - dv.getNw().getHostname())); + log.warn("{} did not send support RIM file...", dv.getNw().getHostname()); } //update Support RIMs and Base RIMs. @@ -582,8 +589,7 @@ public class IdentityClaimProcessor extends AbstractProcessor { log.error(ioEx); } } else { - log.warn(String.format("%s did not send bios measurement log...", - dv.getNw().getHostname())); + log.warn("{} did not send bios measurement log...", dv.getNw().getHostname()); } // Get TPM info, currently unimplemented @@ -688,8 +694,7 @@ public class IdentityClaimProcessor extends AbstractProcessor { dbRdv = digestValueMap.get(patchedValue); if (dbRdv == null) { - log.error(String.format("Patching value does not exist (%s)", - patchedValue)); + log.error("Patching value does not exist ({})", patchedValue); } else { // WIP - Until we get patch examples dbRdv.setPatched(true); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/ProvisionUtils.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/ProvisionUtils.java index 43af0bce..549a9e6e 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/ProvisionUtils.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/ProvisionUtils.java @@ -51,27 +51,60 @@ public final class ProvisionUtils { /** * The default size for IV blocks. */ - public final static int DEFAULT_IV_SIZE = 16; + public static final int DEFAULT_IV_SIZE = 16; + + /** + * HMAC Size Length in bytes. + */ public static final int HMAC_SIZE_LENGTH_BYTES = 2; + + /** + * HMAC key Length in bytes. + */ public static final int HMAC_KEY_LENGTH_BYTES = 32; + + /** + * Seed Length in bytes. + */ public static final int SEED_LENGTH = 32; + + /** + * Max secret length. + */ public static final int MAX_SECRET_LENGTH = 32; + + /** + * AES Key Length un bytes. + */ public static final int AES_KEY_LENGTH_BYTES = 16; + /** * Defines the well known exponent. * https://en.wikipedia.org/wiki/65537_(number)#Applications */ - private final static BigInteger EXPONENT = new BigInteger("010001", DEFAULT_IV_SIZE); + private static final BigInteger EXPONENT = new BigInteger("010001", DEFAULT_IV_SIZE); + private static final int TPM2_CREDENTIAL_BLOB_SIZE = 392; + private static final int RSA_MODULUS_LENGTH = 256; + // Constants used to parse out the ak name from the ak public data. Used in generateAkName private static final String AK_NAME_PREFIX = "000b"; + private static final String AK_NAME_HASH_PREFIX = "0001000b00050072000000100014000b0800000000000100"; - private static final SecureRandom random = new SecureRandom(); + + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); /** - * Helper method to parse a byte array into an {@link hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2.IdentityClaim}. + * This private constructor was created to silence one of checkstyle errors + */ + private ProvisionUtils() { + } + + /** + * Helper method to parse a byte array into an + * {@link hirs.attestationca.configuration.provisionerTpm2.ProvisionerTpm2.IdentityClaim}. * * @param identityClaim byte array that should be converted to a Protobuf IdentityClaim * object @@ -146,6 +179,9 @@ public final class ProvisionUtils { /** * Assembles a public key using a defined big int modulus and the well known exponent. + * + * @param modulus modulus + * @return public key using the provided integer modulus */ public static PublicKey assemblePublicKey(final BigInteger modulus) { // generate a key spec using mod and exp @@ -177,17 +213,14 @@ public final class ProvisionUtils { // create a cipher from the specified transformation Cipher cipher = Cipher.getInstance(scheme.toString()); - switch (scheme) { - case OAEP: - OAEPParameterSpec spec = - new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, - new PSource.PSpecified("".getBytes(StandardCharsets.UTF_8))); + if (scheme == EncryptionScheme.OAEP) { + OAEPParameterSpec spec = + new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, + new PSource.PSpecified("".getBytes(StandardCharsets.UTF_8))); - cipher.init(Cipher.PRIVATE_KEY, privateKey, spec); - break; - default: - // initialize the cipher to decrypt using the ACA private key. - cipher.init(Cipher.DECRYPT_MODE, privateKey); + cipher.init(Cipher.PRIVATE_KEY, privateKey, spec); + } else {// initialize the cipher to decrypt using the ACA private key. + cipher.init(Cipher.DECRYPT_MODE, privateKey); } cipher.update(asymmetricBlob); @@ -237,6 +270,11 @@ public final class ProvisionUtils { return new byte[0]; } + /** + * Generates a symmetric key. + * + * @return a symmetric key + */ public static SymmetricKey generateSymmetricKey() { // create a session key for the CA contents byte[] responseSymmetricKey = @@ -469,7 +507,15 @@ public final class ProvisionUtils { } } - @SuppressWarnings("magicnumber") + /** + * Assembles a credential blob. + * + * @param topSize byte array representation of the top size + * @param integrityHmac byte array representation of the integrity HMAC + * @param encryptedSecret byte array representation of the encrypted secret + * @param encryptedSeed byte array representation of the encrypted seed + * @return byte array representation of a credential blob + */ public static byte[] assembleCredential(final byte[] topSize, final byte[] integrityHmac, final byte[] encryptedSecret, final byte[] encryptedSeed) { @@ -533,7 +579,7 @@ public final class ProvisionUtils { * @throws NoSuchAlgorithmException Wrong crypto algorithm selected * @throws java.security.InvalidKeyException Invalid key used */ - @SuppressWarnings("magicnumber") + public static byte[] cryptKDFa(final byte[] seed, final String label, final byte[] context, final int sizeInBytes) throws NoSuchAlgorithmException, InvalidKeyException { @@ -581,6 +627,7 @@ public final class ProvisionUtils { * quote and the signature hash. * * @param tpmQuote contains hash values for the quote and the signature + * @return parsed TPM Quote hash */ public static String parseTPMQuoteHash(final String tpmQuote) { if (tpmQuote != null) { @@ -600,6 +647,7 @@ public final class ProvisionUtils { * quote and the signature hash. * * @param tpmQuote contains hash values for the quote and the signature + * @return parsed TPM Quote signature */ public static String parseTPMQuoteSignature(final String tpmQuote) { if (tpmQuote != null) { @@ -625,19 +673,29 @@ public final class ProvisionUtils { } /** - * Generates a array of random bytes. + * Generates an array of random bytes. * * @param numberOfBytes to be generated * @return byte array filled with the specified number of bytes. */ public static byte[] generateRandomBytes(final int numberOfBytes) { byte[] bytes = new byte[numberOfBytes]; - random.nextBytes(bytes); + SECURE_RANDOM.nextBytes(bytes); return bytes; } - @SuppressWarnings("magicnumber") + /** + * Calculates the difference in days between the two provided dates. + * + * @param date1 first provided date + * @param date2 second provided date + * @return difference in days between two dates + */ public static int daysBetween(final Date date1, final Date date2) { - return (int) ((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24)); + final int hoursInADay = 24; + final int secondsInAnHour = 3600; + final int millisecondsInASecond = 1000; + return (int) ((date2.getTime() - date1.getTime()) / + (millisecondsInASecond * secondsInAnHour * hoursInADay)); } } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/package-info.java new file mode 100644 index 00000000..52e582fe --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/helper/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.provision.helper; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/package-info.java new file mode 100644 index 00000000..d995e10f --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/provision/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.provision; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/ValidationService.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/ValidationService.java index 5ce06f6d..bf0661cb 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/ValidationService.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/ValidationService.java @@ -42,68 +42,93 @@ import java.util.UUID; @Log4j2 public class ValidationService { + /** + * Evaluates the provided endorsement credential status. + * + * @param endorsementCredential endorsement credential + * @param caCredentialRepository CA Credential repository + * @param acceptExpiredCerts whether to accept expired certificates + * @return a supply chain validation + */ public static SupplyChainValidation evaluateEndorsementCredentialStatus( - final EndorsementCredential ec, + final EndorsementCredential endorsementCredential, final CACredentialRepository caCredentialRepository, final boolean acceptExpiredCerts) { final SupplyChainValidation.ValidationType validationType = SupplyChainValidation.ValidationType.ENDORSEMENT_CREDENTIAL; log.info("Validating endorsement credential"); - if (ec == null) { + if (endorsementCredential == null) { log.error("No endorsement credential to validate"); return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, "Endorsement credential is missing", null, Level.ERROR); } - KeyStore ecStore = getCaChain(ec, caCredentialRepository); + KeyStore ecStore = getCaChain(endorsementCredential, caCredentialRepository); AppraisalStatus result = CredentialValidator. - validateEndorsementCredential(ec, ecStore, acceptExpiredCerts); - switch (result.getAppStatus()) { - case PASS: - return buildValidationRecord(validationType, AppraisalStatus.Status.PASS, - result.getMessage(), ec, Level.INFO); - case FAIL: - return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, - result.getMessage(), ec, Level.WARN); - case ERROR: - default: - return buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, - result.getMessage(), ec, Level.ERROR); - } + validateEndorsementCredential(endorsementCredential, ecStore, acceptExpiredCerts); + return switch (result.getAppStatus()) { + case PASS -> buildValidationRecord(validationType, AppraisalStatus.Status.PASS, + result.getMessage(), endorsementCredential, Level.INFO); + case FAIL -> buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, + result.getMessage(), endorsementCredential, Level.WARN); + default -> buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, + result.getMessage(), endorsementCredential, Level.ERROR); + }; } + /** + * Evaluates the provided platform credential status. + * + * @param platformCredential platform credential + * @param trustedCertificateAuthority trusted certificate authority + * @param acceptExpiredCerts whether to accept expired certificates + * @return a supply chain validation + */ public static SupplyChainValidation evaluatePlatformCredentialStatus( - final PlatformCredential pc, + final PlatformCredential platformCredential, final KeyStore trustedCertificateAuthority, final boolean acceptExpiredCerts) { final SupplyChainValidation.ValidationType validationType = SupplyChainValidation.ValidationType.PLATFORM_CREDENTIAL; - if (pc == null) { + if (platformCredential == null) { log.error("No platform credential to validate"); return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, "Empty Platform credential", null, Level.ERROR); } + log.info("Validating Platform Credential"); - AppraisalStatus result = CredentialValidator.validatePlatformCredential(pc, + + AppraisalStatus result = CredentialValidator.validatePlatformCredential(platformCredential, trustedCertificateAuthority, acceptExpiredCerts); - switch (result.getAppStatus()) { - case PASS: - return buildValidationRecord(validationType, AppraisalStatus.Status.PASS, - result.getMessage(), pc, Level.INFO); - case FAIL: - return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, - result.getMessage(), pc, Level.WARN); - case ERROR: - default: - return buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, - result.getMessage(), pc, Level.ERROR); - } + + return switch (result.getAppStatus()) { + case PASS -> buildValidationRecord(validationType, AppraisalStatus.Status.PASS, + result.getMessage(), platformCredential, Level.INFO); + case FAIL -> buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, + result.getMessage(), platformCredential, Level.WARN); + default -> buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, + result.getMessage(), platformCredential, Level.ERROR); + }; } + /** + * Evaluates PC Attributes status. + * + * @param platformCredential platform credential + * @param deviceInfoReport device information report + * @param endorsementCredential endorsement credential + * @param certificateRepository certificate repository + * @param componentResultRepository component result repository + * @param componentAttributeRepository component attribute repository + * @param componentInfos list of component information + * @param provisionSessionId uuid representation of the provision session id + * @param ignoreRevisionAttribute whether to ignore revision attribute + * @return a supply chain validation + */ public static SupplyChainValidation evaluatePCAttributesStatus( - final PlatformCredential pc, final DeviceInfoReport deviceInfoReport, - final EndorsementCredential ec, + final PlatformCredential platformCredential, final DeviceInfoReport deviceInfoReport, + final EndorsementCredential endorsementCredential, final CertificateRepository certificateRepository, final ComponentResultRepository componentResultRepository, final ComponentAttributeRepository componentAttributeRepository, @@ -112,36 +137,49 @@ public class ValidationService { final SupplyChainValidation.ValidationType validationType = SupplyChainValidation.ValidationType.PLATFORM_CREDENTIAL_ATTRIBUTES; - if (pc == null) { + if (platformCredential == null) { log.error("No platform credential to validate"); return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, "Platform credential is missing", null, Level.ERROR); } log.info("Validating platform credential attributes"); + AppraisalStatus result = CredentialValidator. - validatePlatformCredentialAttributes(pc, deviceInfoReport, ec, + validatePlatformCredentialAttributes(platformCredential, deviceInfoReport, + endorsementCredential, componentResultRepository, componentAttributeRepository, componentInfos, provisionSessionId, ignoreRevisionAttribute); - switch (result.getAppStatus()) { - case PASS: - return buildValidationRecord(validationType, AppraisalStatus.Status.PASS, - result.getMessage(), pc, Level.INFO); - case FAIL: + + return switch (result.getAppStatus()) { + case PASS -> buildValidationRecord(validationType, AppraisalStatus.Status.PASS, + result.getMessage(), platformCredential, Level.INFO); + case FAIL -> { if (!result.getAdditionalInfo().isEmpty()) { - pc.setComponentFailures(result.getAdditionalInfo()); - pc.setComponentFailureMessage(result.getMessage()); - certificateRepository.save(pc); + platformCredential.setComponentFailures(result.getAdditionalInfo()); + platformCredential.setComponentFailureMessage(result.getMessage()); + certificateRepository.save(platformCredential); } - return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, - result.getMessage(), pc, Level.WARN); - case ERROR: - default: - return buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, - result.getMessage(), pc, Level.ERROR); - } + yield buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, + result.getMessage(), platformCredential, Level.WARN); + } + default -> buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, + result.getMessage(), platformCredential, Level.ERROR); + }; } + /** + * @param deviceInfoReport + * @param base + * @param deltaMapping + * @param certificateRepository + * @param componentResultRepository + * @param componentAttributeRepository + * @param componentInfos + * @param provisionSessionId + * @param ignoreRevisionAttribute + * @return + */ public static SupplyChainValidation evaluateDeltaAttributesStatus( final DeviceInfoReport deviceInfoReport, final PlatformCredential base, @@ -160,11 +198,11 @@ public class ValidationService { base, deltaMapping, componentInfos, componentResultRepository, componentAttributeRepository, provisionSessionId, ignoreRevisionAttribute); - switch (result.getAppStatus()) { - case PASS: - return buildValidationRecord(validationType, AppraisalStatus.Status.PASS, - result.getMessage(), base, Level.INFO); - case FAIL: + + return switch (result.getAppStatus()) { + case PASS -> buildValidationRecord(validationType, AppraisalStatus.Status.PASS, + result.getMessage(), base, Level.INFO); + case FAIL -> { if (!result.getAdditionalInfo().isEmpty()) { base.setComponentFailures(result.getAdditionalInfo()); base.setComponentFailureMessage(result.getMessage()); @@ -172,15 +210,24 @@ public class ValidationService { } // we are adding things to componentFailures // certificateRepository.save(delta); - return buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, + yield buildValidationRecord(validationType, AppraisalStatus.Status.FAIL, result.getMessage(), base, Level.WARN); - case ERROR: - default: - return buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, - result.getMessage(), base, Level.ERROR); - } + // we are adding things to componentFailures +// certificateRepository.save(delta); + } + default -> buildValidationRecord(validationType, AppraisalStatus.Status.ERROR, + result.getMessage(), base, Level.ERROR); + }; } + /** + * @param device + * @param policySettings + * @param rimRepo + * @param rdvRepo + * @param caRepo + * @return + */ public static SupplyChainValidation evaluateFirmwareStatus( final Device device, final PolicySettings policySettings, final ReferenceManifestRepository rimRepo, @@ -206,17 +253,12 @@ public class ValidationService { } } - switch (result.getAppStatus()) { - case PASS: - logLevel = Level.INFO; - break; - case FAIL: - logLevel = Level.WARN; - break; - case ERROR: - default: - logLevel = Level.ERROR; - } + logLevel = switch (result.getAppStatus()) { + case PASS -> Level.INFO; + case FAIL -> Level.WARN; + default -> Level.ERROR; + }; + return buildValidationRecord(validationType, result.getAppStatus(), result.getMessage(), referenceManifest, logLevel); } diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/package-info.java new file mode 100644 index 00000000..0210df6c --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.service; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/CertificateSelector.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/CertificateSelector.java index a99d2dba..10ad8859 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/CertificateSelector.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/CertificateSelector.java @@ -6,6 +6,7 @@ import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; +import lombok.Getter; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.util.Arrays; @@ -71,6 +72,7 @@ import java.util.UUID; */ public abstract class CertificateSelector { + @Getter private final Class certificateClass; private final Map fieldValueSelections; @@ -350,6 +352,7 @@ public abstract class CertificateSelector { * Construct the criterion that can be used to query for certificates matching the configuration * of this {@link CertificateSelector}. * + * @param criteriaBuilder criteria builder * @return a Criterion that can be used to query for certificates matching the configuration of * this instance */ @@ -371,13 +374,6 @@ public abstract class CertificateSelector { return predicates; } - /** - * @return the certificate class that this instance will query - */ - public Class getCertificateClass() { - return certificateClass; - } - /** * Configures the selector to query for archived and unarchived certificates. * diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/package-info.java new file mode 100644 index 00000000..263ee908 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/service/selector/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.service.selector; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/package-info.java new file mode 100644 index 00000000..79899629 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/tpm/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.tpm; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/package-info.java new file mode 100644 index 00000000..8b7ae213 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/type/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.type; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/CredentialHelper.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/CredentialHelper.java index df4becff..bf336bbf 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/CredentialHelper.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/CredentialHelper.java @@ -64,7 +64,7 @@ public final class CredentialHelper { * @param certificateBytes raw byte form * @return a cleaned up byte form */ - @SuppressWarnings("magicnumber") + public static byte[] trimCertificate(final byte[] certificateBytes) { int certificateStart = 0; int certificateLength = 0; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/package-info.java new file mode 100644 index 00000000..736028a8 --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/util/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.util; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CertificateAttributeScvValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CertificateAttributeScvValidator.java index 060855ea..af9464ca 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CertificateAttributeScvValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CertificateAttributeScvValidator.java @@ -313,10 +313,15 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid * pick out the changes that lead to the delta cert and make sure the changes * are valid. * - * @param deviceInfoReport The paccor profile of device being validated against. - * @param deltaMapping map of delta certificates to their validated status - * @param origPcComponents The component identifier list associated with the - * base cert for this specific chain + * @param deviceInfoReport The paccor profile of device being validated against. + * @param deltaMapping map of delta certificates to their validated status + * @param origPcComponents The component identifier list associated with the + * base cert for this specific chain + * @param componentInfos list of component information + * @param componentResultRepository component result repository + * @param componentAttributeRepository component attribute repository + * @param provisionSessionId uuid representation of the provision session id + * @param ignoreRevisionAttribute whether to ignore the revision attribute * @return Appraisal Status of delta being validated. */ @@ -1022,11 +1027,13 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid } /** - * @param deltaCertificates - * @param componentResultRepository - * @param componentAttributeRepository - * @param provisionSessionId - * @return + * Compiles a list of delta component results. + * + * @param deltaCertificates delta certificates + * @param componentResultRepository component result repository + * @param componentAttributeRepository component attribute repository + * @param provisionSessionId uuid representation of the provision session id + * @return a list of delta component results */ private static List compileDeltaComponentResults( final List deltaCertificates, @@ -1044,7 +1051,7 @@ public class CertificateAttributeScvValidator extends SupplyChainCredentialValid // pull all component results that are not delta List dbBaseComponents = componentResultRepository .findByBoardSerialNumberAndDelta(deltaCertificates.get(0).getPlatformSerial(), false); - dbBaseComponents.stream().forEach((componentResult) -> { + dbBaseComponents.forEach((componentResult) -> { // ignore values that are not unique if (nonSerialValues.contains(componentResult.getSerialNumber())) { componentNonUniqueSerialMap.put(componentResult.hashCommonElements(), componentResult); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CredentialValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CredentialValidator.java index 14ac22bf..722f9b48 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CredentialValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/CredentialValidator.java @@ -228,13 +228,14 @@ public class CredentialValidator extends SupplyChainCredentialValidator { * @param deviceInfoReport The device info report containing * serial number of the platform to be validated. * @param basePlatformCredential the base credential from the same identity request - * * as the delta credential. + * as the delta credential. * @param deltaMapping delta certificates associated with the - * * delta supply validation. + * delta supply validation. * @param componentInfos list of device components * @param componentResultRepository repository for component results * @param componentAttributeRepository repository for the attribute status * @param provisionSessionId the session id to share + * @param ignoreRevisionAttribute whether to ignore the revision attribute * @return the result of the validation. */ public static AppraisalStatus validateDeltaPlatformCredentialAttributes( @@ -244,7 +245,8 @@ public class CredentialValidator extends SupplyChainCredentialValidator { final List componentInfos, final ComponentResultRepository componentResultRepository, final ComponentAttributeRepository componentAttributeRepository, - final UUID provisionSessionId, final boolean ignoreRevisionAttribute) { + final UUID provisionSessionId, + final boolean ignoreRevisionAttribute) { final String baseErrorMessage = "Can't validate platform credential attributes without "; String message; diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/FirmwareScvValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/FirmwareScvValidator.java index 9d922042..5cf9c635 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/FirmwareScvValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/FirmwareScvValidator.java @@ -40,14 +40,13 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { private static PcrValidator pcrValidator; /** - * @param device - * @param policySettings - * @param referenceManifestRepository - * @param referenceDigestValueRepository - * @param caCredentialRepository - * @return + * @param device device + * @param policySettings policy settings + * @param referenceManifestRepository reference manifest repository + * @param referenceDigestValueRepository reference digest value repository + * @param caCredentialRepository CA Credential repository + * @return an appraisal status */ - public static AppraisalStatus validateFirmware( final Device device, final PolicySettings policySettings, final ReferenceManifestRepository referenceManifestRepository, @@ -66,12 +65,13 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { //baseReferenceManifests = referenceManifestRepository.findAllBaseRims(); // This block was looking for a base RIM matching the device name - // The base rim might not have a device name associated with it- i.e. if it's uploaded to the ACA prior to provisioning - // In this case, try to look up the event log associated with the device, then get the base rim associated by event log hash + // The base rim might not have a device name associated with it- i.e. if it's uploaded to the ACA + // prior to provisioning In this case, try to look up the event log associated with the device, + // then get the base rim associated by event log hash List deviceRims = referenceManifestRepository.findByDeviceName(hostName); for (ReferenceManifest deviceRim : deviceRims) { - if (deviceRim instanceof BaseReferenceManifest && !deviceRim.isSwidSupplemental() && - !deviceRim.isSwidPatch()) { + if (deviceRim instanceof BaseReferenceManifest && !deviceRim.isSwidSupplemental() + && !deviceRim.isSwidPatch()) { baseReferenceManifest = (BaseReferenceManifest) deviceRim; } @@ -210,12 +210,8 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { try { logProcessor = new TCGEventLog(supportReferenceManifest.getRimBytes()); baseline = logProcessor.getExpectedPCRValues(); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } // part 1 of firmware validation check: PCR baseline match @@ -258,12 +254,8 @@ public class FirmwareScvValidator extends SupplyChainCredentialValidator { tpmPcrEvents.addAll(pcrValidator.validateTpmEvents( tcgMeasurementLog, eventValueMap, policySettings)); } - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException noSaEx) { - log.error(noSaEx); - } catch (IOException ioEx) { - log.error(ioEx); + } catch (CertificateException | NoSuchAlgorithmException | IOException exception) { + log.error(exception); } if (!tpmPcrEvents.isEmpty()) { diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/PcrValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/PcrValidator.java index 1ee17fca..f964007f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/PcrValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/PcrValidator.java @@ -66,6 +66,13 @@ public class PcrValidator { System.arraycopy(pcrValues, 0, baselinePcrs, 0, TPMMeasurementRecord.MAX_PCR_ID + 1); } + /** + * Builds a string array of stored pcrs. + * + * @param pcrContent string representation of the pcr content + * @param algorithmLength length of the algorithm + * @return string array representation of the stored pcrs. + */ public static String[] buildStoredPcrs(final String pcrContent, final int algorithmLength) { // we have a full set of PCR values String[] pcrSet = pcrContent.split("\\n"); @@ -142,7 +149,7 @@ public class PcrValidator { } if (!baselinePcrs[i].equals(storedPcrs[i])) { - log.error(String.format("%s =/= %s", baselinePcrs[i], storedPcrs[i])); + log.error("{} =/= {}", baselinePcrs[i], storedPcrs[i]); sb.append(String.format(failureMsg, i)); } } @@ -166,24 +173,24 @@ public class PcrValidator { List tpmPcrEvents = new LinkedList<>(); for (TpmPcrEvent tpe : tcgMeasurementLog.getEventList()) { if (policySettings.isIgnoreImaEnabled() && tpe.getPcrIndex() == IMA_PCR) { - log.info(String.format("IMA Ignored -> %s", tpe)); + log.info("IMA Ignored -> {}", tpe); } else if (policySettings.isIgnoretBootEnabled() && (tpe.getPcrIndex() >= TBOOT_PCR_START && tpe.getPcrIndex() <= TBOOT_PCR_END)) { - log.info(String.format("TBOOT Ignored -> %s", tpe)); + log.info("TBOOT Ignored -> {}", tpe); } else if (policySettings.isIgnoreOsEvtEnabled() && (tpe.getPcrIndex() >= PXE_PCR_START && tpe.getPcrIndex() <= PXE_PCR_END)) { - log.info(String.format("OS Evt Ignored -> %s", tpe)); + log.info("OS Evt Ignored -> {}", tpe); } else { if (policySettings.isIgnoreGptEnabled() && tpe.getEventTypeStr().contains(EVT_EFI_GPT)) { - log.info(String.format("GPT Ignored -> %s", tpe)); + log.info("GPT Ignored -> {}", tpe); } else if (policySettings.isIgnoreOsEvtEnabled() && ( tpe.getEventTypeStr().contains(EVT_EFI_BOOT) || tpe.getEventTypeStr().contains(EVT_EFI_VAR))) { - log.info(String.format("OS Evt Ignored -> %s", tpe)); + log.info("OS Evt Ignored -> {}", tpe); } else if (policySettings.isIgnoreOsEvtEnabled() && ( tpe.getEventTypeStr().contains(EVT_EFI_CFG) && tpe.getEventContentStr().contains("SecureBoot"))) { - log.info(String.format("OS Evt Config Ignored -> %s", tpe)); + log.info("OS Evt Config Ignored -> {}", tpe); } else { if (!eventValueMap.containsKey(tpe.getEventDigestStr())) { tpmPcrEvents.add(tpe); @@ -244,12 +251,13 @@ public class PcrValidator { // other information. String calculatedString = Hex.encodeHexString( pcrInfoShort.getCalculatedDigest()); - log.debug("Validating PCR information with the following:" + - System.lineSeparator() + "calculatedString = " + calculatedString + - System.lineSeparator() + "quoteString = " + quoteString); + log.debug( + "Validating PCR information with the following:{}calculatedString = {}{}" + + "quoteString = {}", System.lineSeparator(), calculatedString, + System.lineSeparator(), quoteString); validated = quoteString.contains(calculatedString); if (!validated) { - log.warn(calculatedString + " not found in " + quoteString); + log.warn("{} not found in {}", calculatedString, quoteString); } } catch (NoSuchAlgorithmException naEx) { log.error(naEx); diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidator.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidator.java index 749a34a8..d1567f7f 100644 --- a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidator.java +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/SupplyChainCredentialValidator.java @@ -39,7 +39,7 @@ import java.util.Set; public class SupplyChainCredentialValidator { /** - * used to identify and clear a nuc + * used to identify and clear a nuc. */ public static final int NUC_VARIABLE_BIT = 159; /** @@ -63,7 +63,7 @@ public class SupplyChainCredentialValidator { */ public static final String FIRMWARE_VALID = "Firmware validated"; - /** + /* * Ensure that BouncyCastle is configured as a javax.security.Security provider, as this * class expects it to be available. */ diff --git a/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/package-info.java b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/package-info.java new file mode 100644 index 00000000..27ae86db --- /dev/null +++ b/HIRS_AttestationCA/src/main/java/hirs/attestationca/persist/validation/package-info.java @@ -0,0 +1 @@ +package hirs.attestationca.persist.validation; diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerStateTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerStateTest.java index 6367720d..2c50cc70 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerStateTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/persist/entity/tpm/TPM2ProvisionerStateTest.java @@ -20,20 +20,21 @@ import static org.mockito.Mockito.when; */ public class TPM2ProvisionerStateTest { - private static final Random random = new Random(); + private static final Random RANDOM_GENERATOR = new Random(); /** * Tests that the values passed to the constructor are equal to the values * returned by the getters. - * - * @throws IOException this will never happen */ @Test - public final void testTPM2ProvisionerState() throws IOException { - byte[] nonce = new byte[32]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + public final void testTPM2ProvisionerState() { + final int nonceSize = 32; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); TPM2ProvisionerState state = new TPM2ProvisionerState(nonce, identityClaim); @@ -45,12 +46,14 @@ public class TPM2ProvisionerStateTest { * Test that the constructor throws an {@link IllegalArgumentException} when a null is * passed in for the nonce. * - * @throws IOException this will never happen + * @throws IllegalArgumentException this will never happen */ @Test - public final void testNullNonce() throws IOException { - byte[] identityClaim = new byte[360]; - random.nextBytes(identityClaim); + public final void testNullNonce() throws IllegalArgumentException { + final int identityClaimSize = 360; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(identityClaim); assertThrows(IllegalArgumentException.class, () -> new TPM2ProvisionerState(null, identityClaim)); } @@ -59,12 +62,15 @@ public class TPM2ProvisionerStateTest { * Test that the constructor throws an {@link IllegalArgumentException} when a null is * passed in for the identity claim. * - * @throws IOException this will never happen + * @throws IllegalArgumentException this will never happen */ @Test - public final void testNullIdentityClaim() throws IOException { - byte[] nonce = new byte[32]; - random.nextBytes(nonce); + public final void testNullIdentityClaim() throws IllegalArgumentException { + final int nonceSize = 32; + byte[] nonce = new byte[nonceSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + assertThrows(IllegalArgumentException.class, () -> new TPM2ProvisionerState(nonce, null)); } @@ -73,14 +79,17 @@ public class TPM2ProvisionerStateTest { * Test that the constructor throws an {@link IllegalArgumentException} when a nonce is * passed in that is less than 8 bytes. * - * @throws IOException this will never happen + * @throws IllegalArgumentException this will never happen */ @Test - public final void testNonceToSmall() throws IOException { - byte[] nonce = new byte[7]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + public final void testNonceToSmall() throws IllegalArgumentException { + final int nonceSize = 7; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); assertThrows(IllegalArgumentException.class, () -> new TPM2ProvisionerState(nonce, identityClaim)); } @@ -98,10 +107,13 @@ public class TPM2ProvisionerStateTest { public final void testGetTPM2ProvisionerStateNominal() throws IOException { TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository = mock(TPM2ProvisionerStateRepository.class); - byte[] nonce = new byte[32]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + final int nonceSize = 32; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(nonce)); Long index = dis.readLong(); @@ -125,10 +137,14 @@ public class TPM2ProvisionerStateTest { public final void testGetTPM2ProvisionerStateNullNonce() throws IOException { TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository = mock(TPM2ProvisionerStateRepository.class); - byte[] nonce = new byte[32]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + final int nonceSize = 32; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); + DataInputStream dis = new DataInputStream(new ByteArrayInputStream(nonce)); Long index = dis.readLong(); dis.close(); @@ -149,10 +165,14 @@ public class TPM2ProvisionerStateTest { public final void testGetTPM2ProvisionerStateNonceTooSmall() throws IOException { TPM2ProvisionerStateRepository tpm2ProvisionerStateRepository = mock(TPM2ProvisionerStateRepository.class); - byte[] nonce = new byte[32]; - byte[] identityClaim = new byte[360]; - random.nextBytes(nonce); - random.nextBytes(identityClaim); + final int nonceSize = 32; + final int identityClaimSize = 360; + byte[] nonce = new byte[nonceSize]; + byte[] identityClaim = new byte[identityClaimSize]; + + RANDOM_GENERATOR.nextBytes(nonce); + RANDOM_GENERATOR.nextBytes(identityClaim); + DataInputStream dis = new DataInputStream(new ByteArrayInputStream(nonce)); Long index = dis.readLong(); dis.close(); diff --git a/HIRS_AttestationCAPortal/build.gradle b/HIRS_AttestationCAPortal/build.gradle index f18edb21..cd03df12 100644 --- a/HIRS_AttestationCAPortal/build.gradle +++ b/HIRS_AttestationCAPortal/build.gradle @@ -21,9 +21,9 @@ java { } bootRun { - if (project.hasProperty('debug')) { - jvmArgs project.debug - } + if (project.hasProperty('debug')) { + jvmArgs project.debug + } } configurations { @@ -80,10 +80,10 @@ configurations.checkstyle { } } checkstyleMain { - source ='src/main/java' + source = 'src/main/java' } checkstyleTest { - source ='src/test/java' + source = 'src/test/java' } tasks.withType(Checkstyle) { reports { @@ -110,36 +110,36 @@ ospackage { arch = NOARCH version = "$packVersion" release = '2' - - + + user 'root' fileMode = 0755 addParentDirs = true - createDirectoryEntry true + createDirectoryEntry true - into ('/etc/hirs') { - from '../VERSION' - } + into('/etc/hirs') { + from '../VERSION' + } // copy json tables - into ('/etc/hirs/aca/default-properties') { - from '../HIRS_AttestationCA/src/main/resources/component-class.json' - from '../HIRS_Utils/src/main/resources/vendor-table.json' + into('/etc/hirs/aca/default-properties') { + from '../HIRS_AttestationCA/src/main/resources/component-class.json' + from '../HIRS_Utils/src/main/resources/vendor-table.json' } // copy springboot property file - into ('/etc/hirs/aca/') { - from '../HIRS_AttestationCAPortal/src/main/resources/application.properties' - from 'build/VERSION' + into('/etc/hirs/aca/') { + from '../HIRS_AttestationCAPortal/src/main/resources/application.properties' + from 'build/VERSION' } // copy setup scripts to /opt/hirs/aca - into ('/opt/hirs/aca/scripts/') { - from '../package/linux/' + into('/opt/hirs/aca/scripts/') { + from '../package/linux/' } // copy the war file into /opt/hirs/aca - into ('/opt/hirs/aca/') { - from '../HIRS_AttestationCAPortal/build/libs/HIRS_AttestationCAPortal.war' - user 'root' - fileMode = 0755 + into('/opt/hirs/aca/') { + from '../HIRS_AttestationCAPortal/build/libs/HIRS_AttestationCAPortal.war' + user 'root' + fileMode = 0755 } // Install - check for existing setup @@ -152,12 +152,12 @@ ospackage { postUninstall 'if [ -d /opt/hirs ]; then rm -rf /opt/hirs; fi;' buildRpm { - dependsOn ':HIRS_AttestationCAPortal:buildVersion' - dependsOn ':HIRS_AttestationCAPortal:bootWar' + dependsOn ':HIRS_AttestationCAPortal:buildVersion' + dependsOn ':HIRS_AttestationCAPortal:bootWar' arch = X86_64 // Required apps will be aut installed by dnf if not present requires('java-17-openjdk', '17.0', GREATER | EQUAL) - requires('mariadb-server' , '10.3' , GREATER | EQUAL) + requires('mariadb-server', '10.3', GREATER | EQUAL) requires('procps-ng', '3.3.15', GREATER | EQUAL) requires('alternatives', '1.19', GREATER | EQUAL) // Post Trans stage (Occurs after required app and postInstall stage) @@ -174,12 +174,12 @@ ospackage { } buildDeb { - dependsOn ':HIRS_AttestationCAPortal:buildVersion' - dependsOn ':HIRS_AttestationCAPortal:bootWar' + dependsOn ':HIRS_AttestationCAPortal:buildVersion' + dependsOn ':HIRS_AttestationCAPortal:bootWar' packageName = 'hirs-attestationca' arch = 'amd64' requires('openjdk-17-jdk', '17.0', GREATER | EQUAL) - requires('mariadb-server' , '10.3' , GREATER | EQUAL) + requires('mariadb-server', '10.3', GREATER | EQUAL) requires('curl') // Install after required packages postInstall 'bash /opt/hirs/aca/scripts/aca/aca_setup.sh -u' diff --git a/HIRS_AttestationCAPortal/config/spotbugs/spotbugs-exclude.xml b/HIRS_AttestationCAPortal/config/spotbugs/spotbugs-exclude.xml index a78c5f3d..9460d1e7 100644 --- a/HIRS_AttestationCAPortal/config/spotbugs/spotbugs-exclude.xml +++ b/HIRS_AttestationCAPortal/config/spotbugs/spotbugs-exclude.xml @@ -2,11 +2,11 @@ - + - + diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSApplication.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSApplication.java index 1207576f..bbb35040 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSApplication.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSApplication.java @@ -1,18 +1,8 @@ package hirs.attestationca.portal; -import jakarta.servlet.ServletContext; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRegistration; import lombok.extern.log4j.Log4j2; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import java.util.Collections; @SpringBootApplication //@EnableAutoConfiguration diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSDbInitializer.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSDbInitializer.java index c42b7dfa..ebd34350 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSDbInitializer.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/HIRSDbInitializer.java @@ -11,7 +11,8 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche @Log4j2 @WebListener -public class HIRSDbInitializer extends AbstractAnnotationConfigDispatcherServletInitializer implements ServletContextListener { +public class HIRSDbInitializer extends AbstractAnnotationConfigDispatcherServletInitializer + implements ServletContextListener { @Override public void contextInitialized(final ServletContextEvent servletContextEvent) { @@ -21,11 +22,12 @@ public class HIRSDbInitializer extends AbstractAnnotationConfigDispatcherServlet // applicationContext.register(PersistenceConfiguration.class); try { - applicationContext.refresh(); + applicationContext.refresh(); } catch (NoSuchBeanDefinitionException nsbdEx) { if (log.isDebugEnabled()) { - log.debug("Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided"); + log.debug( + "Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided"); } } catch (Exception ex) { log.error(ex.getMessage()); @@ -33,14 +35,14 @@ public class HIRSDbInitializer extends AbstractAnnotationConfigDispatcherServlet } @Override - protected Class [] getRootConfigClasses() { + protected Class[] getRootConfigClasses() { return new Class[] { PersistenceJPAConfig.class, PageConfiguration.class, PersistenceConfiguration.class }; } @Override - protected Class [] getServletConfigClasses() { + protected Class[] getServletConfigClasses() { return null; } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/PersistenceJPAConfig.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/PersistenceJPAConfig.java index f969f751..dae778b7 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/PersistenceJPAConfig.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/PersistenceJPAConfig.java @@ -56,10 +56,12 @@ import java.util.Properties; ignoreResourceNotFound = true), @PropertySource(value = "file:/etc/hirs/aca/application.properties", ignoreResourceNotFound = true), - @PropertySource(value = "file:C:/ProgramData/hirs/aca/application.win.properties", + @PropertySource(value = "file:C:/ProgramData/hirs/aca/application.win.properties", ignoreResourceNotFound = true) }) -@ComponentScan({"hirs.attestationca.portal", "hirs.attestationca.portal.page.controllers", "hirs.attestationca.persist", "hirs.attestationca.persist.entity", "hirs.attestationca.persist.service"}) +@ComponentScan({"hirs.attestationca.portal", "hirs.attestationca.portal.page.controllers", + "hirs.attestationca.persist", "hirs.attestationca.persist.entity", + "hirs.attestationca.persist.service"}) @EnableJpaRepositories(basePackages = "hirs.attestationca.persist.entity.manager") public class PersistenceJPAConfig implements WebMvcConfigurer { @@ -80,7 +82,8 @@ public class PersistenceJPAConfig implements WebMvcConfigurer { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean entityManagerBean = new LocalContainerEntityManagerFactoryBean(); + final LocalContainerEntityManagerFactoryBean entityManagerBean = + new LocalContainerEntityManagerFactoryBean(); entityManagerBean.setDataSource(dataSource()); entityManagerBean.setPackagesToScan("hirs.attestationca.persist.entity"); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableInput.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableInput.java index ee6256c7..9c176eea 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableInput.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableInput.java @@ -22,14 +22,66 @@ import java.util.Map; public class DataTableInput { private static final int DEFAULT_LENGTH = 10; + /** + * Draw counter. This is used by DataTables to ensure that the Ajax returns from server-side + * processing requests are drawn in sequence by DataTables (Ajax requests are asynchronous and + * thus can return out of sequence). This is used as part of the draw return parameter (see + * below). + */ + @NotNull + @Min(0) + @Getter + @Setter + private int draw = 1; + /** + * Paging first record indicator. This is the start point in the current data set + * (0 index based - i.e. 0 is the first record). + */ + @NotNull + @Min(0) + @Getter + @Setter + private int start = 0; + /** + * Number of records that the table can display in the current draw. It is expected that the + * number of records returned will be equal to this number, + * unless the server has fewer records to return. Note that this can be -1 to indicate that + * all records should be returned (although that + * negates any benefits of server-side processing!) + */ + @NotNull + @Min(-1) + @Getter + @Setter + private int length = DEFAULT_LENGTH; + /** + * Global search parameter. + */ + @Getter + @Setter + @NotNull + private Search search = new Search(); + /** + * Order parameter. + */ + @Getter + @NotEmpty + private List order = new ArrayList<>(); + /** + * Per-column search parameter. + */ + @Getter + @NotEmpty + private List columns = new ArrayList<>(); /** * Constructor. - * @param draw the draw counter - * @param start the paging start indicator - * @param length the number of records in current draw - * @param search the search parameter - * @param order the orderings + * + * @param draw the draw counter + * @param start the paging start indicator + * @param length the number of records in current draw + * @param search the search parameter + * @param order the orderings * @param columns the columns of the input */ public DataTableInput(final Integer draw, final Integer start, final Integer length, @@ -43,65 +95,9 @@ public class DataTableInput { this.columns.addAll(columns); } - /** - * Draw counter. This is used by DataTables to ensure that the Ajax returns from server-side - * processing requests are drawn in sequence by DataTables (Ajax requests are asynchronous and - * thus can return out of sequence). This is used as part of the draw return parameter (see - * below). - */ - @NotNull - @Min(0) - @Getter - @Setter - private int draw = 1; - - /** - * Paging first record indicator. This is the start point in the current data set - * (0 index based - i.e. 0 is the first record). - */ - @NotNull - @Min(0) - @Getter - @Setter - private int start = 0; - - /** - * Number of records that the table can display in the current draw. It is expected that the - * number of records returned will be equal to this number, - * unless the server has fewer records to return. Note that this can be -1 to indicate that - * all records should be returned (although that - * negates any benefits of server-side processing!) - */ - @NotNull - @Min(-1) - @Getter - @Setter - private int length = DEFAULT_LENGTH; - - /** - * Global search parameter. - */ - @Getter - @Setter - @NotNull - private Search search = new Search(); - - /** - * Order parameter. - */ - @Getter - @NotEmpty - private List order = new ArrayList<>(); - - /** - * Per-column search parameter. - */ - @Getter - @NotEmpty - private List columns = new ArrayList<>(); - /** * Sets the orders. + * * @param order the orders */ public void setOrder(final List order) { @@ -111,6 +107,7 @@ public class DataTableInput { /** * Sets the table columns. + * * @param columns the columns */ public void setColumns(final List columns) { @@ -119,7 +116,6 @@ public class DataTableInput { } /** - * * @return a {@link Map} of {@link Column} indexed by name */ public Map getColumnsAsMap() { @@ -151,9 +147,9 @@ public class DataTableInput { /** * Add a new column. * - * @param columnName the name of the column - * @param searchable whether the column is searchable or not - * @param orderable whether the column is orderable or not + * @param columnName the name of the column + * @param searchable whether the column is searchable or not + * @param orderable whether the column is orderable or not * @param searchValue if any, the search value to apply */ public void addColumn(final String columnName, final boolean searchable, @@ -166,7 +162,7 @@ public class DataTableInput { * Add an order on the given column. * * @param columnName the name of the column - * @param ascending whether the sorting is ascending or descending + * @param ascending whether the sorting is ascending or descending */ public void addOrder(final String columnName, final boolean ascending) { if (columnName == null) { @@ -182,6 +178,7 @@ public class DataTableInput { /** * Gets the order column name, given the order ordinal value. + * * @return the order column name */ public String getOrderColumnName() { @@ -207,6 +204,7 @@ public class DataTableInput { /** * Generates a string for this object. + * * @return the string */ @Override diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java index d366ea37..f931d817 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableResponse.java @@ -20,9 +20,11 @@ import java.util.List; public final class DataTableResponse { private List data = new LinkedList(); - @Getter @Setter + @Getter + @Setter private int draw; - @Getter @Setter + @Getter + @Setter private long recordsTotal, recordsFiltered; /** diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableView.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableView.java index 034fc819..d21b5231 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableView.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/DataTableView.java @@ -2,21 +2,22 @@ package hirs.attestationca.portal.datatables; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import java.util.Map; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.MediaType; import org.springframework.web.servlet.view.AbstractUrlBasedView; +import java.util.Map; + /** * Serializes the DataTableResponse from the view as JSON and writes it to the HTTP response. - * */ public class DataTableView extends AbstractUrlBasedView { private static final Gson GSON = new GsonBuilder().create(); private static final String MODEL_FIELD; + static { final String name = DataTableResponse.class.getSimpleName(); MODEL_FIELD = name.substring(0, 1).toLowerCase() + name.substring(1); @@ -25,9 +26,9 @@ public class DataTableView extends AbstractUrlBasedView { /** * Serializes the DataTableResponse from the view as JSON and writes it to the HTTP response. * - * @param model combined output Map (never {@code null}), with dynamic values taking precedence - * over static attributes - * @param request current HTTP request + * @param model combined output Map (never {@code null}), with dynamic values taking precedence + * over static attributes + * @param request current HTTP request * @param response current HTTP response * @throws Exception if rendering failed */ diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Order.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Order.java index 80ecd80b..4b0a66fe 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Order.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Order.java @@ -19,9 +19,25 @@ import lombok.Setter; public class Order { + /** + * Column to which ordering should be applied. This is an index reference + * to the columns array of information that is also submitted to the server. + */ + @NotNull + @Min(0) + private int column; + /** + * Ordering direction for this column. It will be asc or desc to indicate ascending ordering or + * descending ordering, respectively. + */ + @NotNull + @Pattern(regexp = "(desc|asc)") + private String dir; + /** * Constructor. - * @param column the column index + * + * @param column the column index * @param isAscending true if ascending order */ public Order(final int column, final boolean isAscending) { @@ -33,25 +49,7 @@ public class Order { } } - /** - * Column to which ordering should be applied. This is an index reference - * to the columns array of information that is also submitted to the server. - */ - @NotNull - @Min(0) - private int column; - - /** - * Ordering direction for this column. It will be asc or desc to indicate ascending ordering or - * descending ordering, respectively. - */ - @NotNull - @Pattern(regexp = "(desc|asc)") - private String dir; - - /** - * * @return true if ascending order, false otherwise. */ public boolean isAscending() { diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/OrderedListQueryDataTableAdapter.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/OrderedListQueryDataTableAdapter.java index 518fa12b..dc2fec31 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/OrderedListQueryDataTableAdapter.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/OrderedListQueryDataTableAdapter.java @@ -20,6 +20,7 @@ import java.util.UUID; /** * A class to adapt the Javascript DataTable java class abstractions to the DBManager's getting * of ordered lists. + * * @param The type of object to query */ @NoArgsConstructor(access = AccessLevel.PRIVATE) @@ -28,11 +29,12 @@ public final class OrderedListQueryDataTableAdapter { /** * Gets the ordered list of records using a default, no-op criteria modifier. - * @param clazz the type of objects to query for - * @param dbManager the db manager to execute the actual query - * @param dataTableInput the JS DataTable query abstraction + * + * @param clazz the type of objects to query for + * @param dbManager the db manager to execute the actual query + * @param dataTableInput the JS DataTable query abstraction * @param orderColumnName the name of the column (java object field name) to query on - * @param the parameter type + * @param the parameter type * @return the filtered record list */ public static FilteredRecordsList getOrderedList(final Class clazz, @@ -51,12 +53,13 @@ public final class OrderedListQueryDataTableAdapter { /** * Gets the ordered list of records. - * @param clazz the type of objects to query for - * @param dbManager the db manager to execute the actual query - * @param dataTableInput the JS DataTable query abstraction - * @param orderColumnName the name of the column (java object field name) to query on + * + * @param clazz the type of objects to query for + * @param dbManager the db manager to execute the actual query + * @param dataTableInput the JS DataTable query abstraction + * @param orderColumnName the name of the column (java object field name) to query on * @param criteriaModifier the criteria modifier - * @param the parameter type + * @param the parameter type * @return the filtered record list */ public static FilteredRecordsList getOrderedList(final Class clazz, @@ -92,11 +95,12 @@ public final class OrderedListQueryDataTableAdapter { // searchableColumnMap, criteriaModifier); } - public static FilteredRecordsList getOrderedList(final JpaRepository dbManager, - final DataTableInput dataTableInput, - final String orderColumnName, - final CriteriaModifier criteriaModifier, - final EntityManager entityManager) { + public static FilteredRecordsList getOrderedList( + final JpaRepository dbManager, + final DataTableInput dataTableInput, + final String orderColumnName, + final CriteriaModifier criteriaModifier, + final EntityManager entityManager) { Map searchableColumnMap = new HashMap<>(); for (Column column : dataTableInput.getColumns()) { @@ -121,7 +125,6 @@ public final class OrderedListQueryDataTableAdapter { FilteredRecordsList filteredRecordsList = new FilteredRecordsList<>(); - filteredRecordsList.setRecordsTotal(dbManager.count()); filteredRecordsList.addAll(dbManager.findAll()); filteredRecordsList.setRecordsFiltered(10); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Search.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Search.java index c8d206d5..f6130bc7 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Search.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/Search.java @@ -16,20 +16,11 @@ import lombok.Setter; @NoArgsConstructor(access = AccessLevel.PUBLIC) public class Search { - /** - * Constructor for a non-regex search. - * @param value the search value - */ - public Search(final String value) { - this(value, false); - } - /** * Global search value. To be applied to all columns which have searchable as true. */ @NotNull private String value = ""; - /** * true if the global filter should be treated as a regular expression for advanced searching, * false otherwise. Note that normally server-side processing scripts will not perform regular @@ -39,6 +30,15 @@ public class Search { @NotNull private boolean regex; + /** + * Constructor for a non-regex search. + * + * @param value the search value + */ + public Search(final String value) { + this(value, false); + } + @Override public String toString() { return "Search{" diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/Page.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/Page.java index eb39cf5e..49fbf333 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/Page.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/Page.java @@ -86,13 +86,13 @@ public enum Page { /** * Constructor for Page. * - * @param title title of the page - * @param subtitle subtitle of the page - * @param icon icon for the page - * @param hasMenu the page has its own menu - * @param inMenu the page appears in a menu + * @param title title of the page + * @param subtitle subtitle of the page + * @param icon icon for the page + * @param hasMenu the page has its own menu + * @param inMenu the page appears in a menu * @param menuLinkClass the category to which this page belongs - * @param prefixPath prefix path that appears in the URL for this page + * @param prefixPath prefix path that appears in the URL for this page */ Page(final String title, final String subtitle, @@ -115,10 +115,10 @@ public enum Page { /** * Constructor for Page. * - * @param title title of the page - * @param icon icon for the page + * @param title title of the page + * @param icon icon for the page * @param menuLinkClass the category to which this page belongs - * @param prefixPath prefix path that appears in the URL for this page + * @param prefixPath prefix path that appears in the URL for this page */ Page(final String title, final String icon, @@ -130,8 +130,8 @@ public enum Page { /** * Constructor for Page. * - * @param title title of the page - * @param icon icon for the page + * @param title title of the page + * @param icon icon for the page * @param menuLinkClass the category to which this page belongs */ Page(final String title, @@ -144,7 +144,7 @@ public enum Page { * Constructor for Page. * * @param title title of the page - * @param icon icon for the page + * @param icon icon for the page */ Page(final String title, final String icon) { diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageController.java index 13cf7455..e4a60827 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/PageController.java @@ -61,8 +61,8 @@ public abstract class PageController

{ * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @RequestMapping @@ -110,8 +110,8 @@ public abstract class PageController

{ * Redirects back to this controller's page with the specified data. * * @param params The url parameters to pass to the page. - * @param model The model data to pass to the page. - * @param attr The request's RedirectAttributes to hold the model data. + * @param model The model data to pass to the page. + * @param attr The request's RedirectAttributes to hold the model data. * @return RedirectView back to the page with the specified parameters. * @throws URISyntaxException if malformed URI */ @@ -127,9 +127,9 @@ public abstract class PageController

{ * Redirects controller's page with the specified data. * * @param newPage new page to get the model and view - * @param params The url parameters to pass to the page. - * @param model The model data to pass to the page. - * @param attr The request's RedirectAttributes to hold the model data. + * @param params The url parameters to pass to the page. + * @param model The model data to pass to the page. + * @param attr The request's RedirectAttributes to hold the model data. * @return RedirectView back to the page with the specified parameters. * @throws URISyntaxException if malformed URI */ diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageController.java index eef67603..0853d7df 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/CertificateDetailsPageController.java @@ -39,9 +39,10 @@ public class CertificateDetailsPageController extends PageController { - @Autowired(required = false) - private EntityManager entityManager; - - private CertificateAuthorityCredential certificateAuthorityCredential; + /** + * Model attribute name used by initPage for the aca cert info. + */ + static final String ACA_CERT_DATA = "acaCertData"; + private static final String TRUSTCHAIN = "trust-chain"; + private static final String PLATFORMCREDENTIAL = "platform-credentials"; + private static final String IDEVIDCERTIFICATE = "idevid-certificates"; + private static final String ENDORSEMENTCREDENTIAL = "endorsement-key-credentials"; + private static final String ISSUEDCERTIFICATES = "issued-certificates"; private final CertificateRepository certificateRepository; private final PlatformCertificateRepository platformCertificateRepository; private final ComponentResultRepository componentResultRepository; @@ -92,17 +97,9 @@ public class CertificatePageController extends PageController { private final IssuedCertificateRepository issuedCertificateRepository; private final CACredentialRepository caCredentialRepository; private final IDevIDCertificateRepository iDevIDCertificateRepository; - - private static final String TRUSTCHAIN = "trust-chain"; - private static final String PLATFORMCREDENTIAL = "platform-credentials"; - private static final String IDEVIDCERTIFICATE = "idevid-certificates"; - private static final String ENDORSEMENTCREDENTIAL = "endorsement-key-credentials"; - private static final String ISSUEDCERTIFICATES = "issued-certificates"; - - /** - * Model attribute name used by initPage for the aca cert info. - */ - static final String ACA_CERT_DATA = "acaCertData"; + @Autowired(required = false) + private EntityManager entityManager; + private CertificateAuthorityCredential certificateAuthorityCredential; /** * Constructor providing the Page's display and routing specification. @@ -113,7 +110,8 @@ public class CertificatePageController extends PageController { * @param endorsementCredentialRepository the endorsement credential manager * @param issuedCertificateRepository the issued certificate manager * @param caCredentialRepository the ca credential manager - * @param acaCertificate the ACA's X509 certificate */ + * @param acaCertificate the ACA's X509 certificate + */ @Autowired public CertificatePageController(final CertificateRepository certificateRepository, final PlatformCertificateRepository platformCertificateRepository, @@ -142,12 +140,53 @@ public class CertificatePageController extends PageController { } } + /** + * Get the page based on the certificate type. + * + * @param certificateType String containing the certificate type + * @return the page for the certificate type. + */ + private static Page getCertificatePage(final String certificateType) { + // get page information (default to TRUST_CHAIN) + return switch (certificateType) { + case PLATFORMCREDENTIAL -> Page.PLATFORM_CREDENTIALS; + case ENDORSEMENTCREDENTIAL -> Page.ENDORSEMENT_KEY_CREDENTIALS; + case ISSUEDCERTIFICATES -> Page.ISSUED_CERTIFICATES; + case IDEVIDCERTIFICATE -> Page.IDEVID_CERTIFICATES; + default -> Page.TRUST_CHAIN; + }; + } + + /** + * Gets the concrete certificate class type to query for. + * + * @param certificateType String containing the certificate type + * @return the certificate class type + */ + private static Class getCertificateClass(final String certificateType) { + switch (certificateType) { + case PLATFORMCREDENTIAL: + return PlatformCredential.class; + case ENDORSEMENTCREDENTIAL: + return EndorsementCredential.class; + case ISSUEDCERTIFICATES: + return IssuedAttestationCertificate.class; + case IDEVIDCERTIFICATE: + return IDevIDCertificate.class; + case TRUSTCHAIN: + return CertificateAuthorityCredential.class; + default: + throw new IllegalArgumentException( + String.format("Unknown certificate type: %s", certificateType)); + } + } + /** * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @Override @@ -160,9 +199,9 @@ public class CertificatePageController extends PageController { * Returns the path for the view and the data model for the page. * * @param certificateType String containing the certificate type - * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param params The object to map url parameters into. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @RequestMapping("/{certificateType}") @@ -189,7 +228,8 @@ public class CertificatePageController extends PageController { mav = getBaseModelAndView(Page.TRUST_CHAIN); // Map with the ACA certificate information data.putAll(CertificateStringMapBuilder.getCertificateAuthorityInformation( - certificateAuthorityCredential, this.certificateRepository, this.caCredentialRepository)); + certificateAuthorityCredential, this.certificateRepository, + this.caCredentialRepository)); mav.addObject(ACA_CERT_DATA, data); break; default: @@ -200,13 +240,12 @@ public class CertificatePageController extends PageController { return mav; } - /** * Queries for the list of Certificates and returns a data table response * with the records. * * @param certificateType String containing the certificate type - * @param input the DataTables search/query parameters + * @param input the DataTables search/query parameters * @return the data table */ @ResponseBody @@ -229,7 +268,8 @@ public class CertificatePageController extends PageController { Session session = entityManager.unwrap(Session.class); CriteriaBuilder cb = session.getCriteriaBuilder(); Root rimRoot = criteriaQuery.from(Reference.class); - criteriaQuery.select(rimRoot).distinct(true).where(cb.isNull(rimRoot.get(Certificate.ARCHIVE_FIELD))); + criteriaQuery.select(rimRoot).distinct(true) + .where(cb.isNull(rimRoot.get(Certificate.ARCHIVE_FIELD))); // add a device alias if this query includes the device table // for getting the device (e.g. device name). @@ -249,7 +289,8 @@ public class CertificatePageController extends PageController { // serial number. (pc.HolderSerialNumber = ec.SerialNumber) if (certificateType.equals(PLATFORMCREDENTIAL)) { FilteredRecordsList records = new FilteredRecordsList<>(); - org.springframework.data.domain.Page pagedResult = this.platformCertificateRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + this.platformCertificateRepository.findByArchiveFlag(false, paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -282,7 +323,8 @@ public class CertificatePageController extends PageController { return new DataTableResponse<>(records, input); } else if (certificateType.equals(ENDORSEMENTCREDENTIAL)) { FilteredRecordsList records = new FilteredRecordsList<>(); - org.springframework.data.domain.Page pagedResult = this.endorsementCredentialRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + this.endorsementCredentialRepository.findByArchiveFlag(false, paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -297,7 +339,8 @@ public class CertificatePageController extends PageController { return new DataTableResponse<>(records, input); } else if (certificateType.equals(TRUSTCHAIN)) { FilteredRecordsList records = new FilteredRecordsList<>(); - org.springframework.data.domain.Page pagedResult = this.caCredentialRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + this.caCredentialRepository.findByArchiveFlag(false, paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -312,7 +355,8 @@ public class CertificatePageController extends PageController { return new DataTableResponse<>(records, input); } else if (certificateType.equals(ISSUEDCERTIFICATES)) { FilteredRecordsList records = new FilteredRecordsList<>(); - org.springframework.data.domain.Page pagedResult = this.issuedCertificateRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + this.issuedCertificateRepository.findByArchiveFlag(false, paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -325,8 +369,7 @@ public class CertificatePageController extends PageController { log.debug("Returning list of size: " + records.size()); return new DataTableResponse<>(records, input); - } - else if (certificateType.equals(IDEVIDCERTIFICATE)) { + } else if (certificateType.equals(IDEVIDCERTIFICATE)) { FilteredRecordsList records = new FilteredRecordsList(); org.springframework.data.domain.Page pagedResult = this.iDevIDCertificateRepository.findByArchiveFlag(false, paging); @@ -351,8 +394,8 @@ public class CertificatePageController extends PageController { * Upload and processes a credential. * * @param certificateType String containing the certificate type - * @param files the files to process - * @param attr the redirection attributes + * @param files the files to process + * @param attr the redirection attributes * @return the redirection view * @throws URISyntaxException if malformed URI */ @@ -388,9 +431,9 @@ public class CertificatePageController extends PageController { * Archives (soft delete) the credential. * * @param certificateType String containing the certificate type - * @param id the UUID of the cert to delete - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param id the UUID of the cert to delete + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return redirect to this page * @throws URISyntaxException if malformed URI */ @@ -459,9 +502,9 @@ public class CertificatePageController extends PageController { * for download. * * @param certificateType String containing the certificate type - * @param id the UUID of the cert to download - * @param response the response object (needed to update the header with the - * file name) + * @param id the UUID of the cert to download + * @param response the response object (needed to update the header with the + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/{certificateType}/download", method = RequestMethod.GET) @@ -508,8 +551,7 @@ public class CertificatePageController extends PageController { * stream for download. * * @param response the response object (needed to update the header with the - * file name) - * + * file name) * @throws java.io.IOException when writing to response output stream */ @ResponseBody @@ -530,7 +572,7 @@ public class CertificatePageController extends PageController { * for download in bulk. * * @param response the response object (needed to update the header with the - * file name) + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/trust-chain/bulk", method = RequestMethod.GET) @@ -546,7 +588,8 @@ public class CertificatePageController extends PageController { try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) { // get all files - bulkDownload(zipOut, this.certificateRepository.findByType("CertificateAuthorityCredential"), singleFileName); + bulkDownload(zipOut, this.certificateRepository.findByType("CertificateAuthorityCredential"), + singleFileName); // write cert to output stream } catch (IllegalArgumentException ex) { String uuidError = "Failed to parse ID from: "; @@ -561,7 +604,7 @@ public class CertificatePageController extends PageController { * for download in bulk. * * @param response the response object (needed to update the header with the - * file name) + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/platform-credentials/bulk", method = RequestMethod.GET) @@ -593,7 +636,7 @@ public class CertificatePageController extends PageController { * for download in bulk. * * @param response the response object (needed to update the header with the - * file name) + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/issued-certificates/bulk", method = RequestMethod.GET) @@ -610,7 +653,8 @@ public class CertificatePageController extends PageController { try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) { // get all files - bulkDownload(zipOut, this.certificateRepository.findByType("IssuedAttestationCertificate"), singleFileName); + bulkDownload(zipOut, this.certificateRepository.findByType("IssuedAttestationCertificate"), + singleFileName); // write cert to output stream } catch (IllegalArgumentException ex) { String uuidError = "Failed to parse ID from: "; @@ -625,7 +669,7 @@ public class CertificatePageController extends PageController { * for download in bulk. * * @param response the response object (needed to update the header with the - * file name) + * file name) * @throws java.io.IOException when writing to response output stream */ @RequestMapping(value = "/endorsement-key-credentials/bulk", method = RequestMethod.GET) @@ -641,7 +685,8 @@ public class CertificatePageController extends PageController { try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) { // get all files - bulkDownload(zipOut, this.certificateRepository.findByType("EndorsementCredential"), singleFileName); + bulkDownload(zipOut, this.certificateRepository.findByType("EndorsementCredential"), + singleFileName); // write cert to output stream } catch (IllegalArgumentException ex) { String uuidError = "Failed to parse ID from: "; @@ -690,47 +735,6 @@ public class CertificatePageController extends PageController { return hasDevice; } - /** - * Get the page based on the certificate type. - * - * @param certificateType String containing the certificate type - * @return the page for the certificate type. - */ - private static Page getCertificatePage(final String certificateType) { - // get page information (default to TRUST_CHAIN) - return switch (certificateType) { - case PLATFORMCREDENTIAL -> Page.PLATFORM_CREDENTIALS; - case ENDORSEMENTCREDENTIAL -> Page.ENDORSEMENT_KEY_CREDENTIALS; - case ISSUEDCERTIFICATES -> Page.ISSUED_CERTIFICATES; - case IDEVIDCERTIFICATE -> Page.IDEVID_CERTIFICATES; - default -> Page.TRUST_CHAIN; - }; - } - - /** - * Gets the concrete certificate class type to query for. - * - * @param certificateType String containing the certificate type - * @return the certificate class type - */ - private static Class getCertificateClass(final String certificateType) { - switch (certificateType) { - case PLATFORMCREDENTIAL: - return PlatformCredential.class; - case ENDORSEMENTCREDENTIAL: - return EndorsementCredential.class; - case ISSUEDCERTIFICATES: - return IssuedAttestationCertificate.class; - case IDEVIDCERTIFICATE: - return IDevIDCertificate.class; - case TRUSTCHAIN: - return CertificateAuthorityCredential.class; - default: - throw new IllegalArgumentException( - String.format("Unknown certificate type: %s", certificateType)); - } - } - /** * Gets the certificate by the hash code of its bytes. Looks for both * archived and unarchived certificates. @@ -769,7 +773,7 @@ public class CertificatePageController extends PageController { * Gets the certificate by the platform serial number. * * @param certificateType String containing the certificate type - * @param serialNumber the platform serial number + * @param serialNumber the platform serial number * @return the certificate or null if none is found */ private List getCertificateByBoardSN( @@ -794,8 +798,8 @@ public class CertificatePageController extends PageController { * with error messages if parsing fails. * * @param certificateType String containing the certificate type - * @param file the file being uploaded from the portal - * @param messages contains any messages that will be display on the page + * @param file the file being uploaded from the portal + * @param messages contains any messages that will be display on the page * @return the parsed certificate or null if parsing failed. */ private Certificate parseCertificate( @@ -835,13 +839,15 @@ public class CertificatePageController extends PageController { storeCertificate( certificateType, file.getOriginalFilename(), - messages, new CertificateAuthorityCredential(((java.security.cert.Certificate) i.next()).getEncoded())); + messages, new CertificateAuthorityCredential( + ((java.security.cert.Certificate) i.next()).getEncoded())); } // stop the main thread from saving/storing return null; } catch (CertificateException e) { - throw new IOException("Cannot construct X509Certificate from the input stream", e); + throw new IOException("Cannot construct X509Certificate from the input stream", + e); } } return new CertificateAuthorityCredential(fileBytes); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/DevicePageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/DevicePageController.java index 4b475c35..a783101f 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/DevicePageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/DevicePageController.java @@ -6,15 +6,12 @@ import hirs.attestationca.persist.entity.manager.DeviceRepository; import hirs.attestationca.persist.entity.manager.EndorsementCredentialRepository; import hirs.attestationca.persist.entity.manager.IssuedCertificateRepository; import hirs.attestationca.persist.entity.manager.PlatformCertificateRepository; -import hirs.attestationca.persist.entity.userdefined.Certificate; import hirs.attestationca.persist.entity.userdefined.Device; -import hirs.attestationca.persist.entity.userdefined.certificate.DeviceAssociatedCertificate; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.IssuedAttestationCertificate; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; import hirs.attestationca.portal.datatables.DataTableInput; import hirs.attestationca.portal.datatables.DataTableResponse; -import hirs.attestationca.portal.datatables.OrderedListQueryDataTableAdapter; import hirs.attestationca.portal.page.Page; import hirs.attestationca.portal.page.PageController; import hirs.attestationca.portal.page.params.NoPageParams; @@ -105,6 +102,7 @@ public class DevicePageController extends PageController { /** * Returns the list of devices combined with the certificates. + * * @param deviceList list containing the devices * @return a record list after the device and certificate was mapped together. */ @@ -209,11 +207,12 @@ public class DevicePageController extends PageController { /** * Returns the list of devices IDs. + * * @param deviceList list containing the devices * @return a list of the devices IDs */ private List getDevicesId(final FilteredRecordsList deviceList) { - List deviceIds = new ArrayList<>(); + List deviceIds = new ArrayList<>(); // loop all the devices for (int i = 0; i < deviceList.size(); i++) { diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/HelpPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/HelpPageController.java index 0f874f93..0bb6909e 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/HelpPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/HelpPageController.java @@ -23,11 +23,10 @@ import static hirs.attestationca.portal.page.Page.HELP; @RequestMapping("/HIRS_AttestationCAPortal/portal/help") public class HelpPageController extends PageController { + private static final String PATH = "/docs"; @Autowired private ApplicationContext applicationContext; - private static final String PATH = "/docs"; - /** * Constructor providing the Page's display and routing specification. */ @@ -39,7 +38,7 @@ public class HelpPageController extends PageController { * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from redirect. + * @param model The data model for the request. Can contain data from redirect. * @return the path for the view and data model for the page. */ @Override diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/IndexPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/IndexPageController.java index 6a223db5..eb4f7911 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/IndexPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/IndexPageController.java @@ -29,7 +29,7 @@ public class IndexPageController extends PageController { * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from redirect. + * @param model The data model for the request. Can contain data from redirect. * @return the path for the view and data model for the page. */ @Override diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/PolicyPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/PolicyPageController.java index eba8ad7f..ecd94bc8 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/PolicyPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/PolicyPageController.java @@ -31,27 +31,23 @@ import java.util.Map; @RequestMapping("/HIRS_AttestationCAPortal/portal/policy") public class PolicyPageController extends PageController { - /** - * Represents a web request indicating to enable a setting (based on radio - * buttons from a web form). - */ - private static final String ENABLED_CHECKED_PARAMETER_VALUE = "checked"; - - private static final String ENABLED_EXPIRES_PARAMETER_VALUE = "expires"; - - private final PolicyRepository policyRepository; - /** * Model attribute name used by initPage for the initial data passed to the * page. */ public static final String INITIAL_DATA = "initialData"; - /** * Flash attribute name used by initPage and post for the data forwarded * during the redirect from the POST operation back to the page. */ public static final String RESULT_DATA = "resultData"; + /** + * Represents a web request indicating to enable a setting (based on radio + * buttons from a web form). + */ + private static final String ENABLED_CHECKED_PARAMETER_VALUE = "checked"; + private static final String ENABLED_EXPIRES_PARAMETER_VALUE = "expires"; + private final PolicyRepository policyRepository; /** * Constructor. @@ -69,12 +65,31 @@ public class PolicyPageController extends PageController { } } + /** + * Takes in policy setting states and determines if policy configuration is + * valid or not. PC Attribute Validation must have PC Validation Enabled PC + * Validation must have EC Validation enabled + * + * @param isEcEnable EC Validation Policy State + * @param isPcEnable PC Validation Policy State + * @param isPcAttEnable PC Attribute Validation Policy State + * @return True if policy combination is valid + */ + private static boolean isPolicyValid(final boolean isEcEnable, final boolean isPcEnable, + final boolean isPcAttEnable) { + if (isPcAttEnable && !isPcEnable) { + return false; + } else { + return !isPcEnable || isEcEnable; + } + } + /** * Returns the path for the view and the data model for the page. * * @param params The object to map url parameters into. - * @param model The data model for the request. Can contain data from - * redirect. + * @param model The data model for the request. Can contain data from + * redirect. * @return the path for the view and data model for the page. */ @Override @@ -98,8 +113,8 @@ public class PolicyPageController extends PageController { * the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -149,8 +164,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -199,14 +214,15 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @RequestMapping(value = "update-revision-ignore", method = RequestMethod.POST) public RedirectView updateIgnoreRevisionAttribute(@ModelAttribute final PolicyPageModel ppModel, - final RedirectAttributes attr) throws URISyntaxException { + final RedirectAttributes attr) + throws URISyntaxException { // set the data received to be populated back into the form Map model = new HashMap<>(); PageMessages messages = new PageMessages(); @@ -250,7 +266,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -294,7 +310,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -339,7 +355,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -409,7 +425,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -479,7 +495,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -550,7 +566,7 @@ public class PolicyPageController extends PageController { * back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original page. + * @param attr RedirectAttributes used to forward data back to the original page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -619,8 +635,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -671,8 +687,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -728,8 +744,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -779,8 +795,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -830,8 +846,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -881,8 +897,8 @@ public class PolicyPageController extends PageController { * redirects back to the original page. * * @param ppModel The data posted by the form mapped into an object. - * @param attr RedirectAttributes used to forward data back to the original - * page. + * @param attr RedirectAttributes used to forward data back to the original + * page. * @return View containing the url and parameters * @throws URISyntaxException if malformed URI */ @@ -946,25 +962,6 @@ public class PolicyPageController extends PageController { model.put(MESSAGES_ATTRIBUTE, messages); } - /** - * Takes in policy setting states and determines if policy configuration is - * valid or not. PC Attribute Validation must have PC Validation Enabled PC - * Validation must have EC Validation enabled - * - * @param isEcEnable EC Validation Policy State - * @param isPcEnable PC Validation Policy State - * @param isPcAttEnable PC Attribute Validation Policy State - * @return True if policy combination is valid - */ - private static boolean isPolicyValid(final boolean isEcEnable, final boolean isPcEnable, - final boolean isPcAttEnable) { - if (isPcAttEnable && !isPcEnable) { - return false; - } else { - return !isPcEnable || isEcEnable; - } - } - /** * Helper function to get a fresh load of the default policy from the DB. * @@ -985,7 +982,7 @@ public class PolicyPageController extends PageController { * model. * * @param ppModel the page model - * @param model the map of string messages to be displayed on the view + * @param model the map of string messages to be displayed on the view * @return The default Supply Chain Policy */ private PolicySettings getDefaultPolicyAndSetInModel( diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java index b89c78b7..1c5ca868 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestDetailsPageController.java @@ -19,8 +19,8 @@ import hirs.attestationca.portal.page.Page; import hirs.attestationca.portal.page.PageController; import hirs.attestationca.portal.page.PageMessages; import hirs.attestationca.portal.page.params.ReferenceManifestDetailsPageParams; -import hirs.utils.rim.ReferenceManifestValidator; import hirs.utils.SwidResource; +import hirs.utils.rim.ReferenceManifestValidator; import hirs.utils.tpm.eventlog.TCGEventLog; import hirs.utils.tpm.eventlog.TpmPcrEvent; import lombok.extern.log4j.Log4j2; @@ -33,7 +33,6 @@ import org.springframework.web.servlet.ModelAndView; import java.io.IOException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; @@ -53,28 +52,30 @@ import java.util.UUID; @Log4j2 @Controller @RequestMapping("/HIRS_AttestationCAPortal/portal/rim-details") -public class ReferenceManifestDetailsPageController extends PageController { +public class ReferenceManifestDetailsPageController + extends PageController { + private static final ReferenceManifestValidator RIM_VALIDATOR + = new ReferenceManifestValidator(); private final ReferenceManifestRepository referenceManifestRepository; private final ReferenceDigestValueRepository referenceDigestValueRepository; private final CertificateRepository certificateRepository; private final CACredentialRepository caCertificateRepository; - private static final ReferenceManifestValidator RIM_VALIDATOR - = new ReferenceManifestValidator(); /** * Constructor providing the Page's display and routing specification. * - * @param referenceManifestRepository the repository for RIM. - * @param referenceDigestValueRepository the reference event manager. - * @param certificateRepository the certificate manager. - * @param caCertificateRepository the CA certificate manager. + * @param referenceManifestRepository the repository for RIM. + * @param referenceDigestValueRepository the reference event manager. + * @param certificateRepository the certificate manager. + * @param caCertificateRepository the CA certificate manager. */ @Autowired - public ReferenceManifestDetailsPageController(final ReferenceManifestRepository referenceManifestRepository, - final ReferenceDigestValueRepository referenceDigestValueRepository, - final CertificateRepository certificateRepository, - final CACredentialRepository caCertificateRepository) { + public ReferenceManifestDetailsPageController( + final ReferenceManifestRepository referenceManifestRepository, + final ReferenceDigestValueRepository referenceDigestValueRepository, + final CertificateRepository certificateRepository, + final CACredentialRepository caCertificateRepository) { super(Page.RIM_DETAILS); this.referenceManifestRepository = referenceManifestRepository; this.referenceDigestValueRepository = referenceDigestValueRepository; @@ -82,73 +83,15 @@ public class ReferenceManifestDetailsPageController extends PageController data = new HashMap<>(); - - // Check if parameters were set - if (params.getId() == null) { - String typeError = "ID was not provided"; - messages.addError(typeError); - log.debug(typeError); - mav.addObject(MESSAGES_ATTRIBUTE, messages); - } else { - try { - UUID uuid = UUID.fromString(params.getId()); - data.putAll(getRimDetailInfo(uuid, referenceManifestRepository, - referenceDigestValueRepository, certificateRepository, - caCertificateRepository)); - } catch (IllegalArgumentException iaEx) { - String uuidError = "Failed to parse ID from: " + params.getId(); - messages.addError(uuidError); - log.error(uuidError, iaEx); - } catch (CertificateException cEx) { - log.error(cEx); - } catch (NoSuchAlgorithmException nsEx) { - log.error(nsEx); - } catch (IOException ioEx) { - log.error(ioEx); - } catch (Exception ex) { - log.error(ex); - } - - if (data.isEmpty()) { - String notFoundMessage = "Unable to find RIM with ID: " + params.getId(); - messages.addError(notFoundMessage); - log.warn(notFoundMessage); - mav.addObject(MESSAGES_ATTRIBUTE, messages); - } else { - mav.addObject(INITIAL_DATA, data); - } - } - - // return the model and view - return mav; - } - /** * This method takes the place of an entire class for a string builder. * Gathers all information and returns it for displays. * - * @param uuid database reference for the requested RIM. - * @param referenceManifestRepository the reference manifest manager. - * @param referenceDigestValueRepository the reference event manager. - * @param certificateRepository the certificate manager. - * @param caCertificateRepository the certificate manager. + * @param uuid database reference for the requested RIM. + * @param referenceManifestRepository the reference manifest manager. + * @param referenceDigestValueRepository the reference event manager. + * @param certificateRepository the certificate manager. + * @param caCertificateRepository the certificate manager. * @return mapping of the RIM information from the database. * @throws java.io.IOException error for reading file bytes. * @throws NoSuchAlgorithmException If an unknown Algorithm is encountered. @@ -166,7 +109,8 @@ public class ReferenceManifestDetailsPageController extends PageController to a List. + * * @param set of CACs to convert * @return list of X509Certificates */ - private static List convertCACsToX509Certificates(Set set) + private static List convertCACsToX509Certificates( + Set set) throws IOException { ArrayList certs = new ArrayList<>(set.size()); for (CertificateAuthorityCredential cac : set) { @@ -364,7 +310,7 @@ public class ReferenceManifestDetailsPageController extends PageController data = new HashMap<>(); + + // Check if parameters were set + if (params.getId() == null) { + String typeError = "ID was not provided"; + messages.addError(typeError); + log.debug(typeError); + mav.addObject(MESSAGES_ATTRIBUTE, messages); + } else { + try { + UUID uuid = UUID.fromString(params.getId()); + data.putAll(getRimDetailInfo(uuid, referenceManifestRepository, + referenceDigestValueRepository, certificateRepository, + caCertificateRepository)); + } catch (IllegalArgumentException iaEx) { + String uuidError = "Failed to parse ID from: " + params.getId(); + messages.addError(uuidError); + log.error(uuidError, iaEx); + } catch (CertificateException cEx) { + log.error(cEx); + } catch (NoSuchAlgorithmException nsEx) { + log.error(nsEx); + } catch (IOException ioEx) { + log.error(ioEx); + } catch (Exception ex) { + log.error(ex); + } + + if (data.isEmpty()) { + String notFoundMessage = "Unable to find RIM with ID: " + params.getId(); + messages.addError(notFoundMessage); + log.warn(notFoundMessage); + mav.addObject(MESSAGES_ATTRIBUTE, messages); + } else { + mav.addObject(INITIAL_DATA, data); + } + } + + // return the model and view + return mav; + } } diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java index 9722ab2d..9cc2faa9 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ReferenceManifestPageController.java @@ -64,22 +64,20 @@ public class ReferenceManifestPageController extends PageController records = new FilteredRecordsList<>(); int currentPage = input.getStart() / input.getLength(); Pageable paging = PageRequest.of(currentPage, input.getLength(), Sort.by(orderColumnName)); - org.springframework.data.domain.Page pagedResult = referenceManifestRepository.findByArchiveFlag(false, paging); + org.springframework.data.domain.Page pagedResult = + referenceManifestRepository.findByArchiveFlag(false, paging); int rimCount = 0; if (pagedResult.hasContent()) { @@ -145,10 +144,10 @@ public class ReferenceManifestPageController extends PageController { - @Autowired(required = false) - private EntityManager entityManager; - private final ReferenceDigestValueRepository referenceDigestValueRepository; private final ReferenceManifestRepository referenceManifestRepository; + @Autowired(required = false) + private EntityManager entityManager; /** * Constructor providing the Page's display and routing specification. * * @param referenceDigestValueRepository the referenceDigestValueRepository object - * @param referenceManifestRepository the reference manifest manager object + * @param referenceManifestRepository the reference manifest manager object */ @Autowired public RimDatabasePageController(final ReferenceDigestValueRepository referenceDigestValueRepository, @@ -102,7 +101,8 @@ public class RimDatabasePageController extends PageController { Session session = entityManager.unwrap(Session.class); CriteriaBuilder cb = session.getCriteriaBuilder(); Root rimRoot = criteriaQuery.from(Reference.class); - criteriaQuery.select(rimRoot).distinct(true).where(cb.isNull(rimRoot.get(Certificate.ARCHIVE_FIELD))); + criteriaQuery.select(rimRoot).distinct(true) + .where(cb.isNull(rimRoot.get(Certificate.ARCHIVE_FIELD))); } }; @@ -112,7 +112,8 @@ public class RimDatabasePageController extends PageController { int currentPage = input.getStart() / input.getLength(); Pageable paging = PageRequest.of(currentPage, input.getLength(), Sort.by(orderColumnName)); - org.springframework.data.domain.Page pagedResult = referenceDigestValueRepository.findAll(paging); + org.springframework.data.domain.Page pagedResult = + referenceDigestValueRepository.findAll(paging); if (pagedResult.hasContent()) { referenceDigestValues.addAll(pagedResult.getContent()); @@ -127,7 +128,8 @@ public class RimDatabasePageController extends PageController { for (ReferenceDigestValue rdv : referenceDigestValues) { // We are updating the base rim ID field if necessary and if (rdv.getBaseRimId() == null && referenceManifestRepository.existsById(rdv.getSupportRimId())) { - support = (SupportReferenceManifest) referenceManifestRepository.getReferenceById(rdv.getSupportRimId()); + support = (SupportReferenceManifest) referenceManifestRepository.getReferenceById( + rdv.getSupportRimId()); rdv.setBaseRimId(support.getAssociatedRim()); try { referenceDigestValueRepository.save(rdv); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ValidationReportsPageController.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ValidationReportsPageController.java index ce19f790..7a6cacc2 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ValidationReportsPageController.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/ValidationReportsPageController.java @@ -55,6 +55,13 @@ import java.util.regex.Pattern; @RequestMapping("/HIRS_AttestationCAPortal/portal/validation-reports") public class ValidationReportsPageController extends PageController { + private static final String DEFAULT_COMPANY = "AllDevices"; + private static final String UNDEFINED = "undefined"; + private static final String TRUE = "true"; + private static String systemColumnHeaders = "Verified Manufacturer," + + "Model,SN,Verification Date,Device Status"; + private static String componentColumnHeaders = "Component name,Component manufacturer," + + "Component model,Component SN,Issuer,Component status"; private final SupplyChainValidationSummaryRepository supplyChainValidatorSummaryRepository; private final CertificateRepository certificateRepository; private final DeviceRepository deviceRepository; @@ -62,20 +69,13 @@ public class ValidationReportsPageController extends PageController records = new FilteredRecordsList<>(); int currentPage = input.getStart() / input.getLength(); Pageable paging = PageRequest.of(currentPage, input.getLength(), Sort.by(orderColumnName)); - org.springframework.data.domain.Page pagedResult = supplyChainValidatorSummaryRepository.findByArchiveFlagFalse(paging); + org.springframework.data.domain.Page pagedResult = + supplyChainValidatorSummaryRepository.findByArchiveFlagFalse(paging); if (pagedResult.hasContent()) { records.addAll(pagedResult.getContent()); @@ -138,11 +140,12 @@ public class ValidationReportsPageController extends PageController createTimes = new ArrayList(); - String[] deviceNames = new String[]{}; + String[] deviceNames = new String[] {}; String columnHeaders = ""; boolean systemOnly = false; boolean componentOnly = false; @@ -325,13 +328,14 @@ public class ValidationReportsPageController extends PageController> parsedComponents, final String company, @@ -372,6 +376,7 @@ public class ValidationReportsPageController extends PageController 0) { componentFailureString.append(pc.getComponentFailures()); // get all the certificates associated with the platform serial - List chainCertificates = certificateRepository.byBoardSerialNumber(pc.getPlatformSerial()); + List chainCertificates = + certificateRepository.byBoardSerialNumber(pc.getPlatformSerial()); // combine all components in each certificate for (ComponentIdentifier ci : pc.getComponentIdentifiers()) { ArrayList issuerAndComponent = new ArrayList(); diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/NoPageParams.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/NoPageParams.java index 55497f98..a270d0af 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/NoPageParams.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/NoPageParams.java @@ -1,6 +1,7 @@ package hirs.attestationca.portal.page.params; import hirs.attestationca.portal.page.PageParams; + import java.util.LinkedHashMap; /** diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestDetailsPageParams.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestDetailsPageParams.java index 23a3ddf6..c3cfced2 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestDetailsPageParams.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestDetailsPageParams.java @@ -15,7 +15,8 @@ import java.util.LinkedHashMap; @AllArgsConstructor public class ReferenceManifestDetailsPageParams implements PageParams { - @Getter @Setter + @Getter + @Setter private String id; /** diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestPageParams.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestPageParams.java index 789bd5fc..bd166cc5 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestPageParams.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/ReferenceManifestPageParams.java @@ -21,7 +21,7 @@ public class ReferenceManifestPageParams implements PageParams { private String type; /** - *Constructor to set all Reference Integrity Manifest URL parameters. + * Constructor to set all Reference Integrity Manifest URL parameters. * * @param id the String parameter to set */ diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/CertificateStringMapBuilder.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/CertificateStringMapBuilder.java index d415f3f1..49eefd5e 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/CertificateStringMapBuilder.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/utils/CertificateStringMapBuilder.java @@ -42,7 +42,7 @@ public final class CertificateStringMapBuilder { /** * Returns the general information. * - * @param certificate certificate to get the general information. + * @param certificate certificate to get the general information. * @param certificateRepository the certificate repository for retrieving certs. * @return a hash map with the general certificate information. */ @@ -107,7 +107,8 @@ public final class CertificateStringMapBuilder { //Get issuer ID if not self signed if (data.get("isSelfSigned").equals("false")) { //Get the missing certificate chain for not self sign - Certificate missingCert = containsAllChain(certificate, certificateRepository, caCertificateRepository); + Certificate missingCert = + containsAllChain(certificate, certificateRepository, caCertificateRepository); String issuerResult; if (missingCert != null) { @@ -144,7 +145,7 @@ public final class CertificateStringMapBuilder { /** * Recursive function that check if all the certificate chain is present. * - * @param certificate certificate to get the issuer + * @param certificate certificate to get the issuer * @param certificateRepository the certificate repository for retrieving certs. * @return a boolean indicating if it has the full chain or not. */ @@ -159,7 +160,8 @@ public final class CertificateStringMapBuilder { //Check if there is a subject organization if (certificate.getAuthorityKeyIdentifier() != null && !certificate.getAuthorityKeyIdentifier().isEmpty()) { - skiCA = caCredentialRepository.findBySubjectKeyIdStringAndArchiveFlag(certificate.getAuthorityKeyIdentifier(), false); + skiCA = caCredentialRepository.findBySubjectKeyIdStringAndArchiveFlag( + certificate.getAuthorityKeyIdentifier(), false); } else { log.error(String.format("Certificate (%s) for %s has no authority key identifier.", certificate.getClass().toString(), certificate.getSubject())); @@ -169,10 +171,12 @@ public final class CertificateStringMapBuilder { if (certificate.getIssuerSorted() == null || certificate.getIssuerSorted().isEmpty()) { //Get certificates by subject - issuerCertificates = caCredentialRepository.findBySubjectAndArchiveFlag(certificate.getIssuer(), false); + issuerCertificates = + caCredentialRepository.findBySubjectAndArchiveFlag(certificate.getIssuer(), false); } else { //Get certificates by subject organization - issuerCertificates = caCredentialRepository.findBySubjectSortedAndArchiveFlag(certificate.getIssuerSorted(), false); + issuerCertificates = caCredentialRepository.findBySubjectSortedAndArchiveFlag( + certificate.getIssuerSorted(), false); } } else { issuerCertificates.add(skiCA); @@ -202,7 +206,7 @@ public final class CertificateStringMapBuilder { /** * Returns the Certificate Authority information. * - * @param uuid ID for the certificate. + * @param uuid ID for the certificate. * @param caCertificateRepository the certificate manager for retrieving certs. * @return a hash map with the endorsement certificate information. */ @@ -217,14 +221,15 @@ public final class CertificateStringMapBuilder { String notFoundMessage = "Unable to find Certificate Authority " + "Credential with ID: " + uuid; - return getCertificateAuthorityInfoHelper(certificateRepository, caCertificateRepository, certificate, notFoundMessage); + return getCertificateAuthorityInfoHelper(certificateRepository, caCertificateRepository, certificate, + notFoundMessage); } /** * Returns the Trust Chain credential information. * - * @param certificate the certificate - * @param certificateRepository the certificate repository for retrieving certs. + * @param certificate the certificate + * @param certificateRepository the certificate repository for retrieving certs. * @param caCertificateRepository the certificate repository for retrieving certs. * @return a hash map with the endorsement certificate information. */ @@ -243,7 +248,8 @@ public final class CertificateStringMapBuilder { HashMap data = new HashMap<>(); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); data.put("subjectKeyIdentifier", Arrays.toString(certificate.getSubjectKeyIdentifier())); //x509 credential version @@ -259,7 +265,7 @@ public final class CertificateStringMapBuilder { /** * Returns the endorsement credential information. * - * @param uuid ID for the certificate. + * @param uuid ID for the certificate. * @param certificateRepository the certificate repository for retrieving certs. * @return a hash map with the endorsement certificate information. */ @@ -267,10 +273,12 @@ public final class CertificateStringMapBuilder { final CertificateRepository certificateRepository, final CACredentialRepository caCertificateRepository) { HashMap data = new HashMap<>(); - EndorsementCredential certificate = (EndorsementCredential) certificateRepository.getCertificate(uuid); + EndorsementCredential certificate = + (EndorsementCredential) certificateRepository.getCertificate(uuid); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); // Set extra fields data.put("manufacturer", certificate.getManufacturer()); data.put("model", certificate.getModel()); @@ -301,10 +309,10 @@ public final class CertificateStringMapBuilder { /** * Returns the Platform credential information. * - * @param uuid ID for the certificate. + * @param uuid ID for the certificate. * @param certificateRepository the certificate manager for retrieving certs. * @return a hash map with the endorsement certificate information. - * @throws IOException when parsing the certificate + * @throws IOException when parsing the certificate * @throws IllegalArgumentException invalid argument on parsing the certificate */ public static HashMap getPlatformInformation(final UUID uuid, @@ -316,7 +324,8 @@ public final class CertificateStringMapBuilder { PlatformCredential certificate = (PlatformCredential) certificateRepository.getCertificate(uuid); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCertificateRepository)); data.put("credentialType", certificate.getCredentialType()); data.put("platformType", certificate.getPlatformChainType()); data.put("manufacturer", certificate.getManufacturer()); @@ -344,7 +353,7 @@ public final class CertificateStringMapBuilder { data.put("holderId", ekCertificate.getId().toString()); } } else { - if (certificate.getPlatformChainType()!= null + if (certificate.getPlatformChainType() != null && certificate.getPlatformChainType().equals("Delta")) { PlatformCredential holderCertificate = (PlatformCredential) certificateRepository .findBySerialNumber(certificate.getHolderSerialNumber(), @@ -399,7 +408,8 @@ public final class CertificateStringMapBuilder { if (certificate.getPlatformSerial() != null) { // link certificate chain - List chainCertificates = certificateRepository.byBoardSerialNumber(certificate.getPlatformSerial()); + List chainCertificates = + certificateRepository.byBoardSerialNumber(certificate.getPlatformSerial()); data.put("numInChain", chainCertificates.size()); Collections.sort(chainCertificates, new Comparator() { @Override @@ -433,9 +443,9 @@ public final class CertificateStringMapBuilder { /** * Returns a HasHMap of a string. * Ex: input "TPMSpecification{family='abc',level=0, revision=0}" - * output map[TPMSpecificationFamily] = 'abc' - * map[TPMSpecificationLevel] = 0 - * map[TPMSpecificationRevision] = 0 + * output map[TPMSpecificationFamily] = 'abc' + * map[TPMSpecificationLevel] = 0 + * map[TPMSpecificationRevision] = 0 * * @param str HashMap string to be converted. * @return a hash map with key-value pairs from the string @@ -460,7 +470,7 @@ public final class CertificateStringMapBuilder { /** * Returns the Issued Attestation Certificate information. * - * @param uuid ID for the certificate. + * @param uuid ID for the certificate. * @param certificateRepository the certificate manager for retrieving certs. * @return a hash map with the endorsement certificate information. */ @@ -468,10 +478,12 @@ public final class CertificateStringMapBuilder { final CertificateRepository certificateRepository, final CACredentialRepository caCredentialRepository) { HashMap data = new HashMap<>(); - IssuedAttestationCertificate certificate = (IssuedAttestationCertificate) certificateRepository.getCertificate(uuid); + IssuedAttestationCertificate certificate = + (IssuedAttestationCertificate) certificateRepository.getCertificate(uuid); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCredentialRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCredentialRepository)); // add endorsement credential ID if not null if (certificate.getEndorsementCredential() != null) { @@ -532,7 +544,7 @@ public final class CertificateStringMapBuilder { /** * Returns the IDevID Certificate information. * - * @param uuid ID for the certificate. + * @param uuid ID for the certificate. * @param certificateRepository the certificate manager for retrieving certs. * @return a hash map with the endorsement certificate information. */ @@ -544,15 +556,15 @@ public final class CertificateStringMapBuilder { IDevIDCertificate certificate = (IDevIDCertificate) certificateRepository.getCertificate(uuid); if (certificate != null) { - data.putAll(getGeneralCertificateInfo(certificate, certificateRepository, caCredentialRepository)); + data.putAll( + getGeneralCertificateInfo(certificate, certificateRepository, caCredentialRepository)); if (certificate.getHwType() != null) { data.put("hwType", certificate.getHwType()); String hwTypeReadable; if (certificate.hasTCGOIDs()) { hwTypeReadable = "TPM-Bound IDevID"; - } - else { + } else { hwTypeReadable = "Manufacturer Specific"; } data.put("hwTypeReadable", hwTypeReadable); @@ -570,16 +582,14 @@ public final class CertificateStringMapBuilder { data.put("ekAuthorityKeyIdentifier", hwSerialArray[1]); data.put("ekCertificateSerialNumber", hwSerialArray[2]); } - } - else { + } else { // Corresponds to digest of EK certificate data.put("ekCertificateDigest", Boolean.valueOf(true).toString()); String hwSerialToAdd = Hex.toHexString(certificate.getHwSerialNum()); data.put("hwSerialNumHex", Boolean.valueOf(true).toString()); data.put("hwSerialNum", hwSerialToAdd); } - } - else { + } else { String hwSerialToAdd = hwSerialStr; // Check if hwSerialNum is a printable ASCII string; default to hex otherwise diff --git a/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.win.xml b/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.win.xml index 16b13bf3..a2a7727a 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.win.xml +++ b/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.win.xml @@ -5,28 +5,28 @@ + filePattern="C:/ProgramData/hirs/log/HIRS_AttestationCA_Portal.log-%d{yyyy-MM-dd}-%i.log"> %d{yyyy-MM-dd HH:mm:ss} [%C.%M] %-5p : %m%n - + - + size="10 MB"/> + - - + + - + - + diff --git a/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.xml b/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.xml index 8dec9345..2a64d950 100644 --- a/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.xml +++ b/HIRS_AttestationCAPortal/src/main/resources/log4j2-spring.xml @@ -5,28 +5,28 @@ + filePattern="/var/log/hirs/HIRS_AttestationCA_Portal-%d{yyyy-MM-dd}-%i.log"> %d{yyyy-MM-dd HH:mm:ss} [%C.%M] %-5p : %m%n - + - + size="10 MB"/> + - - - + + + - + - + diff --git a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/web.xml b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/web.xml index f7bf98b6..f6670d93 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/web.xml +++ b/HIRS_AttestationCAPortal/src/main/webapp/WEB-INF/web.xml @@ -1,6 +1,6 @@ - HIRS Attestation CA Portal diff --git a/HIRS_AttestationCAPortal/src/main/webapp/lib/bootstrap-3.3.7/fonts/glyphicons-halflings-regular.svg b/HIRS_AttestationCAPortal/src/main/webapp/lib/bootstrap-3.3.7/fonts/glyphicons-halflings-regular.svg index 94fb5490..2ba280f4 100644 --- a/HIRS_AttestationCAPortal/src/main/webapp/lib/bootstrap-3.3.7/fonts/glyphicons-halflings-regular.svg +++ b/HIRS_AttestationCAPortal/src/main/webapp/lib/bootstrap-3.3.7/fonts/glyphicons-halflings-regular.svg @@ -1,288 +1,543 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageControllerTest.java index 7b70a1b9..b0ea939d 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageControllerTest.java @@ -5,11 +5,6 @@ import hirs.attestationca.persist.entity.userdefined.certificate.CertificateAuth import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.IssuedAttestationCertificate; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -17,20 +12,29 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import org.springframework.web.context.WebApplicationContext; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + import static org.hamcrest.Matchers.equalTo; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; /** * Base class for PageController tests. - * */ @SpringBootTest @@ -39,22 +43,19 @@ import static org.hamcrest.Matchers.equalTo; @TestInstance(TestInstance.Lifecycle.PER_CLASS) // needed to use non-static BeforeAll public abstract class PageControllerTest { + // Pre-prefix path for all the Controllers. + // There's an option in Page to add prefix path used for some Controllers. + private static final String PRE_PREFIX_PATH = "/HIRS_AttestationCAPortal/portal/"; + // Represents the Page for the Controller under test. + private final Page page; // Contains server-side support for testing Spring MVC applications // via WebTestClient with MockMvc for server request handling. @Autowired private WebApplicationContext webApplicationContext; - // Used to set up mocked servlet environment to test the HTTP controller // endpoints without the need to launch the embedded servlet container. private MockMvc mockMvc; - // Represents the Page for the Controller under test. - private final Page page; - - // Pre-prefix path for all the Controllers. - // There's an option in Page to add prefix path used for some Controllers. - private static final String PRE_PREFIX_PATH = "/HIRS_AttestationCAPortal/portal/"; - /** * Constructor requiring the Page's display and routing specification. * @@ -64,6 +65,43 @@ public abstract class PageControllerTest { this.page = page; } + /** + * Returns a blank model for initPage tests. + * + * @return a blank model for initPage tests. + */ + protected static final Model getBlankModel() { + return new ExtendedModelMap(); + } + + /** + * If the AssertionError is a redirected URL error, check the results of the executed request + * for the actual redirected URL and throw a new error containing the comparison to the expected + * URL. + *

+ * If the error is not a redirected URL error, rethrow the original error. + * + * @param expectedURL the expected redirected URL AntMatcher pattern + * @param actions the results of the executed request + * @param err the AssertionError to indicate if the error is a redirected URL error + * @throws AssertionError with added information if a redirected URL error or the original error + */ + protected static final void enhanceRedirectedUrlError( + final String expectedURL, + final ResultActions actions, + final AssertionError err) throws AssertionError { + if ("Redirected URL".equals(err.getMessage())) { + final String actualURL = actions.andReturn().getResponse().getRedirectedUrl(); + final String msg + = err.getMessage() + ": " + + " expected [" + expectedURL + "]" + + " but found [" + actualURL + "]"; + throw new AssertionError(msg); + } else { + throw err; + } + } + /** * Returns the Page's display and routing specification. * @@ -82,49 +120,12 @@ public abstract class PageControllerTest { return mockMvc; } - /** - * Returns a blank model for initPage tests. - * - * @return a blank model for initPage tests. - */ - protected static final Model getBlankModel() { - return new ExtendedModelMap(); - } - - /** - * If the AssertionError is a redirected URL error, check the results of the executed request - * for the actual redirected URL and throw a new error containing the comparison to the expected - * URL. - * - * If the error is not a redirected URL error, rethrow the original error. - * - * @param expectedURL the expected redirected URL AntMatcher pattern - * @param actions the results of the executed request - * @param err the AssertionError to indicate if the error is a redirected URL error - * @throws AssertionError with added information if a redirected URL error or the original error - */ - protected static final void enhanceRedirectedUrlError( - final String expectedURL, - final ResultActions actions, - final AssertionError err) throws AssertionError { - if ("Redirected URL".equals(err.getMessage())) { - final String actualURL = actions.andReturn().getResponse().getRedirectedUrl(); - final String msg - = err.getMessage() + ": " - + " expected [" + expectedURL + "]" - + " but found [" + actualURL + "]"; - throw new AssertionError(msg); - } else { - throw err; - } - } - - /** * Construct a test certificate from the given parameters. - * @param the type of Certificate that will be created + * + * @param the type of Certificate that will be created * @param certificateClass the class of certificate to generate - * @param filename the location of the certificate to be used + * @param filename the location of the certificate to be used * @return the newly-constructed Certificate * @throws IOException if there is a problem constructing the test certificate */ @@ -138,11 +139,12 @@ public abstract class PageControllerTest { /** * Construct a test certificate from the given parameters. - * @param the type of Certificate that will be created - * @param certificateClass the class of certificate to generate - * @param filename the location of the certificate to be used + * + * @param the type of Certificate that will be created + * @param certificateClass the class of certificate to generate + * @param filename the location of the certificate to be used * @param endorsementCredential the endorsement credentials (can be null) - * @param platformCredentials the platform credentials (can be null) + * @param platformCredentials the platform credentials (can be null) * @return the newly-constructed Certificate * @throws IOException if there is a problem constructing the test certificate */ diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageTestConfiguration.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageTestConfiguration.java index 5fd2b98e..20c6a009 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageTestConfiguration.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/PageTestConfiguration.java @@ -1,18 +1,10 @@ package hirs.attestationca.portal.page; import hirs.attestationca.persist.entity.userdefined.certificate.CertificateAuthorityCredential; -import javax.sql.DataSource; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.*; -import java.security.cert.X509Certificate; -import java.util.Properties; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.context.annotation.*; +import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; @@ -21,12 +13,24 @@ import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import javax.sql.DataSource; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.Properties; + /** * A configuration class for testing Attestation CA Portal classes that require a database. * This class sets up a temporary in-memory database that is used for testing. * This class also creates beans that override beans in main class PersistenceJPAConfig. * A few 'dummy' beans had to be created to override PersistenceJPAConfig beans that were - * not needed and would interfere with the tests. + * not needed and would interfere with the tests. */ @TestConfiguration @EnableJpaRepositories(basePackages = "hirs.attestationca.persist.entity.manager") @@ -49,7 +53,7 @@ public class PageTestConfiguration { * * @return the {@link X509Certificate} of the ACA * @throws URISyntaxException if there's a syntax error on the path to the cert - * @throws IOException exception reading the file + * @throws IOException exception reading the file */ @Bean public X509Certificate acaCertificate() throws URISyntaxException, IOException { @@ -78,7 +82,7 @@ public class PageTestConfiguration { * hibernate configuration file. * * @return entity manager factory, which provides instances of EntityManager for connecting - * to same database. + * to same database. */ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { @@ -123,8 +127,7 @@ public class PageTestConfiguration { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); PrivateKey dummy_privKey = keyGenerator.generateKeyPair().getPrivate(); return dummy_privKey; - } - catch (GeneralSecurityException e) { + } catch (GeneralSecurityException e) { throw new AssertionError(e); } } diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/DevicePageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/DevicePageControllerTest.java index 3ba0bcb9..a04ae23e 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/DevicePageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/DevicePageControllerTest.java @@ -2,21 +2,24 @@ package hirs.attestationca.portal.page.controllers; import hirs.attestationca.persist.entity.manager.CertificateRepository; import hirs.attestationca.persist.entity.manager.DeviceRepository; +import hirs.attestationca.persist.entity.userdefined.Device; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredential; -import hirs.attestationca.persist.entity.userdefined.Device; import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.attestationca.persist.enums.HealthStatus; import hirs.attestationca.portal.page.PageControllerTest; -import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.io.IOException; + import static hirs.attestationca.portal.page.Page.DEVICES; import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Integration tests that test the URL End Points of DevicePageController. @@ -24,17 +27,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class DevicePageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between device entity and data storage in db - @Autowired - private DeviceRepository deviceRepository; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - // Location of test certs private static final String TEST_ENDORSEMENT_CREDENTIAL = "/endorsement_credentials/tpmcert.pem"; @@ -42,6 +34,14 @@ public class DevicePageControllerTest extends PageControllerTest { = "/endorsement_credentials/ab21ccf2-tpmcert.pem"; private static final String TEST_PLATFORM_CREDENTIAL = "/platform_credentials/Intel_pc.cer"; + // Base path for the page + private String pagePath; + // Repository manager to handle data access between device entity and data storage in db + @Autowired + private DeviceRepository deviceRepository; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; /** @@ -54,6 +54,7 @@ public class DevicePageControllerTest extends PageControllerTest { /** * Prepares a testing environment. + * * @throws IOException if there is a problem constructing the test certificate */ @BeforeAll @@ -63,8 +64,8 @@ public class DevicePageControllerTest extends PageControllerTest { Device device; // Create new device to be used in test and save it to db - device = new Device("Test Device",null, HealthStatus.TRUSTED, AppraisalStatus.Status.PASS, - null,false,"tmp_overrideReason", "tmp_summId"); + device = new Device("Test Device", null, HealthStatus.TRUSTED, AppraisalStatus.Status.PASS, + null, false, "tmp_overrideReason", "tmp_summId"); device = deviceRepository.save(device); // Upload and save EK Cert diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/EndorsementKeyCredentialsPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/EndorsementKeyCredentialsPageControllerTest.java index b6064600..d5aeb522 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/EndorsementKeyCredentialsPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/EndorsementKeyCredentialsPageControllerTest.java @@ -6,8 +6,6 @@ import hirs.attestationca.persist.entity.userdefined.Certificate; import hirs.attestationca.persist.entity.userdefined.certificate.EndorsementCredential; import hirs.attestationca.portal.page.PageControllerTest; import hirs.attestationca.portal.page.PageMessages; -import java.io.IOException; -import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -18,8 +16,14 @@ import org.springframework.test.annotation.Rollback; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.servlet.FlashMap; + +import java.io.IOException; +import java.util.List; + import static hirs.attestationca.portal.page.Page.ENDORSEMENT_KEY_CREDENTIALS; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.annotation.DirtiesContext.MethodMode.BEFORE_METHOD; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -29,21 +33,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class EndorsementKeyCredentialsPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - - // Repository manager to handle data access between endorsement certificate entity and data storage in db - @Autowired - private EndorsementCredentialRepository endorsementCredentialRepository; - // Location of test certs private static final String EKCERT = "certificates/fakeIntelIntermediateCA.pem"; private static final String BADEKCERT = "certificates/badCert.pem"; - + // Base path for the page + private String pagePath; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; + // Repository manager to handle data access between endorsement certificate entity and data storage in db + @Autowired + private EndorsementCredentialRepository endorsementCredentialRepository; // A file that contains a cert that is not an EK Cert. Should be parsable as a general cert, // but should (eventually) not be stored as an EK because it isn't one. private MockMultipartFile nonEkCertFile; @@ -60,6 +60,7 @@ public class EndorsementKeyCredentialsPageControllerTest extends PageControllerT /** * Prepares tests. + * * @throws IOException if test resources are not found */ @BeforeAll @@ -79,6 +80,7 @@ public class EndorsementKeyCredentialsPageControllerTest extends PageControllerT * Tests uploading a cert that is not an Endorsement Credential. Eventually, this * should indicate a failure, but for now, EndorsementCredential just parses it as a * generic credential successfully. + * * @throws Exception if an exception occurs */ @Test @@ -128,13 +130,14 @@ public class EndorsementKeyCredentialsPageControllerTest extends PageControllerT /** * Tests that uploading something that is not a cert at all results in an error returned * to the web client. + * * @throws Exception an exception occurs */ @Test @Rollback @DirtiesContext(methodMode = BEFORE_METHOD) // clear endorsement cert from db public void uploadBadEndorsementCert() throws Exception { - + // perform upload. Attach csv file and add HTTP parameters for the baseline name and type. MvcResult result = getMockMvc().perform(MockMvcRequestBuilders .multipart(pagePath + "/upload") diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/IssuedCertificatesPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/IssuedCertificatesPageControllerTest.java index d3fd2cbc..1001f286 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/IssuedCertificatesPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/IssuedCertificatesPageControllerTest.java @@ -9,22 +9,23 @@ import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredent import hirs.attestationca.persist.enums.AppraisalStatus; import hirs.attestationca.persist.enums.HealthStatus; import hirs.attestationca.portal.page.PageControllerTest; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.Rollback; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + import static hirs.attestationca.portal.page.Page.ISSUED_CERTIFICATES; import static org.hamcrest.Matchers.hasSize; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Integration tests that test the URL End Points of IssuedCertificatesPageController. @@ -32,20 +33,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class IssuedCertificatesPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Fake device to store in db for test - private Device device; - - // Repository manager to handle data access between device entity and data storage in db - @Autowired - private DeviceRepository deviceRepository; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - // Location of test certs private static final String TEST_ENDORSEMENT_CREDENTIAL = "/endorsement_credentials/tpmcert.pem"; @@ -55,7 +42,16 @@ public class IssuedCertificatesPageControllerTest extends PageControllerTest { = "/platform_credentials/Intel_pc2.pem"; private static final String ISSUED_CLIENT_CERT = "/certificates/sample_identity_cert.cer"; - + // Base path for the page + private String pagePath; + // Fake device to store in db for test + private Device device; + // Repository manager to handle data access between device entity and data storage in db + @Autowired + private DeviceRepository deviceRepository; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; // Certs objects private List platformCredentialList; private IssuedAttestationCertificate issued; @@ -71,14 +67,15 @@ public class IssuedCertificatesPageControllerTest extends PageControllerTest { /** * Prepares a testing environment. + * * @throws IOException if there is a problem constructing the test certificate */ @BeforeAll public void beforeMethod() throws IOException { // Create new device to be used in test and save it to db - device = new Device("Test Device",null, HealthStatus.TRUSTED, AppraisalStatus.Status.PASS, - null,false,"temp", "temp"); + device = new Device("Test Device", null, HealthStatus.TRUSTED, AppraisalStatus.Status.PASS, + null, false, "temp", "temp"); device = deviceRepository.save(device); // Upload and save EK Cert @@ -148,6 +145,7 @@ public class IssuedCertificatesPageControllerTest extends PageControllerTest { /** * Tests downloading the certificate. + * * @throws Exception when getting raw report */ @Test diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PlatformCredentialsPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PlatformCredentialsPageControllerTest.java index c7fd0f1a..94270880 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PlatformCredentialsPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PlatformCredentialsPageControllerTest.java @@ -4,6 +4,8 @@ import hirs.attestationca.persist.entity.manager.CertificateRepository; import hirs.attestationca.persist.entity.userdefined.Certificate; import hirs.attestationca.portal.page.PageControllerTest; import hirs.attestationca.portal.page.PageMessages; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.mock.web.MockMultipartFile; @@ -12,14 +14,14 @@ import org.springframework.test.annotation.Rollback; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.servlet.FlashMap; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import static hirs.attestationca.portal.page.Page.PLATFORM_CREDENTIALS; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** @@ -28,18 +30,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class PlatformCredentialsPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - // Location of test certs private static final String REALPCCERT = "platform_credentials/Intel_pc.cer"; private static final String NONPCCERT = "certificates/fakeIntelIntermediateCA.pem"; private static final String BADPCCERT = "certificates/badCert.pem"; - + // Base path for the page + private String pagePath; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; // A cert that is an actual PC cert file and should be parsable. private MockMultipartFile realPcCertFile; @@ -60,6 +59,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Prepares tests. + * * @throws IOException if test resources are not found */ @BeforeAll @@ -83,6 +83,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Tests uploading a cert that is a Platform Credential, and archiving it. + * * @throws Exception if an exception occurs */ @Test @@ -94,6 +95,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Uploads test cert to db + * * @return the cert that was uploaded * @throws Exception if an exception occurs */ @@ -126,6 +128,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Archives test cert that is in db by setting the archive flag + * * @throws Exception if an exception occurs */ private void archiveTestCert(final Certificate cert) throws Exception { @@ -147,6 +150,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Tests that uploading a certificate when an identical certificate is archived will cause * the existing certificate to be unarchived and updated. + * * @throws Exception if an exception occurs */ @Test @@ -171,7 +175,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { assertEquals(1, pageMessages.getSuccess().size()); assertEquals(0, pageMessages.getError().size()); assertEquals("Pre-existing certificate found and unarchived (" - + pathTokens[1] + "): ", + + pathTokens[1] + "): ", pageMessages.getSuccess().get(0)); // verify there is still only one cert in db @@ -189,6 +193,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Tests uploading a cert that is not a Platform Credential, which results in failure. + * * @throws Exception if an exception occurs */ @Test @@ -222,6 +227,7 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest { /** * Tests that uploading something that is not a cert at all results in an error returned * to the web client. + * * @throws Exception an exception occurs */ @Test diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PolicyPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PolicyPageControllerTest.java index e551eeba..5f785b79 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PolicyPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/PolicyPageControllerTest.java @@ -11,9 +11,15 @@ import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static hirs.attestationca.portal.page.Page.POLICY; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Integration tests that test the URL End Points of PolicyPageController. @@ -32,7 +38,6 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Constructor requiring the Page's display and routing specification. - * */ public PolicyPageControllerTest() { super(POLICY); @@ -229,6 +234,7 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Verifies the rest call for disabling the PC Validation policy setting. + * * @throws Exception if test fails */ @Test @@ -338,6 +344,7 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Verifies the rest call for disabling the PC attribute validation policy setting. + * * @throws Exception if test fails */ @Test @@ -381,7 +388,7 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Helper function to set policy member variable - PC Validation to True - * Note: to set PC Validation to true, EC Validation must also be true + * Note: to set PC Validation to true, EC Validation must also be true * * @return void */ @@ -392,7 +399,7 @@ public class PolicyPageControllerTest extends PageControllerTest { /** * Helper function to set policy member variable - PC Attribute Validation to True - * Note: to set PC Attribute Validation to true, PC Validation must also be true + * Note: to set PC Attribute Validation to true, PC Validation must also be true * * @return void */ diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/TrustChainManagementPageControllerTest.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/TrustChainManagementPageControllerTest.java index 4cef7ef7..5a06b2c5 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/TrustChainManagementPageControllerTest.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/TrustChainManagementPageControllerTest.java @@ -21,7 +21,9 @@ import java.util.List; import static hirs.attestationca.portal.page.Page.TRUST_CHAIN; import static org.hamcrest.Matchers.hasEntry; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; @@ -33,20 +35,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class TrustChainManagementPageControllerTest extends PageControllerTest { - // Base path for the page - private String pagePath; - - // Repository manager to handle data access between certificate entity and data storage in db - @Autowired - private CertificateRepository certificateRepository; - - @Autowired - private X509Certificate acaCert; - // Location of test certs private static final String NONCACERT = "certificates/fakeIntelIntermediateCA.pem"; private static final String BADCERT = "certificates/badCert.pem"; - + // Base path for the page + private String pagePath; + // Repository manager to handle data access between certificate entity and data storage in db + @Autowired + private CertificateRepository certificateRepository; + @Autowired + private X509Certificate acaCert; // A file that contains a cert that is not an UTC Cert. Should be parsable as a general // cert, but should (eventually) not be stored as an UTC because it isn't one. private MockMultipartFile nonCaCertFile; @@ -66,6 +64,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Prepares tests. + * * @throws IOException if test resources are not found */ @BeforeAll @@ -121,6 +120,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Tests downloading the certificate. + * * @throws Exception when getting raw report */ @Test @@ -153,6 +153,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { * Currently this test may pass certs that meet some, but not all requirements * However the underlying code is looking for the basic elements of a CA certificate * generic credential successfully. + * * @throws Exception if an exception occurs */ @Test @@ -164,6 +165,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Uploads test cert to db + * * @return the cert that was uploaded * @throws Exception if an exception occurs */ @@ -181,8 +183,9 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { // verify redirection messages FlashMap flashMap = result.getFlashMap(); PageMessages pageMessages = (PageMessages) flashMap.get("messages"); - assertEquals("New certificate successfully uploaded (" + pathTokens[1] + "): ", pageMessages.getSuccess() - .get(0)); + assertEquals("New certificate successfully uploaded (" + pathTokens[1] + "): ", + pageMessages.getSuccess() + .get(0)); assertEquals(0, pageMessages.getError().size()); // verify the cert was actually stored @@ -199,6 +202,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Archives test cert that is in db by setting the archive flag + * * @throws Exception if an exception occurs */ private void archiveTestCert(final Certificate cert) throws Exception { @@ -218,6 +222,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Tests that uploading a certificate when an identical certificate is archived will cause * the existing certificate to be unarchived and updated. + * * @throws Exception if an exception occurs */ // @Test @@ -258,6 +263,7 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest { /** * Tests that uploading something that is not a cert at all results in an error returned * to the web client. + * * @throws Exception an exception occurs */ @Test diff --git a/HIRS_Utils/src/main/java/hirs/utils/rim/ReferenceManifestValidator.java b/HIRS_Utils/src/main/java/hirs/utils/rim/ReferenceManifestValidator.java index c84a70ec..306e8109 100644 --- a/HIRS_Utils/src/main/java/hirs/utils/rim/ReferenceManifestValidator.java +++ b/HIRS_Utils/src/main/java/hirs/utils/rim/ReferenceManifestValidator.java @@ -177,7 +177,7 @@ public class ReferenceManifestValidator { * @param encodedPublicKey the encoded public key * @return true if the signature element is validated, false otherwise */ - @SuppressWarnings("magicnumber") + public boolean validateXmlSignature(final PublicKey publicKey, final String subjectKeyIdString, final byte[] encodedPublicKey) {