v3_issue_811: added javadocs specific to controllers to all new controllers, fixed error/info messages display, fixed build issue and fixed checksytle issues. New code works like a charm. Need to fix platform cert bug found on main and need to finish implementing the new search feature for all the other aca pages/ individual table columns.

This commit is contained in:
ThatSilentCoder 2025-04-10 11:58:07 -04:00
parent 9d4b8eca31
commit da9fa3bd1f
20 changed files with 553 additions and 403 deletions

View File

@ -9,6 +9,7 @@ import hirs.attestationca.persist.entity.userdefined.certificate.PlatformCredent
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.ComponentIdentifier;
import hirs.attestationca.persist.entity.userdefined.certificate.attributes.V2.ComponentIdentifierV2;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
@ -65,11 +66,11 @@ public class CertificateService {
* @param <T> generic entity class
* @return page full of the generic certificates.
*/
public <T> Page<T> findBySearchableColumnsAndArchiveFlag(Class<T> entityClass,
List<String> searchableColumns,
String searchText,
Boolean archiveFlag,
Pageable pageable) {
public <T extends Certificate> Page<T> findBySearchableColumnsAndArchiveFlag(Class<T> entityClass,
List<String> searchableColumns,
String searchText,
Boolean archiveFlag,
Pageable pageable) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(entityClass);
Root<T> certificate = query.from(entityClass);
@ -105,15 +106,17 @@ public class CertificateService {
}
/**
* @param uuid
* @return
* Attempts to find a certificate whose uuid matches the provided uuid.
*
* @param uuid certificate uuid
* @return certificate
*/
public Certificate findCertificate(UUID uuid) {
return this.certificateRepository.getCertificate(uuid);
}
/**
* Stored the given certificate in the database.
* Stores the given certificate in the database.
*
* @param certificateType String containing the certificate type
* @param fileName contain the name of the file of the certificate to
@ -238,17 +241,19 @@ public class CertificateService {
* @param successMessages contains any success messages that will be displayed on the page
* @param errorMessages contains any error messages that will be displayed on the page
*/
public void deleteCertificate(UUID uuid, String certificateType,
public void deleteCertificate(final UUID uuid,
final String certificateType,
final List<String> successMessages,
final List<String> errorMessages) {
Certificate certificate = certificateRepository.getCertificate(uuid);
Certificate certificate = findCertificate(uuid);
if (certificate == null) {
// Use the term "record" here to avoid user confusion b/t cert and cred
String notFoundMessage = "Unable to locate record with ID: " + uuid;
errorMessages.add(notFoundMessage);
log.warn(notFoundMessage);
throw new EntityNotFoundException(notFoundMessage);
} else {
if (certificateType.equals(PLATFORM_CREDENTIALS)) {
PlatformCredential platformCertificate = (PlatformCredential) certificate;

View File

@ -27,7 +27,6 @@ public class Column {
@NotBlank
private String data;
/**
* Column's name.
*
@ -35,7 +34,7 @@ public class Column {
*/
@NotBlank
private String name;
/**
* Flag to indicate if this column is searchable (true) or not (false).
*

View File

@ -22,9 +22,8 @@ public class Search {
*/
@NotNull
private String value = "";
/**
* true if the global filter should be treated as a regular expression for advanced searching,
* 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
* expression searching for performance reasons on large data sets,
* but it is technically possible and at the discretion of your script.

View File

@ -1,43 +1,36 @@
package hirs.attestationca.portal.page;
import lombok.Getter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Encapsulates error, success, and informational messages to display on a page.
*/
@Getter
public class PageMessages {
private final List<String> error = new ArrayList<>();
private final List<String> success = new ArrayList<>();
private final List<String> info = new ArrayList<>();
/**
* Returns the list of error messages.
*
* @return the list of error messages.
*/
public List<String> getError() {
return Collections.unmodifiableList(error);
}
private final List<String> errorMessages = new ArrayList<>();
private final List<String> successMessages = new ArrayList<>();
private final List<String> infoMessages = new ArrayList<>();
/**
* Adds an error message.
*
* @param error the error message to add
*/
public void addError(final String error) {
this.error.add(error);
public void addErrorMessage(final String error) {
this.errorMessages.add(error);
}
/**
* Returns the list of success messages.
* Adds multiple error messages.
*
* @return the list of success messages.
* @param multipleErrors list of error messages
*/
public List<String> getSuccess() {
return Collections.unmodifiableList(success);
public void addErrorMessages(final List<String> multipleErrors) {
this.errorMessages.addAll(multipleErrors);
}
/**
@ -45,17 +38,17 @@ public class PageMessages {
*
* @param success the success message to add
*/
public void addSuccess(final String success) {
this.success.add(success);
public void addSuccessMessage(final String success) {
this.successMessages.add(success);
}
/**
* Returns the list of informational messages.
* Adds multiple success messages.
*
* @return the list of informational messages.
* @param multipleSuccessMessages list of success messages to add
*/
public List<String> getInfo() {
return Collections.unmodifiableList(info);
public void addSuccessMessages(final List<String> multipleSuccessMessages) {
this.successMessages.addAll(multipleSuccessMessages);
}
/**
@ -63,8 +56,16 @@ public class PageMessages {
*
* @param info the informational message to add
*/
public void addInfo(final String info) {
this.info.add(info);
public void addInfoMessage(final String info) {
this.infoMessages.add(info);
}
/**
* Adds multiple informational messages.
*
* @param multipleInfoMessages list of informational messages to add
*/
public void addInfoMessages(final List<String> multipleInfoMessages) {
this.errorMessages.addAll(multipleInfoMessages);
}
}

View File

@ -77,12 +77,12 @@ public class CertificateDetailsPageController extends PageController<Certificate
// Check if parameters were set
if (params.getId() == null) {
String typeError = "ID was not provided";
messages.addError(typeError);
messages.addErrorMessage(typeError);
log.error(typeError);
mav.addObject(MESSAGES_ATTRIBUTE, messages);
} else if (params.getType() == null) {
String typeError = "Type was not provided";
messages.addError(typeError);
messages.addErrorMessage(typeError);
log.error(typeError);
mav.addObject(MESSAGES_ATTRIBUTE, messages);
} else {
@ -112,20 +112,20 @@ public class CertificateDetailsPageController extends PageController<Certificate
break;
default:
String typeError = "Invalid certificate type: " + params.getType();
messages.addError(typeError);
messages.addErrorMessage(typeError);
log.error(typeError);
mav.addObject(MESSAGES_ATTRIBUTE, messages);
break;
}
} catch (IllegalArgumentException | IOException ex) {
String uuidError = "Failed to parse ID from: " + params.getId();
messages.addError(uuidError);
messages.addErrorMessage(uuidError);
log.error(uuidError, ex);
}
if (data.isEmpty()) {
String notFoundMessage = "Unable to find certificate with ID: " + params.getId();
messages.addError(notFoundMessage);
messages.addErrorMessage(notFoundMessage);
log.warn(notFoundMessage);
mav.addObject(MESSAGES_ATTRIBUTE, messages);
} else {

View File

@ -97,7 +97,7 @@ public class DevicePageController extends PageController<NoPageParams> {
produces = MediaType.APPLICATION_JSON_VALUE)
public DataTableResponse<HashMap<String, Object>> getTableData(
final DataTableInput input) {
log.debug("Handling request for device list");
log.debug("Receiving request to for device list");
String orderColumnName = input.getOrderColumnName();
log.debug("Ordering on column: {}", orderColumnName);

View File

@ -1,6 +1,5 @@
package hirs.attestationca.portal.page.controllers;
import hirs.attestationca.persist.DBManagerException;
import hirs.attestationca.persist.FilteredRecordsList;
import hirs.attestationca.persist.entity.manager.EndorsementCredentialRepository;
import hirs.attestationca.persist.entity.userdefined.Certificate;
@ -13,6 +12,7 @@ import hirs.attestationca.portal.page.Page;
import hirs.attestationca.portal.page.PageController;
import hirs.attestationca.portal.page.PageMessages;
import hirs.attestationca.portal.page.params.NoPageParams;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
@ -44,6 +44,9 @@ import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;
/**
* Controller for the Endorsement Key Credentials page.
*/
@Log4j2
@Controller
@RequestMapping("/HIRS_AttestationCAPortal/portal/certificate-request/endorsement-key-credentials")
@ -54,6 +57,12 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
private final EndorsementCredentialRepository endorsementCredentialRepository;
private final CertificateService certificateService;
/**
* Constructor for the Endorsement Credential page.
*
* @param endorsementCredentialRepository endorsementCredentialRepository
* @param certificateService certificateService
*/
@Autowired
public EndorsementCredentialPageController(
final EndorsementCredentialRepository endorsementCredentialRepository,
@ -64,12 +73,12 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
}
/**
* Returns the path for the view and the data model for the page.
* Returns the path for the view and the data model for the Endorsement Key Credentials page.
*
* @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.
* @return the path for the view and data model for the Endorsement Key Credentials page.
*/
@RequestMapping
public ModelAndView initPage(
@ -78,8 +87,8 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
}
/**
* Retrieves the collection of endorsement credentials that will be displayed on the endorsement
* credentials page.
* Processes request to retrieve the collection of endorsement credentials that will be
* displayed on the endorsement credentials page.
*
* @param input data table input received from the front-end
* @return data table of endorsement credentials
@ -89,8 +98,9 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
produces = MediaType.APPLICATION_JSON_VALUE)
public DataTableResponse<EndorsementCredential> getEndorsementCredentialsTableData(
final DataTableInput input) {
log.debug("Handling list request for endorsement credentials: {}", input);
log.info("Receiving request to display list of endorsement credentials");
log.debug("Request received a datatable input object for the endorsement credentials page: {}",
input);
// attempt to get the column property based on the order index.
String orderColumnName = input.getOrderColumnName();
@ -132,10 +142,10 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
}
/**
* Handles request to download the endorsement credential by writing it to the response stream
* Processes request to download the endorsement credential by writing it to the response stream
* for download.
*
* @param id the UUID of the cert to download
* @param id the UUID of the endorsement credential to download
* @param response the response object (needed to update the header with the
* file name)
* @throws IOException when writing to response output stream
@ -145,41 +155,50 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
@RequestParam final String id,
final HttpServletResponse response)
throws IOException {
log.info("Handling request to download endorsement credential id {}", id);
log.info("Receiving request to download endorsement credential id {}", id);
try {
UUID uuid = UUID.fromString(id);
Certificate certificate = this.certificateService.findCertificate(uuid);
if (certificate == null) {
// Use the term "record" here to avoid user confusion b/t cert and cred
String notFoundMessage = "Unable to locate record with ID: " + uuid;
log.warn(notFoundMessage);
// send a 404 error when invalid certificate
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else if (certificate instanceof EndorsementCredential uploadedEndorsementCredential) {
String fileName = "filename=\"" + EndorsementCredential.class.getSimpleName()
+ "_"
+ uploadedEndorsementCredential.getSerialNumber()
+ ".cer\"";
final String errorMessage = "Unable to locate endorsement credential record with ID " + uuid;
log.warn(errorMessage);
throw new EntityNotFoundException(errorMessage);
} else if (!(certificate instanceof EndorsementCredential)) {
final String errorMessage =
"Unable to cast the found certificate to a endorsement credential object";
log.warn(errorMessage);
throw new ClassCastException(errorMessage);
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write cert to output stream
response.getOutputStream().write(certificate.getRawBytes());
}
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from: " + id;
log.error(uuidError, ex);
// send a 404 error when invalid certificate
final EndorsementCredential endorsementCredential = (EndorsementCredential) certificate;
final String fileName = "filename=\"" + EndorsementCredential.class.getSimpleName()
+ "_"
+ endorsementCredential.getSerialNumber()
+ ".cer\"";
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write endorsement credential to output stream
response.getOutputStream().write(certificate.getRawBytes());
} catch (Exception ex) {
log.error("An exception was thrown while attempting to download the"
+ " specified endorsement credential", ex);
// send a 404 error when an exception is thrown while attempting to download the
// specified endorsement credential
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Handles request to download the endorsement credentials by writing it to the response stream
* Processes request to bulk download all the endorsement credentials by writing it to the response stream
* for download in bulk.
*
* @param response the response object (needed to update the header with the
@ -189,7 +208,7 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
@GetMapping("/bulk-download")
public void bulkDownloadEndorsementCredentials(final HttpServletResponse response)
throws IOException {
log.info("Handling request to download all endorsement credentials");
log.info("Receiving request to download all endorsement credentials");
final String fileName = "endorsement_certificates.zip";
final String singleFileName = "Endorsement_Certificates";
@ -201,16 +220,18 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
// write endorsement credentials to output stream and bulk download them
this.certificateService.bulkDownloadCertificates(zipOut, ENDORSEMENT_CREDENTIALS, singleFileName);
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from: ";
log.error(uuidError, ex);
// send a 404 error when invalid certificate
} catch (Exception ex) {
log.error("An exception was thrown while attempting to bulk download all the"
+ "endorsement credentials", ex);
// send a 404 error when an exception is thrown while attempting to download the
// endorsement credentials
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Uploads and processes an endorsement credential.
* Processes request to upload one or more endorsement credentials to the ACA.
*
* @param files the files to process
* @param attr the redirection attributes
@ -222,15 +243,15 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
@RequestParam("file") final MultipartFile[] files,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to upload one or more endorsement credentials");
log.info("Receiving request to upload one or more endorsement credentials");
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
for (MultipartFile file : files) {
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
//Parse endorsement credential
EndorsementCredential parsedEndorsementCredential = parseEndorsementCredential(file, messages);
@ -240,6 +261,9 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
ENDORSEMENT_CREDENTIALS,
file.getOriginalFilename(),
successMessages, errorMessages, parsedEndorsementCredential);
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
}
}
@ -250,7 +274,7 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
}
/**
* Archives (soft deletes) the endorsement credential.
* Processes request to archive/soft delete the provided endorsement credential.
*
* @param id the UUID of the endorsement certificate to delete
* @param attr RedirectAttributes used to forward data back to the original
@ -262,28 +286,26 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
public RedirectView deleteEndorsementCredential(
@RequestParam final String id,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to delete endorsement credential id {}", id);
log.info("Receiving request to delete endorsement credential id {}", id);
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
try {
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
UUID uuid = UUID.fromString(id);
this.certificateService.deleteCertificate(uuid, ENDORSEMENT_CREDENTIALS,
successMessages, errorMessages);
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from: " + id;
messages.addError(uuidError);
log.error(uuidError, ex);
} catch (DBManagerException ex) {
String dbError = "Failed to archive cert: " + id;
messages.addError(dbError);
log.error(dbError, ex);
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
} catch (Exception exception) {
final String errorMessage = "An exception was thrown while attempting to delete"
+ " endorsement credential";
messages.addErrorMessage(errorMessage);
log.error(errorMessage, exception);
}
model.put(MESSAGES_ATTRIBUTE, messages);
@ -293,9 +315,10 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
/**
* Helper method that returns a list of column names that are searchable.
*
* @param columns columns
* @return searchable column names
*/
private List<String> findSearchableColumnsNames(List<Column> columns) {
private List<String> findSearchableColumnsNames(final List<Column> columns) {
// Retrieve all searchable columns and collect their names into a list of strings.
return columns.stream().filter(Column::isSearchable).map(Column::getName)
@ -310,7 +333,8 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
* @param messages page messages
* @return endorsement credential
*/
private EndorsementCredential parseEndorsementCredential(MultipartFile file, PageMessages messages) {
private EndorsementCredential parseEndorsementCredential(final MultipartFile file,
final PageMessages messages) {
log.info("Received endorsement credential file of size: {}", file.getSize());
byte[] fileBytes;
@ -323,7 +347,7 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
final String failMessage = String.format(
"Failed to read uploaded endorsement credential file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
return null;
}
@ -334,25 +358,25 @@ public class EndorsementCredentialPageController extends PageController<NoPagePa
final String failMessage = String.format(
"Failed to parse uploaded endorsement credential file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
return null;
} catch (DecoderException dEx) {
final String failMessage = String.format(
"Failed to parse uploaded endorsement credential pem file (%s): ", fileName);
log.error(failMessage, dEx);
messages.addError(failMessage + dEx.getMessage());
messages.addErrorMessage(failMessage + dEx.getMessage());
return null;
} catch (IllegalArgumentException iaEx) {
final String failMessage = String.format(
"Endorsement credential format not recognized(%s): ", fileName);
log.error(failMessage, iaEx);
messages.addError(failMessage + iaEx.getMessage());
messages.addErrorMessage(failMessage + iaEx.getMessage());
return null;
} catch (IllegalStateException isEx) {
final String failMessage = String.format(
"Unexpected object while parsing endorsement credential %s ", fileName);
log.error(failMessage, isEx);
messages.addError(failMessage + isEx.getMessage());
messages.addErrorMessage(failMessage + isEx.getMessage());
return null;
}
}

View File

@ -1,6 +1,5 @@
package hirs.attestationca.portal.page.controllers;
import hirs.attestationca.persist.DBManagerException;
import hirs.attestationca.persist.FilteredRecordsList;
import hirs.attestationca.persist.entity.manager.IDevIDCertificateRepository;
import hirs.attestationca.persist.entity.userdefined.Certificate;
@ -13,6 +12,7 @@ import hirs.attestationca.portal.page.Page;
import hirs.attestationca.portal.page.PageController;
import hirs.attestationca.portal.page.PageMessages;
import hirs.attestationca.portal.page.params.NoPageParams;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
@ -44,6 +44,9 @@ import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;
/**
* Controller for the IDevID Certificates page.
*/
@Log4j2
@Controller
@RequestMapping("/HIRS_AttestationCAPortal/portal/certificate-request/idevid-certificates")
@ -54,6 +57,12 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
private final IDevIDCertificateRepository iDevIDCertificateRepository;
private final CertificateService certificateService;
/**
* Constructor for the IDevID Certificate page.
*
* @param iDevIDCertificateRepository iDevIDCertificateRepository
* @param certificateService certificateService
*/
@Autowired
public IDevIdCertificatePageController(final IDevIDCertificateRepository iDevIDCertificateRepository,
final CertificateService certificateService) {
@ -63,12 +72,12 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
}
/**
* Returns the path for the view and the data model for the page.
* Returns the path for the view and the data model for the IDevId Certificate page.
*
* @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.
* @return the path for the view and data model for the IDevId Certificate page.
*/
@RequestMapping
public ModelAndView initPage(
@ -77,8 +86,8 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
}
/**
* Retrieves the collection of idevid certificates that will be displayed on the idevid certificates
* page.
* Processes request to retrieve the collection of idevid certificates that will
* be displayed on the idevid certificates page.
*
* @param input data table input received from the front-end
* @return data table of idevid certificates
@ -89,7 +98,8 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
public DataTableResponse<IDevIDCertificate> getIDevIdCertificatesTableData(
final DataTableInput input) {
log.debug("Handling list request for idevid certificates: {}", input);
log.info("Receiving request to display list of idevid certificates");
log.debug("Request received a datatable input object for the idevid certificates page: {}", input);
// attempt to get the column property based on the order index.
String orderColumnName = input.getOrderColumnName();
@ -126,15 +136,15 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
records.setRecordsFiltered(iDevIDCertificateRepository.findByArchiveFlag(false).size());
log.debug("Returning the size of the list of IDEVID certificates: {}", records.size());
log.info("Returning the size of the list of IDEVID certificates: {}", records.size());
return new DataTableResponse<>(records, input);
}
/**
* Handles request to download the IDevId certificate by writing it to the response stream
* Processes request to download the IDevId certificate by writing it to the response stream
* for download.
*
* @param id the UUID of the cert to download
* @param id the UUID of the idevid certificate to download
* @param response the response object (needed to update the header with the
* file name)
* @throws IOException when writing to response output stream
@ -144,41 +154,48 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
@RequestParam final String id,
final HttpServletResponse response)
throws IOException {
log.info("Handling request to download idevid certificate id {}", id);
log.info("Receiving request to download idevid certificate id {}", id);
try {
UUID uuid = UUID.fromString(id);
Certificate certificate = this.certificateService.findCertificate(uuid);
if (certificate == null) {
// Use the term "record" here to avoid user confusion b/t cert and cred
String notFoundMessage = "Unable to locate record with ID: " + uuid;
log.warn(notFoundMessage);
// send a 404 error when invalid certificate
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else if (certificate instanceof IDevIDCertificate uploadedIDevIdCertificate) {
String fileName = "filename=\"" + IDevIDCertificate.class.getSimpleName()
+ "_"
+ uploadedIDevIdCertificate.getSerialNumber()
+ ".cer\"";
final String errorMessage = "Unable to locate idevid certificate record with ID " + uuid;
log.warn(errorMessage);
throw new EntityNotFoundException(errorMessage);
} else if (!(certificate instanceof IDevIDCertificate)) {
final String errorMessage =
"Unable to cast the found certificate to a idevid certificate object";
log.warn(errorMessage);
throw new ClassCastException(errorMessage);
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write cert to output stream
response.getOutputStream().write(certificate.getRawBytes());
}
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from: " + id;
log.error(uuidError, ex);
// send a 404 error when invalid certificate
final IDevIDCertificate iDevIDCertificate = (IDevIDCertificate) certificate;
final String fileName = "filename=\"" + IDevIDCertificate.class.getSimpleName()
+ "_"
+ iDevIDCertificate.getSerialNumber()
+ ".cer\"";
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write idevid certificate to output stream
response.getOutputStream().write(certificate.getRawBytes());
} catch (Exception ex) {
log.error("An exception was thrown while attempting to download the"
+ " specified idevid certificate", ex);
// send a 404 error when an exception is thrown while attempting to download the
// specified idevid certificate
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Handles request to download the IDevID Certificates by writing it to the response stream
* Processes request to bulk download all the IDevID Certificates by writing it to the response stream
* for download in bulk.
*
* @param response the response object (needed to update the header with the
@ -188,7 +205,7 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
@GetMapping("/bulk-download")
public void bulkDownloadIDevIdCertificates(final HttpServletResponse response)
throws IOException {
log.info("Handling request to download all idevid certificates");
log.info("Receiving request to download all idevid certificates");
final String fileName = "idevid_certificates.zip";
final String singleFileName = "IDevID_Certificates";
@ -200,16 +217,18 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
// write idevid certificates to output stream and bulk download them
this.certificateService.bulkDownloadCertificates(zipOut, IDEVID_CERTIFICATE, singleFileName);
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from: ";
log.error(uuidError, ex);
// send a 404 error when invalid certificate
} catch (Exception ex) {
log.error("An exception was thrown while attempting to bulk download all the"
+ "idevid certificates", ex);
// send a 404 error when an exception is thrown while attempting to download the
// specified platform credential
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Uploads and processes an idevid certificate.
* Processes request to upload one or more idevid certificates to the ACA.
*
* @param files the files to process
* @param attr the redirection attributes
@ -221,15 +240,15 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
@RequestParam("file") final MultipartFile[] files,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to upload one or more idevid certificates");
log.info("Receiving request to upload one or more idevid certificates");
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
for (MultipartFile file : files) {
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
//Parse IDevId Certificate
IDevIDCertificate parsedIDevIDCertificate =
parseIDevIDCertificate(file, messages);
@ -240,6 +259,9 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
IDEVID_CERTIFICATE,
file.getOriginalFilename(),
successMessages, errorMessages, parsedIDevIDCertificate);
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
}
}
@ -250,7 +272,7 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
}
/**
* Archives (soft deletes) the idevid certificate.
* Processes request to archive/soft delete the provided idevid certificate.
*
* @param id the UUID of the idevid certificate to delete
* @param attr RedirectAttributes used to forward data back to the original
@ -262,28 +284,27 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
public RedirectView deleteIdevIdCertificate(
@RequestParam final String id,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to delete idevid id {}", id);
log.info("Receiving request to delete idevid certificate id {}", id);
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
try {
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
try {
UUID uuid = UUID.fromString(id);
this.certificateService.deleteCertificate(uuid, IDEVID_CERTIFICATE,
successMessages, errorMessages);
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from idevid certificate: " + id;
messages.addError(uuidError);
log.error(uuidError, ex);
} catch (DBManagerException ex) {
String dbError = "Failed to archive idevid certificate: " + id;
messages.addError(dbError);
log.error(dbError, ex);
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
} catch (Exception exception) {
final String errorMessage = "An exception was thrown while attempting to delete"
+ " the specified idevid certificate";
messages.addErrorMessage(errorMessage);
log.error(errorMessage, exception);
}
model.put(MESSAGES_ATTRIBUTE, messages);
@ -293,9 +314,10 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
/**
* Helper method that returns a list of column names that are searchable.
*
* @param columns columns
* @return searchable column names
*/
private List<String> findSearchableColumnsNames(List<Column> columns) {
private List<String> findSearchableColumnsNames(final List<Column> columns) {
// Retrieve all searchable columns and collect their names into a list of strings.
return columns.stream().filter(Column::isSearchable).map(Column::getName)
@ -309,8 +331,8 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
* @param messages page messages
* @return IDevId certificate
*/
private IDevIDCertificate parseIDevIDCertificate(MultipartFile file,
PageMessages messages) {
private IDevIDCertificate parseIDevIDCertificate(final MultipartFile file,
final PageMessages messages) {
log.info("Received IDevId certificate file of size: {}", file.getSize());
byte[] fileBytes;
@ -323,7 +345,7 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
final String failMessage = String.format(
"Failed to read uploaded IDevId certificate file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
return null;
}
@ -334,25 +356,25 @@ public class IDevIdCertificatePageController extends PageController<NoPageParams
final String failMessage = String.format(
"Failed to parse uploaded IDevId certificate file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
return null;
} catch (DecoderException dEx) {
final String failMessage = String.format(
"Failed to parse uploaded IDevId certificate pem file (%s): ", fileName);
log.error(failMessage, dEx);
messages.addError(failMessage + dEx.getMessage());
messages.addErrorMessage(failMessage + dEx.getMessage());
return null;
} catch (IllegalArgumentException iaEx) {
final String failMessage = String.format(
"IDevId certificate format not recognized(%s): ", fileName);
log.error(failMessage, iaEx);
messages.addError(failMessage + iaEx.getMessage());
messages.addErrorMessage(failMessage + iaEx.getMessage());
return null;
} catch (IllegalStateException isEx) {
final String failMessage = String.format(
"Unexpected object while parsing IDevId certificate %s ", fileName);
log.error(failMessage, isEx);
messages.addError(failMessage + isEx.getMessage());
messages.addErrorMessage(failMessage + isEx.getMessage());
return null;
}
}

View File

@ -1,6 +1,5 @@
package hirs.attestationca.portal.page.controllers;
import hirs.attestationca.persist.DBManagerException;
import hirs.attestationca.persist.FilteredRecordsList;
import hirs.attestationca.persist.entity.manager.IssuedCertificateRepository;
import hirs.attestationca.persist.entity.userdefined.Certificate;
@ -13,6 +12,7 @@ import hirs.attestationca.portal.page.Page;
import hirs.attestationca.portal.page.PageController;
import hirs.attestationca.portal.page.PageMessages;
import hirs.attestationca.portal.page.params.NoPageParams;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
@ -42,6 +42,9 @@ import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;
/**
* Controller for the Issued Certificates page.
*/
@Log4j2
@Controller
@RequestMapping("/HIRS_AttestationCAPortal/portal/certificate-request/issued-certificates")
@ -52,6 +55,12 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
private final IssuedCertificateRepository issuedCertificateRepository;
private final CertificateService certificateService;
/**
* Constructor for the Issued Attestation Certificate page.
*
* @param issuedCertificateRepository issuedCertificateRepository
* @param certificateService certificateService
*/
@Autowired
public IssuedCertificateController(
final IssuedCertificateRepository issuedCertificateRepository,
@ -67,7 +76,7 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
* @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.
* @return the path for the view and data model for the Issued Attestation Certificate page.
*/
@RequestMapping
public ModelAndView initPage(
@ -76,15 +85,20 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
}
/**
* @param input
* @return
* Processes request to retrieve the collection of issued attestation certificates
* that will be displayed on the issued certificates page.
*
* @param input data table input received from the front-end
* @return data table of issued certificates
*/
@ResponseBody
@GetMapping(value = "/list",
produces = MediaType.APPLICATION_JSON_VALUE)
public DataTableResponse<IssuedAttestationCertificate> getIssuedCertificatesTableData(
final DataTableInput input) {
log.debug("Handling list request for issued certificates: {}", input);
log.info("Receiving request to display list of issued attestation certificates");
log.debug("Request received a datatable input object for the issued attestation certificate page: "
+ "{}", input);
// attempt to get the column property based on the order index.
String orderColumnName = input.getOrderColumnName();
@ -121,12 +135,12 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
records.setRecordsFiltered(issuedCertificateRepository.findByArchiveFlag(false).size());
log.debug("Returning the size of the list of issued certificates: {}", records.size());
log.info("Returning the size of the list of issued certificates: {}", records.size());
return new DataTableResponse<>(records, input);
}
/**
* Handles request to download the issued attestation certificate by writing it to the response stream
* Processes request to download the issued attestation certificate by writing it to the response stream
* for download.
*
* @param id the UUID of the issued attestation certificate to download
@ -139,42 +153,53 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
@RequestParam final String id,
final HttpServletResponse response)
throws IOException {
log.info("Handling request to download issued certificate id {}", id);
log.info("Receiving request to download issued certificate id {}", id);
try {
UUID uuid = UUID.fromString(id);
Certificate certificate = this.certificateService.findCertificate(uuid);
if (certificate == null) {
// Use the term "record" here to avoid user confusion b/t cert and cred
String notFoundMessage = "Unable to locate record with ID: " + uuid;
log.warn(notFoundMessage);
// send a 404 error when invalid certificate
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else if (certificate instanceof IssuedAttestationCertificate uploadedIssuedCertificate) {
String fileName = "filename=\"" + IssuedAttestationCertificate.class.getSimpleName()
+ "_"
+ uploadedIssuedCertificate.getSerialNumber()
+ ".cer\"";
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write cert to output stream
response.getOutputStream().write(certificate.getRawBytes());
final String errorMessage =
"Unable to locate issued attestation certificate record with ID " + uuid;
log.warn(errorMessage);
throw new EntityNotFoundException(errorMessage);
} else if (!(certificate instanceof IssuedAttestationCertificate)) {
final String errorMessage =
"Unable to cast the found certificate to an issued attestation certificate "
+ "object";
log.warn(errorMessage);
throw new ClassCastException(errorMessage);
}
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from: " + id;
log.error(uuidError, ex);
// send a 404 error when invalid certificate
final IssuedAttestationCertificate issuedAttestationCertificate =
(IssuedAttestationCertificate) certificate;
final String fileName = "filename=\"" + IssuedAttestationCertificate.class.getSimpleName()
+ "_"
+ issuedAttestationCertificate.getSerialNumber()
+ ".cer\"";
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write issued certificate to output stream
response.getOutputStream().write(certificate.getRawBytes());
} catch (Exception ex) {
log.error("An exception was thrown while attempting to download the"
+ " specified issued attestation certificate", ex);
// send a 404 error when an exception is thrown while attempting to download the
// specified issued attestation certificate
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Handles request to download the issued attestation certificates by writing it to the response stream
* for download in bulk.
* Processes request to bulk download all the issued attestation certificates by writing it
* to the response stream for download in bulk.
*
* @param response the response object (needed to update the header with the
* file name)
@ -183,7 +208,7 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
@GetMapping("/bulk-download")
public void bulkDownloadIssuedCertificates(final HttpServletResponse response)
throws IOException {
log.info("Handling request to download all issued certificates");
log.info("Receiving request to download all issued certificates");
final String singleFileName = "Issued_Certificate";
final String fileName = "issued_certificates.zip";
@ -196,14 +221,17 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
// write issued attestation certificates to output stream and bulk download them
this.certificateService.bulkDownloadCertificates(zipOut, ISSUED_CERTIFICATES, singleFileName);
} catch (Exception ex) {
log.error("Failed to bulk download issued certificates:", ex);
// send a 404 error when invalid certificate
log.error("An exception was thrown while attempting to bulk download all the"
+ "issued attestation certificates", ex);
// send a 404 error when an exception is thrown while attempting to download the
// issued attestation certificates
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Archives (soft deletes) the issued attestation certificate.
* Processes request to archive/soft delete the provided issued attestation certificate.
*
* @param id the UUID of the issued attestation certificate to delete
* @param attr RedirectAttributes used to forward data back to the original
@ -215,28 +243,27 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
public RedirectView deleteIssuedCertificate(
@RequestParam final String id,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to delete issued attestation certificate id {}", id);
log.info("Receiving request to delete issued attestation certificate id {}", id);
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
try {
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
try {
UUID uuid = UUID.fromString(id);
this.certificateService.deleteCertificate(uuid, ISSUED_CERTIFICATES,
successMessages, errorMessages);
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from issued attestation certificate: " + id;
messages.addError(uuidError);
log.error(uuidError, ex);
} catch (DBManagerException ex) {
String dbError = "Failed to archive issued attestation certificate: " + id;
messages.addError(dbError);
log.error(dbError, ex);
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
} catch (Exception exception) {
final String errorMessage = "An exception was thrown while attempting to delete"
+ " the specified issued attestation certificate";
messages.addErrorMessage(errorMessage);
log.error(errorMessage, exception);
}
model.put(MESSAGES_ATTRIBUTE, messages);
@ -246,9 +273,10 @@ public class IssuedCertificateController extends PageController<NoPageParams> {
/**
* Helper method that returns a list of column names that are searchable.
*
* @param columns columns
* @return searchable column names
*/
private List<String> findSearchableColumnsNames(List<Column> columns) {
private List<String> findSearchableColumnsNames(final List<Column> columns) {
// Retrieve all searchable columns and collect their names into a list of strings.
return columns.stream().filter(Column::isSearchable).map(Column::getName)

View File

@ -1,6 +1,5 @@
package hirs.attestationca.portal.page.controllers;
import hirs.attestationca.persist.DBManagerException;
import hirs.attestationca.persist.FilteredRecordsList;
import hirs.attestationca.persist.entity.manager.EndorsementCredentialRepository;
import hirs.attestationca.persist.entity.manager.PlatformCertificateRepository;
@ -15,6 +14,7 @@ import hirs.attestationca.portal.page.Page;
import hirs.attestationca.portal.page.PageController;
import hirs.attestationca.portal.page.PageMessages;
import hirs.attestationca.portal.page.params.NoPageParams;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
@ -46,6 +46,9 @@ import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;
/**
* Controller for the Platform Credentials page.
*/
@Log4j2
@Controller
@RequestMapping("/HIRS_AttestationCAPortal/portal/certificate-request/platform-credentials")
@ -57,6 +60,13 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
private final EndorsementCredentialRepository endorsementCredentialRepository;
private final CertificateService certificateService;
/**
* Constructor for the Platform Credential page.
*
* @param platformCertificateRepository platformCertificateRepository
* @param endorsementCredentialRepository endorsementCredentialRepository
* @param certificateService certificateService
*/
@Autowired
public PlatformCredentialPageController(
final PlatformCertificateRepository platformCertificateRepository,
@ -69,12 +79,12 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
}
/**
* Returns the path for the view and the data model for the page.
* Returns the path for the view and the data model for the platform credential page.
*
* @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.
* @return the path for the view and data model for the platform credential page.
*/
@RequestMapping
public ModelAndView initPage(
@ -83,8 +93,8 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
}
/**
* Retrieves the collection of platform credentials that will be displayed on the platform
* credentials page.
* Processes request to retrieve the collection of platform credentials that will be displayed
* on the platform credentials page.
*
* @param input data table input received from the front-end
* @return data table of platform credentials
@ -94,8 +104,8 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
produces = MediaType.APPLICATION_JSON_VALUE)
public DataTableResponse<PlatformCredential> getPlatformCredentialsTableData(
final DataTableInput input) {
log.debug("Handling list request for platform credentials: {}", input);
log.info("Receiving request to display list of platform credentials");
log.debug("Request received a datatable input object for the platform credentials page: {}", input);
// attempt to get the column property based on the order index.
String orderColumnName = input.getOrderColumnName();
@ -151,12 +161,12 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
}
}
log.debug("Returning the size of the list of platform credentials: {}", records.size());
log.info("Returning the size of the list of platform credentials: {}", records.size());
return new DataTableResponse<>(records, input);
}
/**
* Handles request to download the platform credential by writing it to the response stream
* Processes request to download the platform credential by writing it to the response stream
* for download.
*
* @param id the UUID of the platform credential to download
@ -169,41 +179,50 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
@RequestParam final String id,
final HttpServletResponse response)
throws IOException {
log.info("Handling request to download platform credential id {}", id);
log.info("Receiving request to download platform credential id {}", id);
try {
UUID uuid = UUID.fromString(id);
Certificate certificate = this.certificateService.findCertificate(uuid);
if (certificate == null) {
log.warn("Unable to locate platform credential record with ID: {}", uuid);
// send a 404 error when invalid certificate
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
if (certificate instanceof PlatformCredential uploadedPlatformCredential) {
final String errorMessage = "Unable to locate platform credential record with ID " + uuid;
log.warn(errorMessage);
throw new EntityNotFoundException(errorMessage);
} else if (!(certificate instanceof PlatformCredential)) {
final String errorMessage =
"Unable to cast the found certificate to a platform credential object";
log.warn(errorMessage);
throw new ClassCastException(errorMessage);
String fileName = "filename=\"" + PlatformCredential.class.getSimpleName()
+ "_"
+ uploadedPlatformCredential.getSerialNumber()
+ ".cer\"";
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write platform credential to output stream
response.getOutputStream().write(certificate.getRawBytes());
}
}
} catch (IllegalArgumentException ex) {
log.error("Failed to parse platform credential ID from: " + id, ex);
// send a 404 error when invalid certificate
final PlatformCredential platformCredential = (PlatformCredential) certificate;
final String fileName = "filename=\"" + PlatformCredential.class.getSimpleName()
+ "_"
+ platformCredential.getSerialNumber()
+ ".cer\"";
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write platform credential to output stream
response.getOutputStream().write(certificate.getRawBytes());
} catch (Exception ex) {
log.error("An exception was thrown while attempting to download the"
+ " specified platform credential", ex);
// send a 404 error when an exception is thrown while attempting to download the
// specified platform credential
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Handles request to download the platform credentials by writing it to the response stream
* Processes request to bulk download all the platform credentials by writing it to the response stream
* for download in bulk.
*
* @param response the response object (needed to update the header with the
@ -213,7 +232,7 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
@GetMapping("/bulk-download")
public void bulkDownloadPlatformCredentials(final HttpServletResponse response)
throws IOException {
log.info("Handling request to download all platform credentials");
log.info("Receiving request to download all platform credentials");
final String fileName = "platform_certificates.zip";
final String singleFileName = "Platform_Certificate";
@ -225,16 +244,18 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
// write platform credentials to output stream and bulk download them
this.certificateService.bulkDownloadCertificates(zipOut, PLATFORM_CREDENTIALS, singleFileName);
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse platform credential ID from: ";
log.error(uuidError, ex);
// send a 404 error when invalid certificate
} catch (Exception ex) {
log.error("An exception was thrown while attempting to bulk download all the"
+ "platform credentials", ex);
// send a 404 error when an exception is thrown while attempting to download the
//platform credentials
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Upload and processes a platform credential.
* Processes request to upload one or more platform credentials to the ACA.
*
* @param files the files to process
* @param attr the redirection attributes
@ -246,15 +267,15 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
@RequestParam("file") final MultipartFile[] files,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to upload one or more platform credentials");
log.info("Receiving request to upload one or more platform credentials");
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
for (MultipartFile file : files) {
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
//Parse platform credential
PlatformCredential parsedPlatformCredential = parsePlatformCredential(file, messages);
@ -264,6 +285,9 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
PLATFORM_CREDENTIALS,
file.getOriginalFilename(),
successMessages, errorMessages, parsedPlatformCredential);
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
}
}
@ -273,9 +297,8 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
return redirectTo(Page.PLATFORM_CREDENTIALS, new NoPageParams(), model, attr);
}
/**
* Archives (soft delete) the platform credential.
* Processes request to archive/soft delete the provided platform credential.
*
* @param id the UUID of the platform credential to delete
* @param attr RedirectAttributes used to forward data back to the original
@ -287,28 +310,27 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
public RedirectView deletePlatformCredential(
@RequestParam final String id,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to delete platform credential id {}", id);
log.info("Receiving request to delete platform credential id {}", id);
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
try {
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
try {
UUID uuid = UUID.fromString(id);
this.certificateService.deleteCertificate(uuid, PLATFORM_CREDENTIALS,
successMessages, errorMessages);
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse platform credential ID from: " + id;
messages.addError(uuidError);
log.error(uuidError, ex);
} catch (DBManagerException ex) {
String dbError = "Failed to archive platform credential: " + id;
messages.addError(dbError);
log.error(dbError, ex);
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
} catch (Exception exception) {
final String errorMessage = "An exception was thrown while attempting to delete"
+ " the specified platform credential";
messages.addErrorMessage(errorMessage);
log.error(errorMessage, exception);
}
model.put(MESSAGES_ATTRIBUTE, messages);
@ -318,22 +340,24 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
/**
* Helper method that returns a list of column names that are searchable.
*
* @param columns columns
* @return searchable column names
*/
private List<String> findSearchableColumnsNames(List<Column> columns) {
private List<String> findSearchableColumnsNames(final List<Column> columns) {
// Retrieve all searchable columns and collect their names into a list of strings.
return columns.stream().filter(Column::isSearchable).map(Column::getName)
.collect(Collectors.toList());
}
/**
* Attempts to parse the provided file in order to create a PLatform Credential.
* Attempts to parse the provided file in order to create a Platform Credential.
*
* @param file file
* @param messages page messages
* @return platform credential
*/
private PlatformCredential parsePlatformCredential(MultipartFile file, PageMessages messages) {
private PlatformCredential parsePlatformCredential(final MultipartFile file,
final PageMessages messages) {
log.info("Received platform credential file of size: {}", file.getSize());
byte[] fileBytes;
@ -346,7 +370,7 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
final String failMessage = String.format(
"Failed to read uploaded platform credential file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
return null;
}
@ -357,25 +381,25 @@ public class PlatformCredentialPageController extends PageController<NoPageParam
final String failMessage = String.format(
"Failed to parse uploaded platform credential file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
return null;
} catch (DecoderException dEx) {
final String failMessage = String.format(
"Failed to parse uploaded platform credential pem file (%s): ", fileName);
log.error(failMessage, dEx);
messages.addError(failMessage + dEx.getMessage());
messages.addErrorMessage(failMessage + dEx.getMessage());
return null;
} catch (IllegalArgumentException iaEx) {
final String failMessage = String.format(
"platform credential format not recognized(%s): ", fileName);
"Platform credential format not recognized(%s): ", fileName);
log.error(failMessage, iaEx);
messages.addError(failMessage + iaEx.getMessage());
messages.addErrorMessage(failMessage + iaEx.getMessage());
return null;
} catch (IllegalStateException isEx) {
final String failMessage = String.format(
"Unexpected object while parsing platform credential %s ", fileName);
log.error(failMessage, isEx);
messages.addError(failMessage + isEx.getMessage());
messages.addErrorMessage(failMessage + isEx.getMessage());
return null;
}
}

View File

@ -951,14 +951,14 @@ public class PolicyPageController extends PageController<NoPageParams> {
final PolicyManagerException pmEx,
final String message, final String error) {
log.error(message, pmEx);
messages.addError(error);
messages.addErrorMessage(error);
model.put(MESSAGES_ATTRIBUTE, messages);
}
private void handleUserError(final Map<String, Object> model,
final PageMessages messages,
final String errorMessage) {
messages.addError(errorMessage);
messages.addErrorMessage(errorMessage);
model.put(MESSAGES_ATTRIBUTE, messages);
}
@ -1003,7 +1003,7 @@ public class PolicyPageController extends PageController<NoPageParams> {
policyRepository.saveAndFlush(settings);
// Log and set the success message
messages.addSuccess(successMessage);
messages.addSuccessMessage(successMessage);
log.debug("ACA Policy set to: " + ppModel.toString());
model.put(MESSAGES_ATTRIBUTE, messages);

View File

@ -595,7 +595,7 @@ public class ReferenceManifestDetailsPageController
// Check if parameters were set
if (params.getId() == null) {
String typeError = "ID was not provided";
messages.addError(typeError);
messages.addErrorMessage(typeError);
log.debug(typeError);
mav.addObject(MESSAGES_ATTRIBUTE, messages);
} else {
@ -606,7 +606,7 @@ public class ReferenceManifestDetailsPageController
caCertificateRepository));
} catch (IllegalArgumentException iaEx) {
String uuidError = "Failed to parse ID from: " + params.getId();
messages.addError(uuidError);
messages.addErrorMessage(uuidError);
log.error(uuidError, iaEx);
} catch (CertificateException cEx) {
log.error(cEx);
@ -620,7 +620,7 @@ public class ReferenceManifestDetailsPageController
if (data.isEmpty()) {
String notFoundMessage = "Unable to find RIM with ID: " + params.getId();
messages.addError(notFoundMessage);
messages.addErrorMessage(notFoundMessage);
log.warn(notFoundMessage);
mav.addObject(MESSAGES_ATTRIBUTE, messages);
} else {

View File

@ -183,7 +183,7 @@ public class ReferenceManifestPageController extends PageController<NoPageParams
+ "\".rimpcr\", \".rimel\", \".bin\", and \".log\". "
+ "Please verify your upload and retry.";
log.error("File extension in " + fileName + " not recognized as base or support RIM.");
messages.addError(errorString);
messages.addErrorMessage(errorString);
}
}
baseRims.forEach((rim) -> {
@ -236,21 +236,21 @@ public class ReferenceManifestPageController extends PageController<NoPageParams
if (referenceManifest == null) {
String notFoundMessage = "Unable to locate RIM with ID: " + id;
messages.addError(notFoundMessage);
messages.addErrorMessage(notFoundMessage);
log.warn(notFoundMessage);
} else {
referenceManifestRepository.delete(referenceManifest);
String deleteCompletedMessage = "RIM successfully deleted";
messages.addInfo(deleteCompletedMessage);
messages.addInfoMessage(deleteCompletedMessage);
log.info(deleteCompletedMessage);
}
} catch (IllegalArgumentException iaEx) {
String uuidError = "Failed to parse ID from: " + id;
messages.addError(uuidError);
messages.addErrorMessage(uuidError);
log.error(uuidError, iaEx);
} catch (DBManagerException dbmEx) {
String dbError = "Failed to archive cert: " + id;
messages.addError(dbError);
messages.addErrorMessage(dbError);
log.error(dbError, dbmEx);
}
@ -400,7 +400,7 @@ public class ReferenceManifestPageController extends PageController<NoPageParams
final String failMessage
= String.format("Failed to read uploaded file (%s): ", fileName);
log.error(failMessage, e);
messages.addError(failMessage + e.getMessage());
messages.addErrorMessage(failMessage + e.getMessage());
}
try {
@ -409,26 +409,26 @@ public class ReferenceManifestPageController extends PageController<NoPageParams
if (referenceManifestRepository.findByHexDecHashAndRimType(
supportRim.getHexDecHash(), supportRim.getRimType()) == null) {
supportRims.add(supportRim);
messages.addInfo("Saved support RIM " + fileName);
messages.addInfoMessage("Saved support RIM " + fileName);
}
} else {
baseRim = new BaseReferenceManifest(fileName, fileBytes);
if (referenceManifestRepository.findByHexDecHashAndRimType(
baseRim.getHexDecHash(), baseRim.getRimType()) == null) {
baseRims.add(baseRim);
messages.addInfo("Saved base RIM " + fileName);
messages.addInfoMessage("Saved base RIM " + fileName);
}
}
} catch (IOException | NullPointerException ioEx) {
final String failMessage
= String.format("Failed to parse support RIM file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
} catch (UnmarshalException e) {
final String failMessage
= String.format("Failed to parse base RIM file (%s): ", fileName);
log.error(failMessage, e);
messages.addError(failMessage + e.getMessage());
messages.addErrorMessage(failMessage + e.getMessage());
} catch (Exception e) {
final String failMessage
= String.format("Failed to parse (%s): ", fileName);

View File

@ -1,6 +1,5 @@
package hirs.attestationca.portal.page.controllers;
import hirs.attestationca.persist.DBManagerException;
import hirs.attestationca.persist.FilteredRecordsList;
import hirs.attestationca.persist.entity.manager.CACredentialRepository;
import hirs.attestationca.persist.entity.manager.CertificateRepository;
@ -16,6 +15,7 @@ import hirs.attestationca.portal.page.PageController;
import hirs.attestationca.portal.page.PageMessages;
import hirs.attestationca.portal.page.params.NoPageParams;
import hirs.attestationca.portal.page.utils.CertificateStringMapBuilder;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
@ -54,6 +54,9 @@ import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;
/**
* Controller for the Trust Chain Certificates page.
*/
@Log4j2
@Controller
@RequestMapping("/HIRS_AttestationCAPortal/portal/certificate-request/trust-chain")
@ -71,6 +74,14 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
private final CertificateService certificateService;
private CertificateAuthorityCredential certificateAuthorityCredential;
/**
* Constructor for the Trust Chain Certificate page.
*
* @param certificateRepository certificateRepository
* @param caCredentialRepository caCredentialRepository
* @param certificateService certificateService
* @param acaCertificate acaCertificate
*/
@Autowired
public TrustChainCertificatePageController(final CertificateRepository certificateRepository,
final CACredentialRepository caCredentialRepository,
@ -92,12 +103,12 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
}
/**
* Returns the path for the view and the data model for the page.
* Returns the path for the view and the data model for the Trust Chain certificate page.
*
* @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.
* @return the path for the view and data model for the Trust Chain certificate page.
*/
@RequestMapping
public ModelAndView initPage(
@ -114,15 +125,20 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
}
/**
* @param input
* @return
* Processes request to retrieve the collection of trust chain certificates that will be
* displayed on the trust chain certificates page.
*
* @param input data table input received from the front-end
* @return data table of trust chain certificates
*/
@ResponseBody
@GetMapping(value = "/list",
produces = MediaType.APPLICATION_JSON_VALUE)
public DataTableResponse<CertificateAuthorityCredential> getTrustChainCertificatesTableData(
final DataTableInput input) {
log.debug("Handling list request for trust chain certificates: {}", input);
log.info("Receiving request to display list of trust chain certificates");
log.debug("Request received a datatable input object for the trust chain certificates page: {}",
input);
// attempt to get the column property based on the order index.
String orderColumnName = input.getOrderColumnName();
@ -161,7 +177,7 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
records.setRecordsFiltered(caCredentialRepository.findByArchiveFlag(false).size());
log.debug("Returning the size of the list of trust chain certificates: {}", records.size());
log.info("Returning the size of the list of trust chain certificates: {}", records.size());
return new DataTableResponse<>(records, input);
}
@ -179,41 +195,52 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
@RequestParam final String id,
final HttpServletResponse response)
throws IOException {
log.info("Handling request to download {}", id);
log.info("Receiving request to download trust chain certificate {}", id);
try {
UUID uuid = UUID.fromString(id);
Certificate certificate = this.certificateService.findCertificate(uuid);
if (certificate == null) {
// Use the term "record" here to avoid user confusion b/t cert and cred
String notFoundMessage = "Unable to locate record with ID: " + uuid;
log.warn(notFoundMessage);
// send a 404 error when invalid certificate
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
String fileName = "filename=\"" + CertificateAuthorityCredential.class.getSimpleName()
+ "_"
+ certificate.getSerialNumber()
+ ".cer\"";
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write cert to output stream
response.getOutputStream().write(certificate.getRawBytes());
final String errorMessage =
"Unable to locate trust chain certificate record with ID " + uuid;
log.warn(errorMessage);
throw new EntityNotFoundException(errorMessage);
} else if (!(certificate instanceof CertificateAuthorityCredential)) {
final String errorMessage =
"Unable to cast the found certificate to a trust chain certificate "
+ "object";
log.warn(errorMessage);
throw new ClassCastException(errorMessage);
}
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from: " + id;
log.error(uuidError, ex);
// send a 404 error when invalid certificate
final CertificateAuthorityCredential trustChainCertificate =
(CertificateAuthorityCredential) certificate;
final String fileName = "filename=\"" + CertificateAuthorityCredential.class.getSimpleName()
+ "_"
+ trustChainCertificate.getSerialNumber()
+ ".cer\"";
// Set filename for download.
response.setHeader("Content-Disposition", "attachment;" + fileName);
response.setContentType("application/octet-stream");
// write trust chain certificate to output stream
response.getOutputStream().write(certificate.getRawBytes());
} catch (Exception ex) {
log.error("An exception was thrown while attempting to download the"
+ " specified trust chain certificate", ex);
// send a 404 error when an exception is thrown while attempting to download the
// specified trust chain certificate
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Handles request to download the ACA cert by writing it to the response
* Processes request to download the ACA cert by writing it to the response
* stream for download.
*
* @param response the response object (needed to update the header with the
@ -225,6 +252,8 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
public void downloadAcaCertificate(final HttpServletResponse response)
throws IOException {
log.info("Receiving request to download the ACA server trust chain certificate");
// Set filename for download.
response.setHeader("Content-Disposition", "attachment; filename=\"hirs-aca-cert.cer\"");
response.setContentType("application/octet-stream");
@ -234,7 +263,7 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
}
/**
* Handles request to download the certs by writing it to the response stream
* Processes request to bulk download all the trust chain certificate by writing it to the response stream
* for download in bulk.
*
* @param response the response object (needed to update the header with the
@ -244,7 +273,7 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
@GetMapping("/bulk-download")
public void bulkDownloadTrustChainCertificates(final HttpServletResponse response)
throws IOException {
log.info("Handling request to download all trust chain certificates");
log.info("Receiving request to download all trust chain certificates");
final String fileName = "trust-chain.zip";
final String singleFileName = "ca-certificates";
@ -256,14 +285,17 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
// write trust chain certificates to output stream and bulk download them
this.certificateService.bulkDownloadCertificates(zipOut, TRUST_CHAIN, singleFileName);
} catch (Exception ex) {
log.error("Failed to bulk download trust chain certificates: ", ex);
// send a 404 error when invalid certificate
log.error("An exception was thrown while attempting to bulk download all the"
+ "trust chain certificates", ex);
// send a 404 error when an exception is thrown while attempting to download the
// trust chain certificates
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Uploads and processes a trust chain certificate.
* Processes request to upload one or more trust chain certificates.
*
* @param files the files to process
* @param attr the redirection attributes
@ -275,15 +307,15 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
@RequestParam("file") final MultipartFile[] files,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to upload one or more trust chain certificates");
log.info("Receiving request to upload one or more trust chain certificates");
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
for (MultipartFile file : files) {
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
//Parse trust chain certificate
CertificateAuthorityCredential parsedTrustChainCertificate =
parseTrustChainCertificate(file, messages);
@ -294,10 +326,10 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
TRUST_CHAIN,
file.getOriginalFilename(),
successMessages, errorMessages, parsedTrustChainCertificate);
}
var a = successMessages;
var b = errorMessages;
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
}
}
//Add messages to the model
@ -307,7 +339,7 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
}
/**
* Archives (soft deletes) the trust chain certificate.
* Processes request to archive/soft delete the provided trust chain certificate.
*
* @param id the UUID of the trust chain certificate to delete
* @param attr RedirectAttributes used to forward data back to the original
@ -316,36 +348,32 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
* @throws URISyntaxException if malformed URI
*/
@PostMapping("/delete")
public RedirectView deleteTrustChainCertificates(
public RedirectView deleteTrustChainCertificate(
@RequestParam final String id,
final RedirectAttributes attr) throws URISyntaxException {
log.info("Handling request to delete trust chain certificate id {}", id);
log.info("Receiving request to delete trust chain certificate id {}", id);
Map<String, Object> model = new HashMap<>();
PageMessages messages = new PageMessages();
try {
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
try {
UUID uuid = UUID.fromString(id);
this.certificateService.deleteCertificate(uuid, TRUST_CHAIN,
successMessages, errorMessages);
var a = successMessages;
} catch (IllegalArgumentException ex) {
String uuidError = "Failed to parse ID from: " + id;
messages.addError(uuidError);
log.error(uuidError, ex);
} catch (DBManagerException ex) {
String dbError = "Failed to archive cert: " + id;
messages.addError(dbError);
log.error(dbError, ex);
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
} catch (Exception exception) {
final String errorMessage = "An exception was thrown while attempting to delete"
+ " the specified trust chain certificate";
messages.addErrorMessage(errorMessage);
log.error(errorMessage, exception);
}
model.put(MESSAGES_ATTRIBUTE, messages);
return redirectTo(Page.TRUST_CHAIN, new NoPageParams(), model, attr);
}
@ -353,9 +381,10 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
/**
* Helper method that returns a list of column names that are searchable.
*
* @param columns columns
* @return searchable column names
*/
private List<String> findSearchableColumnsNames(List<Column> columns) {
private List<String> findSearchableColumnsNames(final List<Column> columns) {
// Retrieve all searchable columns and collect their names into a list of strings.
return columns.stream().filter(Column::isSearchable).map(Column::getName)
@ -369,8 +398,8 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
* @param messages page messages
* @return trust chain certificate
*/
private CertificateAuthorityCredential parseTrustChainCertificate(MultipartFile file,
PageMessages messages) {
private CertificateAuthorityCredential parseTrustChainCertificate(final MultipartFile file,
final PageMessages messages) {
log.info("Received trust chain certificate file of size: {}", file.getSize());
byte[] fileBytes;
@ -383,7 +412,7 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
final String failMessage = String.format(
"Failed to read uploaded trust chain certificate file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
return null;
}
@ -398,6 +427,7 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
for (java.security.cert.Certificate certificate : c) {
List<String> successMessages = new ArrayList<>();
List<String> errorMessages = new ArrayList<>();
this.certificateService.storeCertificate(
TRUST_CHAIN,
file.getOriginalFilename(),
@ -405,6 +435,9 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
errorMessages,
new CertificateAuthorityCredential(
certificate.getEncoded()));
messages.addSuccessMessages(successMessages);
messages.addErrorMessages(errorMessages);
}
// stop the main thread from saving/storing
@ -419,27 +452,26 @@ public class TrustChainCertificatePageController extends PageController<NoPagePa
final String failMessage = String.format(
"Failed to parse uploaded trust chain certificate file (%s): ", fileName);
log.error(failMessage, ioEx);
messages.addError(failMessage + ioEx.getMessage());
messages.addErrorMessage(failMessage + ioEx.getMessage());
return null;
} catch (DecoderException dEx) {
final String failMessage = String.format(
"Failed to parse uploaded trust chain certificate pem file (%s): ", fileName);
log.error(failMessage, dEx);
messages.addError(failMessage + dEx.getMessage());
messages.addErrorMessage(failMessage + dEx.getMessage());
return null;
} catch (IllegalArgumentException iaEx) {
final String failMessage = String.format(
"Trust chain certificate format not recognized(%s): ", fileName);
log.error(failMessage, iaEx);
messages.addError(failMessage + iaEx.getMessage());
messages.addErrorMessage(failMessage + iaEx.getMessage());
return null;
} catch (IllegalStateException isEx) {
final String failMessage = String.format(
"Unexpected object while parsing trust chain certificate %s ", fileName);
log.error(failMessage, isEx);
messages.addError(failMessage + isEx.getMessage());
messages.addErrorMessage(failMessage + isEx.getMessage());
return null;
}
}
}

View File

@ -6,7 +6,7 @@
<div id="page-messages-container">
<ul id="page-messages" class="noPaddingOrMargin">
<c:forEach var="error" items="${messages.error}">
<c:forEach var="error" items="${messages.errorMessages}">
<li id="page-errorMessage" class="page-message">
<span class="page-messageIcon">
<img src="${icons}/ic_priority_high_white_24dp.png"/>
@ -15,7 +15,7 @@
</li>
</c:forEach>
<c:forEach var="success" items="${messages.success}">
<c:forEach var="success" items="${messages.successMessages}">
<li id="page-successMessage" class="page-message">
<span class="page-messageIcon">
<img src="${icons}/ic_done_white_24dp.png"/>
@ -24,7 +24,7 @@
</li>
</c:forEach>
<c:forEach var="info" items="${messages.info}">
<c:forEach var="info" items="${messages.infoMessages}">
<li id="page-infoMessage" class="page-message">
<span class="page-messageIcon">
<img src="${icons}/ic_priority_high_white_24dp.png"/>

View File

@ -42,34 +42,51 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest {
// Random UUID for certificate search.
private static final String ID = "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
private static final String TEST_CA_CERTIFICATE
= "/certificates/fakestmtpmekint02.pem";
private static final String TEST_ROOT_CA_CERTIFICATE
= "/certificates/fakeCA.pem";
private static final String ISSUED_CLIENT_CERT
= "/certificates/sample_identity_cert.cer";
private static final String TEST_ENDORSEMENT_CREDENTIAL
= "/endorsement_credentials/tpmcert.pem";
private static final String TEST_PLATFORM_CREDENTIAL
= "/platform_credentials/Intel_pc.cer";
private static final String TEST_PLATFORM_CREDENTIAL_2
= "/platform_credentials/basic_plat_cert_2-0.pem";
private static final String TEST_PLATFORM_CREDENTIAL_2_PCI
= "/platform_credentials/pciids_plat_cert_2-0.pem";
// Base path for the page
private final 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;
private CertificateAuthorityCredential caCertificate;
private CertificateAuthorityCredential caRootCertificate;
private PlatformCredential platformCredential;
private PlatformCredential platformCredential2;
private PlatformCredential platformCertificatePCI;
private EndorsementCredential endorsementCredential;
private IssuedAttestationCertificate issuedCredential;
/**
@ -171,7 +188,7 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest {
.param("id", ID)
.param("type", "certificateauthority"))
.andExpect(status().isOk())
.andExpect(model().attribute(PageController.MESSAGES_ATTRIBUTE, hasProperty("error",
.andExpect(model().attribute(PageController.MESSAGES_ATTRIBUTE, hasProperty("errorMessages",
hasItem("Unable to find certificate with ID: " + ID))))
.andReturn();
}
@ -189,7 +206,7 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest {
.param("id", ID)
.param("type", "invalid"))
.andExpect(status().isOk())
.andExpect(model().attribute(PageController.MESSAGES_ATTRIBUTE, hasProperty("error",
.andExpect(model().attribute(PageController.MESSAGES_ATTRIBUTE, hasProperty("errorMessages",
hasItem("Invalid certificate type: invalid"))))
.andReturn();
}
@ -206,7 +223,7 @@ public class CertificateDetailsPageControllerTest extends PageControllerTest {
.perform(MockMvcRequestBuilders.get(pagePath)
.param("id", ID))
.andExpect(status().isOk())
.andExpect(model().attribute(PageController.MESSAGES_ATTRIBUTE, hasProperty("error",
.andExpect(model().attribute(PageController.MESSAGES_ATTRIBUTE, hasProperty("errorMessages",
hasItem("Type was not provided"))))
.andReturn();
}

View File

@ -99,8 +99,8 @@ public class EndorsementKeyCredentialsPageControllerTest extends PageControllerT
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals("New certificate successfully uploaded (" + pathTokens[1] + "): ",
pageMessages.getSuccess().get(0));
assertEquals(0, pageMessages.getError().size());
pageMessages.getSuccessMessages().get(0));
assertEquals(0, pageMessages.getErrorMessages().size());
// verify the cert was actually stored
List<EndorsementCredential> records =
@ -147,8 +147,8 @@ public class EndorsementKeyCredentialsPageControllerTest extends PageControllerT
// verify redirection messages
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals(1, pageMessages.getError().size());
assertEquals(0, pageMessages.getSuccess().size());
assertEquals(1, pageMessages.getErrorMessages().size());
assertEquals(0, pageMessages.getSuccessMessages().size());
// verify the cert was not actually stored
List<EndorsementCredential> records =

View File

@ -111,8 +111,8 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest {
// verify redirection messages
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals(1, pageMessages.getSuccess().size());
assertEquals(0, pageMessages.getError().size());
assertEquals(1, pageMessages.getSuccessMessages().size());
assertEquals(0, pageMessages.getErrorMessages().size());
// verify the cert was actually stored
List<Certificate> records =
@ -173,11 +173,11 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest {
// verify redirection messages
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals(1, pageMessages.getSuccess().size());
assertEquals(0, pageMessages.getError().size());
assertEquals(1, pageMessages.getSuccessMessages().size());
assertEquals(0, pageMessages.getErrorMessages().size());
assertEquals("Pre-existing certificate found and unarchived ("
+ pathTokens[1] + "): ",
pageMessages.getSuccess().get(0));
pageMessages.getSuccessMessages().get(0));
// verify there is still only one cert in db
List<Certificate> records = certificateRepository.findAll();
@ -216,8 +216,8 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest {
// verify redirection messages
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals(0, pageMessages.getSuccess().size());
assertEquals(1, pageMessages.getError().size());
assertEquals(0, pageMessages.getSuccessMessages().size());
assertEquals(1, pageMessages.getErrorMessages().size());
// verify the cert was not actually stored
List<Certificate> records =
@ -243,8 +243,8 @@ public class PlatformCredentialsPageControllerTest extends PageControllerTest {
// verify redirection messages
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals(1, pageMessages.getError().size());
assertEquals(0, pageMessages.getSuccess().size());
assertEquals(1, pageMessages.getErrorMessages().size());
assertEquals(0, pageMessages.getSuccessMessages().size());
// verify the cert was not actually stored
List<Certificate> records =

View File

@ -61,7 +61,6 @@ public class PolicyPageControllerTest extends PageControllerTest {
*/
@Test
public void verifySpringInitialized() {
assertNotNull(policyRepository);
assertNotNull(policy);
}
@ -116,7 +115,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("success",
hasProperty("successMessages",
hasItem("Endorsement credential validation enabled"))));
policy = policyRepository.findByName("Default");
@ -148,7 +147,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("success",
hasProperty("successMessages",
hasItem("Endorsement credential validation disabled"))));
policy = policyRepository.findByName("Default");
@ -169,7 +168,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("error",
hasProperty("errorMessages",
hasItem("To disable Endorsement Credential Validation, Platform Validation"
+ " must also be disabled."))));
@ -203,7 +202,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("success",
hasProperty("successMessages",
hasItem("Platform certificate validation enabled"))));
policy = policyRepository.findByName("Default");
@ -224,7 +223,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("error",
hasProperty("errorMessages",
hasItem("Unable to change Platform Validation setting,"
+ " invalid policy configuration."))));
@ -258,7 +257,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("success",
hasProperty("successMessages",
hasItem("Platform certificate validation disabled"))));
policy = policyRepository.findByName("Default");
@ -279,7 +278,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("error",
hasProperty("errorMessages",
hasItem("Unable to change Platform Validation setting,"
+ " invalid policy configuration."))));
@ -313,7 +312,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("success",
hasProperty("successMessages",
hasItem("Platform certificate attribute validation enabled"))));
policy = policyRepository.findByName("Default");
@ -334,7 +333,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("error",
hasProperty("errorMessages",
hasItem("To enable Platform Attribute Validation,"
+ " Platform Credential Validation must also be enabled."))));
@ -367,7 +366,7 @@ public class PolicyPageControllerTest extends PageControllerTest {
.andExpect(status().is3xxRedirection())
// check the messages forwarded to the redirected page
.andExpect(flash().attribute(PageController.MESSAGES_ATTRIBUTE,
hasProperty("success",
hasProperty("successMessages",
hasItem("Platform certificate attribute validation disabled"))));
policy = policyRepository.findByName("Default");

View File

@ -183,9 +183,9 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest {
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals("New certificate successfully uploaded (" + pathTokens[1] + "): ",
pageMessages.getSuccess()
pageMessages.getSuccessMessages()
.get(0));
assertEquals(0, pageMessages.getError().size());
assertEquals(0, pageMessages.getErrorMessages().size());
// verify the cert was actually stored
List<Certificate> records =
@ -244,10 +244,10 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest {
// verify redirection messages
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals(1, pageMessages.getSuccess().size());
assertEquals(0, pageMessages.getError().size());
assertEquals(1, pageMessages.getSuccessMessages().size());
assertEquals(0, pageMessages.getErrorMessages().size());
assertEquals("Pre-existing certificate found and unarchived (" + pathTokens[1] + "): ",
pageMessages.getSuccess().get(0));
pageMessages.getSuccessMessages().get(0));
// verify the cert can be retrieved and that there is only 1 cert in db
List<Certificate> records = certificateRepository.findAll();
@ -279,8 +279,8 @@ public class TrustChainManagementPageControllerTest extends PageControllerTest {
// verify redirection messages
FlashMap flashMap = result.getFlashMap();
PageMessages pageMessages = (PageMessages) flashMap.get("messages");
assertEquals(1, pageMessages.getError().size());
assertEquals(0, pageMessages.getSuccess().size());
assertEquals(1, pageMessages.getErrorMessages().size());
assertEquals(0, pageMessages.getSuccessMessages().size());
// verify the cert was not actually stored
List<Certificate> records = certificateRepository.findAll();