What is a good practice of securing methods? - oop

I would like to know what is a good practice of securing methods.
Should all methods be secure, bullet-proof or would it result in too much boilerplate code?
Consider this example in PseudoCode:
class Endpoint {
def create(list: List[Item]): Response =
if(list.isEmpty) BadRequest("Empty list")
else service.insert(list)
}
class Service {
def insert(list: List[Item]) = list.head //throws exception for empty list
...
}
Should the method insert also be secured for invalid input, empty list if it's only usage is in the endpoint class to prevent scenarios in which people call it without checking the list or should it be left as it is?

It is good practice to secure methods and codes. But lots of boilerplate code is not advised since we are blessed with lots of frameworks to get our job done.
We must focus on securing our APIs end-points as a general practice.
Listing few of the best practices:-
1. Validate input
2. Heed compiler warnings
3. Architect and design for security policies
4. Keep it simple
5. Default deny
6. Adhere to the principle of least privilege
7. Sanitize data sent to other systems
8. Practice defense in depth
9. Use effective quality assurance techniques
10. Adopt a secure coding standard
For detailed understanding you can refer:-
Secure Code Guide by Oracle,
Secure Coding Practices

Related

Interface segregation principle for a framework interface with optional features

I am designing a authentication framework. I need users of the framework to implement data access logic since it is not the main purpose of the framework and I want to allow multiple data access approaches (SQL, NoSQL, Cache etc.) I don't implement it inside my framework. My framework uses this logic through an interface called IUserStore but the problem is, there are certain methods inside my interface that are used only when certain feature is active and not used otherwise. For example framework will try to access two factor information through GetTwoFactorInfo method only if two factor authentication is enabled.
My question is about interface segregation principle. Is it ok to leave the interface as it is and explain in the documentation that user needs to implement GetTwoFactorInfo only if user wants to use two factor authentication and throw NotImplementedException otherwise? Or should I separate interface for each optional feature and explain in the documentation user should implement and register this interface to service provider to be able to use that feature? A problem with second approach is when injecting services that implement those interfaces to constructors, I need to check if those features are active otherwise I would get an error because service is not registered and I am trying to access those services from service provider. Which leads to extra complexity for my framework classes.
What would be the best way to handle this problem?
There are practical problems with both of the approaches you suggest, but the plan to have clients throw NotImplementedException is far worse.
Let's go through both of them:
Option 1
leave the interface as it is and explain in the documentation that user needs to implement GetTwoFactorInfo only if user wants to use two factor authentication and throw NotImplementedException otherwise
Well, this might work for the problem you have today, but software design is about the problems you'll have tomorrow. What happens if you add support for different authentication methods to future versions of the framework? If you follow this pattern, then you'll add new methods to IUserStore... but this would break existing clients, because they will not have implemented them!
You can get around this particular problem in some languages by providing default implementations for new methods that throw exceptions, but that defeats much of the purpose of defining an interface in the first place -- the type system no longer tells the client what he has to implement.
Also, this pattern only works for pre-existing interfaces. If you add a new authentication method that requires the client to implement a new interface, that you're back to considering something like your second option, and then you'll have an inconsistent mix if versioning strategies. Ick.
Option 2
separate interface for each optional feature and explain in the documentation user should implement and register this interface to service provider to be able to use that feature
This is much better, but also not great, because it introduces hidden rules that clients of your framework have to follow. All of the ways to find out about these rules are frustrating -- read docs, troubleshoot errors, etc.
This is a common problem in lots of dependency injection systems, though, and lots of people don't seem to mind, but things get really complicated as interacting system of hidden rules accumulates.
Option 3
I don't know how you enable this 2-factor feature right now, but I would suggest that you have your customers enable this feature by calling a method that takes the implied dependencies as arguments, like
void enable2FactorAuth(I2FactorInfoStore store)
Then all the hidden rules go away. Your system ensures that you can't enable the feature unless you've implemented the required interfaces. Easy.
If you are thinking that you will lose the ability to configure your product without programming, then I would like to remind you that you do not have that feature. As you said, there is code that clients have to write in order to use 2 factor authentication. They have to implement the store. Requiring them to call a method to enable it will only improve this code, because it will now be obvious why they had to implement that store in the first place.

OOP design recommendation - REST client with services, each services has methods

I'm writing a client for a REST API for an ERP system(large complicated piece of software). I want to get the design architecture correct now, so I save myself time down the road, hoping you can help. If helpful server side urls are of the format /myServer/v1/someService/someMethod?someParam=x
I started off with a restClient class with public function for all the ERP actions(e.g. restClient->someServiceSomeMethod(someParam)). The restClient knows about authentication, and has private get, post, etc methods. I started with this approach as it's the simplest architecture, although I'm wondering if I should be using inheritance or some other approach(I don't want to overcomplicate but I'm starting to feel like I'm going down the wrong path). For the past 10 years are so I've written mostly procedural code, so I'm a bit rusty on OOP design... Would it be "better" to have classes for each service that inherits the restClient class? The the end code would then instantiate the service object they need then calls the method(someService->someMethod(someParam)? This "feels" like the right way to go, but I'm fuzzy on how I'd authenticate and it's been a long time since I did OOP so would hate to overcomplicate things and get no value out of it.
A good rule of thumb for me is that simpler is usually better.
Inheritance, in my opinion, feels a bit restrictive for this - and you introduce coupling that might cause you pain later. If you build 100 different services and they all share a common super class, but it turns out that 5 of them need to be behave in a slightly different fashion, everything else will also be affected. That could get messy.
Although I don't have sufficient detail to understand all the aspects of your particular scenario, I would strongly consider composition over inheritance - build a RestClient class that can deal with some of the common scenarios (auth, GET, POST, etc.), but instead of extending it, just provide a reference to it to anything else that might require that functionality.
In addition, if there are various 'groups' of common operations (e.g CRUD), why not model those with an interface? Your classes could then implement the interface instead of extending a common super class, giving you the benefit of consistency but without the drawbacks of inheritance.

Dependency injection vs singleton, Initialization

I'm working on a big project right now, and the app is taking advantage of many different services, as:
Comments, likes, posts, purchase and so on..
I have a class for each service.
Now, I came to a point where I would like to restrict registered users only, for some actions, as post, comment, and so on..
Till now every class use to have only class methods, as the following:
#interface UpdateOrderServies : NSObject
+(void)deleteOrder: (STOrder *)order
andReturn: (void(^)(NSError *error))errorBlock;
+(void)updateOrder: (STOrder *)order
andReturn: (void(^)(NSError *error))errorBlock;
But now, i would like to check first if the user is registerd, and if not, not to return a value.
So the best way i figgerd out is changing the classes to singel tone, and asking every time the class is called, if the user is registerd like so:
+(id) getInstance {
static UpdateOrderServies *__sharedDataModel = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__sharedDataModel = [[UpdateOrderServies alloc]init];
});
if (![__sharedDataModel userIsRegisterd]) {
return nil;
}
return __sharedDataModel;
}
And it works, but, well, its not a very good answer as you can see.. i would like somthing more generic.
I was thinking about using Typhoon dependency injection, but there is no place were i could check every call if the user is registered...
Any idea for a better way to deal with this issue? more dynamic...
Based on your question above, I think you're not looking for dependency injection but Aspect Oriented Programming.
Aspect Orientes Programming (AOP) is designed to solve exactly the kinds of problem you describe above - those that cut across many modules in your system. Examples:
every time a user interacts with a service, security should be checked.
all transactions should have an audit trail
every store interraction should result in a genius recommendation
If we use normal Object Oriented programming for these cross-cutting requirements, we break the single responsibility principle and a class that should've been nearly about one topic is now taking on more roles which gets confusing, repetitive and messy.
AOP modularizes these cross-cutting concerns and then identifies all of the places these should be applied using method interception. (In AOP we call this a point-cut expression).
In Objective-c you could either do manual AOP using ISA-swizzling, message forwarding or or using NSProxy - these are all ways of achieving method interception at run-time. Alternatively, you could use a library and one such library called 'Aspects' by Pete Steinberger and team. This library doesn't have a point-cut expression language as yet, but is still certainly much simpler than using the ObjC run-time directly to intercept methods.
Summary of how an Authorization Aspect would work:
At login we authenticate our user, using a username/password challenge, oauth token or similar. Having authenticated a user we are now able to authorization service invocations.
Identify each of the services that require authorization, and the required permission (you can whatever scheme you like roles, capabilities, etc).
Good Object Oriented principles say that each class should have a single responsibility. So your service client should be all about invoking the remote service. We could edit the service client to evaluate the logged in user's permissions and decide whether to proceed. But this would be messy and repetitive. Instead we'll use the information in step 2 (permission required for each service) and delegate that evaluation of that to our authorization module.
Now the AOP step: For each service call, we'll tell our AOP lib to intercept service client method and first invoke the authorization module.
This way your cross-cutting requirement (authorizing client invocations) isn't repeated. Now you may to decide for the sake of simplicity that you can prefer with having each service call invoking an authorization module, but it nonetheless helps to know the theory behind AOP and cross-cutting concerns.
Dependency Injection / Typhoon
Dependency injection doesn't really relate directly to your question, though it can certainly help to avoid the pitfalls of your singleton clients:
Creates a clear contract between your classes - increasing code cohesion.
Identify the key 'actors' in your application, and describe the way they are assembled into a whole. Makes it possible to swap one actor for another that will fulfill the same contract.
Simplifies unit testing using mocks and stubs.
Simplifies integration testing - being able to swap one actor for another to put the system into the required state. For example, patching out just an authorization module.

Is Fetching and updating in same web service operation symantically correct

I know that WCF or any web service platform does not prevent the developers from mixing fetch and update in same operation. What I mean is mentioned below
List UpdateDate( SomeType Datacontract)
Syntactically this is correct format an is supported in WCF. But is it ok to do this in service oriented world, also is industry wide standard to support this.
One problem I see right away is we violate the very first law of SOA which is atomicity but are there any other issues associated?
It's wider than just WCF: any method that appears to be a Get/Fetch (i.e. by its name) should ideally not perform updates.
The classic Bad example is a Property Getter than alters the state of objects, thus introducing the possibility of unwanted side effects.

Using SOA principles over OOD in non-service code

Our architect has spoken about using SOA techniques throughout our codebase, even on interfaces that are not actually hosted as a service. One of his requests is that we design our interface methods so that we make no assumptions about the actual implementation. So if we have a method that takes in an object and needs to update a property on that object, we explictly need to return the object from the method. Otherwise we would be relying on the fact that Something is a reference type and c# allows us to update properties on a reference type by default.
So:
public void SaveSomething(Something something)
{
//save to database
something.SomethingID = 42;
}
becomes:
public Something SaveSomething(Something something)
{
//save to database
return new Something
{
//all properties here including new primary key from db
};
}
I can't really get my head around the benefits of this approach and was wondering if anyone could help?
Is this a common approach?
I think your architect is trying to get your code to have fewer side effects. In your specific example, there isn't a benefit. In many, many cases, your architect would be right, and you can design large parts of your application without side effects, but one place this cannot happen is during operations against a database.
What you need to do is get familiar with functional programming, and prepare for your conversations about cases like these with your architect. Remember his/her intentions are most likely good, but specific cases are YOUR domain. In this case, the side effect is the point, and you would most likely want a return type of bool to indicate success, but returning a new type doesn't make sense.
Show your architect that you understand limiting side effects, but certain side effects must be allowed (database, UI, network access, et cetera), and you will likely find that he or she agrees with you. Find a way to isolate the desired side effects and make them clear to him or her, and it will help your case. Your architect will probably appreciate it if you do this in the spirit of collaboration (not trying to shoot holes in his or her plan).
A couple resources for FP:
A great tutorial on Functional
Programming
Wikipedia's entry on Functional programming
Good luck, I hope this helps.