How to prevent malicious input in Spring JPA+Spring REST+jHipster - spring

I'm new to Spring JPA/jHipster.
My question is inspired by the jHipster talk by Julien Dubois: https://youtu.be/R3jm2qmqctI?t=43m7s
Assume you have a bank account with operations on it (+100$ for restaurant, -50$ ATM, ...)
Each bank account has an owner of course.
The payload of a POST REST call that creates the operation could look like this:
{"amount":100,"description":"restaurant","bankaccount":{"id":1136}}
The id of the bankaccount is unique and (for the sake of this example) would have been sent to me earlier via another REST call.
Unfortunately, nothing prevents a malicious user to change this value. One could simply guess the id of a bankaccount owned by someone else, and then the operation would be added to that one.
I have not (yet) seen examples that deal with this problem.
Should I explicitly check if the bankaccount is owned by the user?
I imagine that this type of verification may cascade through all your entities, causing a lot of extra calls.
Maybe I'm missing something?
Thanks,
Andy

Yes it's your reponsibility to check in your REST controller or underlying services that an operation is authorized. Spring security offers different mechanisms to do it in particular by using #PreAuthorize and #PostFilter.
It's also a good thing to use DTOs, this way you can better control what fields of your entities are exposed for reading and writing through the API.

Related

Is possible to use Oauth2 scopes to scope model data?

Every place I read about Oauth2 scopes it uses examples of read, write, delete, post:read, post:delete, etc... This always representing "actions", like It was a permission...
I am in a situation that I must implement an API that must authenticate the user but limit user's access to data that only belongs to the same corporation he belongs, this user may belong to "N" corporations.
I came with the idea to use the Oauth2 scopes for that purpose then use Laravel's eloquent global scopes in model to filter the data.
I am stuck and dont know How to proceed. Could anyone give some advice?
There are 2 concepts in the requirements you mention:
Scopes are high level privileges that represent an area of data and operations allowed on that data - they are also static values defined as part of the system design. Avoid attempting to use them for dynamic logic.
Claims are where the real authorization happens, and what most domain specific authorization uses. Claims are just extra fields included in JWTs. In your case an array claim of Corporation IDs could be issued and included in JWTs received by APIs.
These two Curity articles explain this in more detail, along with some real world examples. When done well, the result should be simple code in your APIs:
Scope Best Practices
Claims Best Practices

Defining two separate API endpoints for essentially the same logic just for the sake of avoiding REST anti-patterns?

Suppose we have a M:M relationship between a User model and a Project model in a project management SaaS. Naturally we have a pivot table mapping users to projects. An entry is deleted either if the user leaves or if the project manager removes that user from the project.
Even though the final result is essentially the same (i.e., the entry is deleted), I imagine it would be better to distinguish between these two actions by defining two separate API endpoints as follows:
user leaves project
route DELETE /users/{id}/projects/{id}
action UserProjectController#destroy($id) where $id refers to the project
project manager removes user
route DELETE /projects/{id}/participants/{id}
action ProjectParticipantController#destroy($id) where $id refers to the user
Should I ignore Cruddy by Design and RESTful design principles and simply define leave() join() remove() actions instead and use verbs in the URIs? like so:
POST /projects/{id}/join
POST /projects/{id}/leave
POST /projects/{id}/participants/{id}/remove
join,leave,remove are arguably RPC rather than REST. Pivot tables etc are how the domain is implemented and are irrelevant to the caller of the API, which works at the domain level. How do the URLs map to your domain model?
If Project has one or more User why not just use
/projects/{id}/
to manage everything about Project and Participant instances?
User is in a Project but only if
/projects/{id}/participants/{id}
has been called.
FWIW,
DELETE /users/{id}/projects/{id}
looks like it's deleting the Project instance owned by a User as the Project object has participants but the User doesn't use that terminology. Perhaps it would be:
DELETE /users/{id}/projects/{id}/participants
for consistency with the domain model.
However it seems much easier to just use Project to manage Project instances. Removing a User from a Project using the User API seems a convenience that complicates the backend and doesn't really match the Project terminology. That would mean only having UserController and ProjectController classes.
You would have to consider whether a Participant id is the same as a User id and whether the pivot table handles that but that won't affect the API. The API should be an intuitive representation of your domain model.
Something to consider: how would you do it on the web?
Even though the final result is essentially the same (i.e., the entry is deleted), I imagine it would be better to distinguish between these two actions by defining two separate API endpoints
So on the web, you might well have two different forms that are used to "achieve the same result", but that doesn't necessarily mean that the forms should target different resources.
POST /foo
Content-Type: application/x-www-form-urlencoded
action=UnsubscribeUser&otherArguments=....
POST /foo
Content-Type: application/x-www-form-urlencoded
action=CancelProject&otherArguments=....
"One resource or two resources" isn't a question of right or wrong, but rather a question of trade-offs.
POST /projects/{id}/join
POST /projects/{id}/leave
POST /projects/{id}/participants/{id}/remove
That's also "fine"; again, it's a question of trade offs. The machines don't care that your identifiers have a verb in the URI.
They do, somewhat, care whether or not the identifier for reading is the same as the identifier for writing. See RFC 7234.
But it's perfectly reasonable to say that having semantically significant URI spellings in the access log or browser history are more important to our long term success than cache-invalidation.
Keep firmly in mind that DELETE - in the context of HTTP - does not mean the same thing as DELETE in the context of SQL; we're talking about two different name spaces with their own semantics.
HTTP DELETE is of the transfer of documents over a network domain. The fact that the implementation of your handler includes a SQL DELETE is completely irrelevant.
Relatively few resources allow the DELETE method -- its primary use is for remote authoring environments, where the user has some direction regarding its effect.
It is OK to use POST.

Creational adapter

I have a lot of code like this
additional_params = {
date_issued: pending.present? ? pending.date_issued : Time.current,
gift_status: status,
date_played: status == "Opened" ? Chronic.parse("now") : (opened.present? ? opened.date_played : nil),
email_template: service&.email_template,
email_text: service&.email_text,
email_subject: service&.email_subject,
label: service&.label,
vendor_confirmation_code: service&.vendor_confirmation_code
}
SomeService.new(reward, employee: employee, **additional_params).create
The same pattern applies to many models and services.
What is the name of this pattern?
How to refactor the current solution?
Is there a gem to solve this kind of solution? Like draper or something else
To me, that looks a bit like a god object for every type of entity. You expect your service to take care of everything related to your entity. The entity itself just acts as a data container and isn't responsible for its data. That's called an anemic model.
First of all, you need to understand that there can be several representations of the same entity. You can have several different classes that represent a user. On the "List user" page, the class contains just a subset of the information, maybe combined with information from the account system (last login, login attempt etc). On the user registration page, you have another class as it's not valid to supply all information for the user.
Those classes are called data transfer objects. Their purpose is to provide the information required for a specific use case and to decouple the internal entity from the external API (i.e. the web page).
Once you have done that, your service classes will start to shrink and you need fewer custom parameters for every method call.
Now your service class has two responsibilities: To manage all entities and to be responsible for their business rules.
To solve that, you should start to only modify your entities through behaviors (methods) and never update the fields directly. When you do so, you will automatically move logic from your service class to your entity class.
Once that is done, your service classes will be even cleaner.
You can read about Domain Driven Design to get inspired (no need to use DDD, but get inspired by how the application layer is structured in it).
You can try the builder pattern. I am not familiar with a ruby gem, but you can find information here: https://en.wikipedia.org/wiki/Builder_pattern and https://en.wikipedia.org/wiki/Fluent_interface

Spring data rest and custom representation

I am using the current version of Spring Data Rest (SDR) and Spring Security (SS) and have following entities:
User: contains a List of teams joined and another for teams managed.
Team: contains a List for members and another for admins.
What I would like to do is customize the information returned for the entities by SDR given permissions of the current User. I'm aware of Projections in SDR but I believe they're not suitable for my current problem since this should be done transparently without having the User specify the projection in the request.
Given the following:
(1) /teams/{team_id}/members
(2) /teams/{team_id}/members/{member_id}
(3) /users/{user_id}/teamsJoined
Here is what I want to implement:
Visiting (1) by a normal member of the team would return different fields than when done by an admin.
Visiting (2) would return additional fields not returned by (1)
Visiting (3):
by the user with {user_id} should return all teams.
by another member should return only the intersection of their teams.
I was thinking about maybe using AOP but I'm not really sure if it would work. What would be the best way to implement this?
I'm not sure exposing various representations of a resource (at the same uri) based on the requesting user follows the REST philosophy. You should use another uri for that.
Maybe you could split the data visible by only some kind of users from the original entity into another 'sub'entity (1-1 relation) and restrict the access to theses related resources endpoints. You can make use of #PreAuthorize and #PostFilter annotations on your repositories methods to restrict access on your resources based on the identified user.

Code Design. How to access your api-key in your business logic?

It's a code design question :)
I have a DelegatingHandler which takes the http request header and validates the API-key. Pretty common task I guess. In my controller I call my business logic and pass along all business-relevant information. However now I'm challenged with the task to change behavior inside my business logic (separate assemblies) depending on certain api-keys.
Various possible solutions come to my mind...
Change business logic method signatures to ask for an api-key, too.
public void SomeUseCase(Entity1 e1, Entity2 e2, string apiKey);
Use HttpContext.Current to access the current request context. However I read somewhere that using HttpContext restrict my hosting options to IIS. Is there any better suited option for that?
var request = HttpContext.Current.Request; // next extract header information
Use Sessions (don't really want to go that road...)
What's your opinion on that topic?
I'd go for #1 although I don't like the idea of mixing in enivonmental stuff in business logic methods. But depending on your point of view you might argue the api-key is in fact logic-relevant.
Update #1:
I'm using a delegatingHandler to validate the apiKey and once it is validated I add it to the Request's Properties Collection.
The part in question is how the "api-key" or RegisteredIdentifier is passed along to the business logic layer. Right now I am passing the object (e.g. IRegisteredIdentifier) as a parameter to the business logic classes' constructors. I understand there is no more elegant way to solve this(?). I thought about changing the method signatures but I'm not sure whether it's interface pollution or not. Some methods need to work with the api-key, most don't. Experience tells me that the number will more likely grow than drop :) So keeping a reference to it in my bl classes seems to be a good choice.
Thank you for your answers - I think all of them are part of my solution. I'm new to StackOverflow.. but as far as I can see - I cannot rate answers yet. Rest assured I'm still thankful :)
I would suggest two different options.
Promote the value into a custom HTTP header (e.g. something like mycompany-api-key: XXXX ). This makes your delegating handler work more like a standard HTTP intermediary. This would be handy if you ever hand off your request to some secondary internal server.
Put the api-key into the request.Properties dictionary. The idea of the the Properties dictionary is to provide a place to put custom meta information about the request.
HTTP works hard to make sure authentication/authorization is a orthogonal concern to the actual request, which is why I would try and keep it out of the action signature.
I would go for option 1.
But you could introduce the entity RegisteredIdentifier (Enterprise Patterns and MDA by Jim Arlow and Ila Neustadt) in your business logic.
The api-key can be converted to a RegisteredIdentifier.
RegisteredIdentifier id = new RegisteredIdentitief(api-key);
public void SomeUseCase(Entity1 e1, Entity2 e2, RegisteredIdentifier id);
The business logic layer has a dependency on the API key. So I would suggest:
interface IApiKeyProvider
{
string ApiGet { get; }
}
..then have your BLL require that an object implementing that interface is supplied to it (in constructor, setup, or even each method that requires it).
Since in the future it might not be one API key. The key point is that this identifies the BLL is dependent on something, and defining a contract for the something.
Real-world example:
Then, in your DI container (Ninject etc), bind your own ConfigFileApiKeyProvider (or whatever) implementation to that interface, in the "place" (layer) that DOES have the API key. So the app that calls the BLL specifies/configures how the API key is specified.
Edit: I misunderstood the part about this being a "how-to-do-it-over-HTTP" question and not a code architecture/code design question. So:
HTTP header is the way to go in terms of transport

Resources