Fortify Cross-Site Scripting : Content Sniffing fix for DTO response - spring-boot

So I'm trying to fix Fortify Vulnerability Issue for content-sniffing, and this needs to use StringEscapeUtils.escapeHtml4 for all attributes of the DTO.
My problem is that the DTO is not a simple object, but rather having nested objects as its attributes:
Root DTO:
public class ServiceOrderListDTO implements Serializable {
private String count;
private String next;
private String previous;
private List<ServiceOrderDetailDTO> results;
}
public class ServiceOrderDetailDTO implements Serializable {
private static final long serialVersionUID = -819641011600662396L;
#JsonProperty("order_code")
private String orderCode;
#JsonProperty("service_number")
private String serviceNumber;
#JsonProperty("customer_name")
private String customerName;
#JsonProperty("customer_brn")
private String customerBrn;
private CustomerDTO[] customer;
#JsonProperty("order_details")
private OrderDetailsDTO orderDetails;
#JsonProperty("site_a_address")
private String siteAAddress;
#JsonProperty("site_b_address")
private String siteBAddress;
#JsonProperty("dff_service_order_id")
private String dffServiceOrderID;
#JsonProperty("dff_response")
private DffResponse dffResponse;
private MilestonesDTO milestones;
private AppointmentsDTO appointments;
}
So I need to Iterate through all the child objects and apply the escapehtml4 function one by one.
However I got feedback that this may lead to performance issue. Is there a way that the escapeHtml4 be applied in the DTO as a whole?
I've been going through SO also but no viable solution so far.
Cross-Site Scripting/Content Sniffing vulnerability detected through static scan for API while returning response

Related

Spring redirect simple rest POST with body (json) on another port

I have 2 spring rest applications.
When I send data to the first one,
private Long id;
private String name;
private String surname;
private String productName;
private Double productValue;
First I create a client entry in DB with the fields:
private Long id;
private String name;
private String surname;
and than
I would like to make a redirect post to another port, another application
handling product data with body including the two fields:
private String productName;
private Double productValue;
private Long clientId;
to create a product entry in the db
after creating product, I would like to redirect back to the first app and show the saved client.
The question is, how should I build my Controller?
Do I have to use ModelAndView? - this is only a backend rest, without any front (run from postman :)
You may like to do this way first autowire RestTemplate and then use it to call another api -
#RestController
public class ProductResource {
#Autowired
RestTemplate restTemplate;
#Autowired
private ProductRepository repository;
#PostMapping
public ResponseEntity<Product> saveProduct(#RequestBody Product product) {
Product productSavedAtClient = repository.save(product);
Product savedProduct = restTemplate.postForObject("http://some.other.app/product", productSavedAtClient, Product.class);
return ResponseEntity.ok().body(savedProduct);
}
}

CQEngine Query nested object using parser.retrieve

I have a nested object like
public class SQSMessage implements Serializable {
private String type;
private boolean isEntity;
private String eventType;
private SystemInfo systemInfo;
private DomainAttributes domainAttributes;
#Data
public static class SystemInfo implements Serializable {
private String identifier;
private String ownedBy;
private Payload payload;
private EntityTags entityTags;
private long createdOn;
private String createdBy;
private long version;
private long lastUpdatedOn;
private String lastUpdatedBy;
private String attrEncKeyName;
#Data
public static class Payload implements Serializable {
private String bucketName;
private String objName;
private String encKeyName;
private byte[] payloadBytes;
private byte[] decryptedBytes;
private byte[] sanitizedBytes;
}
#Data
public static class EntityTags implements Serializable {
private List<Tag> tags;
#Data
public static class Tag implements Serializable {
private String tagName;
private String tagValue;
}
}
}
#Data
public static class DomainAttributes implements Serializable {
private String updatedByAuthId;
private String saveType;
private String docName;
private String ceDataType;
private String year;
private String appId;
private String formSetId;
private String appSku;
private String deviceId;
private String deviceName;
}
}
I would like to query the collection of SQSObjects by applying a filter like
ResultSet<SQSMessage> results = parser.retrieve(indexedSQSMessage, "SELECT * FROM indexedSQSMessage WHERE type='income' and DomainAttributes.saveType in ('endSession', 'cancelled')or (DomainAttributes.countryCode is null or DomainAttributes.countryCode='US'");
Is that possible using CQEngine? if yes.. please send me the examples.
The reason why I want o make that as sql... where clause is dynamic for various use cases.
Your example is more complicated than it needs to be for the question, so I am just skimming it. (Read about SSCCE)
However generally this kind of thing should be possible. See this related question/answer for how to construct nested queries: Can CQEngine query an object inside another object
If you set up attributes like that, you should be able to use them in SQL queries as well as programmatically.

want to autowire DAO class in my entity class

i have a method which i need to call in my entity class company.java.
but when i run my application it throws null pointer exception didn't fount that DAO object in entity class..
How can i get that object in entity class please help
This is my entity class..
package com.salebuild.model;
/**
* Define a company.
*
* #author mseritan
*/
#Entity
#Table(name = "company", uniqueConstraints = {#UniqueConstraint(columnNames = "name")})
#XmlRootElement
#XmlSeeAlso(value = ArrayList.class)
public class Company implements PublishableIF, Serializable, PersistableIF, HistoryIF, AddressableIF {
private static final Logger log = LoggerFactory.getLogger( Company.class );
#Autowired
private CompanyDAO companyDAO;
// CONSTANTS -----------------------------------------------------------------------------------
private static final long serialVersionUID = 1L;
// ATTRIBUTES ----------------------------------------------------------------------------------
private Long id;
#NotBlank
private String name;
private String formerName;
private CorporateTitle topLevelExec;
private List<CompanySite> sites;
private List<CompanyAlias> aliases;
#NotNull
private Industry industry;
private Company parentCompany;
private String emailTopology;
#NotNull
private Double revenue;
#NotNull
private Long numberEmployees;
private CustomerType.Type customerType;
private Boolean recruiter = false;
private int publishState;
private CompanyStatus status;
private Boolean excludeCompany = false;
private CompanyType companyType;
private String salesifyCompanyId;
private CompanySiteType companySiteType;
private String websiteUrl;
private String sourceVendor;
private String notes;
private List<CompanySpecializedRanking> specializedList = new ArrayList<CompanySpecializedRanking>();
#NotNull
private NAICSCode naicsCode;
#NotNull
private SICCode sicCode;
private Long version;
private List<Technology> technologies = new ArrayList<Technology>();
private List<CompanyContact> contacts;
private String phoneNumber;
private String faxNumber;
private String email;
private User userCreated;
private Date dateCreated;
private User userLastModified;
private Date dateLastModified;
private User userLastResearcher;
private Date dateLastResearcher;
#NotBlank
private String street1;
private String street2;
private String street3;
private String city;
private String zipCode;
private State state;
private Country country;
private String specRankingListName;
private Integer specRankingRank;
private Integer specRankingYear;
private String modifiedCompanyName;
private String formattedRevenue;
private String formattedEmployeeSize;
private List<JobPostingRaw> unconfirmedTechnologies;
// ACESSORS ------------------------------------------------------------------------------------
//getter setter for other fields //
this.specRankingYear = specRankingYear;
}
/**
* #param modifiedCompanyName
*
*/
#Column(name="modifiedCompanyName")
public String getModifiedCompanyName() {
return modifiedCompanyName;
}
public void setModifiedCompanyName(String modifiedCompanyName) {
if(modifiedCompanyName==null)
this.modifiedCompanyName=modifiedCompanyName;
else{
this.modifiedCompanyName =companyDAO.updateCompanyName(modifiedCompanyName);
}
}
#Transient
public List<JobPostingRaw> getUnconfirmedTechnologies() {
return unconfirmedTechnologies;
}
public void setUnconfirmedTechnologies(
List<JobPostingRaw> unconfirmedTechnologies) {
this.unconfirmedTechnologies = unconfirmedTechnologies;
}
}
my DAO class is like that --
package com.salebuild.dao;
import com.salebuild.model.Company;
import com.salebuild.model.search.EntitySearchCriteria;
import com.salebuild.model.search.SortedResultsPage;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public interface CompanyDAO extends CrudDAO<Company> {
Company findByNameOrAlias(String name);
List<Company> findBySearchTerm(String searchTerm, Integer start, Integer count);
// SortedResultsPage<Company> findPaged(EntitySearchCriteria criteria);
List<Long> findIds(EntitySearchCriteria criteria);
List<Company> find(Collection<Long> ids);
/**
* For just finding the company name and not looking for alias names.
*
* #param name
* #return
*/
public Company findByName( String name );
public Company findByModifiedName(String name,Company... c);
public int companyCountSinceLastLogin(Long id);
Set<Long> findDistinctIds(EntitySearchCriteria criteria);
public Integer getCompanyCountByRegion(Long regionId,List techCatIds);
List<Company> findAllCompanies(Company instance);
public List<Company> findAllModifiedCompanies(Company instance);
public String updateCompanyName(String name);
}
The easiest option is to implement factory for building entities. Then you can use AutowireCapableBeanFactory to autowire dependencies:
public abstract class GenericFactory<T> {
#Autowired
private AutowireCapableBeanFactory autowireBeanFactory;
public T createBean() {
// creation logic
autowireBeanFactory.autowireBean(createdBean);
return createdBean;
}
}
Of course you can pass object (created or retrieved) and just autowire it.
Another option is to use #Configurable - it automatically injects dependencies. http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-atconfigurable
You can find more details in my post: http://www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non.html
JPA entities are meant to be POJOs i.e. simple Java beans which do not have dependencies and have getters and setters which contain no complex logic.
It would be better to create a service which is responsible for saving and updating your entity which is used throughout your code. This service can then be responsible for executing the logic you wish to put in your setter using dependencies which can be autowired.
The issue you have is that you Spring is not responsible for the creation of your entity. You either instantiate it using new or you obtain it from your JPA implementation. Either way there is no opportunity for Spring to autowire declared dependencies.
As an aside it's not good practice to autowire private variables. See this blog post for a fuller discussion.

How to add properties to the relationship in Spring data neo4j when we use createRelationshipBetween

For example I want to make relationship between User A and User B and they have RelationshipEntity named MakeFriend, I am used code below, but I am also want to set in relation entity some property values like role = 10.........
userRepository.createRelationshipBetween(startUser, endUser, MakeFriend.class, RelTypes.FRIEND.name());
#RelationshipEntity
public class MakeFriend {
#GraphId
private Long id;
private String role;
#StartNode
private UserEntity startUser;
#EndNode
private UserEntity endUser
#NodeEntity
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
public static final String FRIEND = "FRIEND";
public static final String JOYNED = "JOYNED";
#GraphId
private Long id;
#Indexed(unique = true)
private Long userId;
private String email;
You could could add the following to your UserEntity class:
#RelatedToVia(type = RelTypes.FRIEND, direction = Direction.BOTH)
private MakeFriend friend;
friend.setRole("yourRole");
Another way to do it, when you're using the advanced mapping mode, is using one of the NodeBacked.relateTo() methods. Then add the property to the returned Relationship.
And a third way, it to use the Neo4jTemplate.createRelationshipBetween() method and provide your properties (e.g. role) as the final argument.

javax.validation getting ignore from jersey

I am trying to use Jersey to get JSON request from the user to create vendor
#POST
#Produces({APPLICATION_JSON})
#Consumes({APPLICATION_JSON})
#Path("create")
public Response create(VendorTO vendorTO) throws Exception {
But before it converts in vendorTO object I want to validate it with javax.validation
I have added constraints in my pojo like this
{#JsonSerialize(include=Inclusion.NON_NULL)
public class VendorTO {
#NotNull
private Integer userId;
#Size(min = 2)
private String vendorName;
private String address1;
private String address2;
private String city;
private String state;
private String country;
private String email;
private String phone;
}
but it doesnt seems to be working. Can anyone help ?
You need to tell the framework that the parameter should be #Validated:
#POST
#Produces({APPLICATION_JSON})
#Consumes({APPLICATION_JSON})
#Path("create")
public Response create(#Valid VendorTO vendorTO) {
// ...
}
At this point, it appears Jersey does not support JSR 303 natively. You might have to write some ResourceFilters and handle the validation manually.

Resources