Injection Methods/Variables: public or Not? - java

Many Java frameworks allow class members used for injection to be declared non-public. For example, injected variables in Spring and EJB 3 may be private. JPA allows properties of a persistent class to be protected or package-private.
We know it's better to declare methods non-public if you can. That being said, if I'm not mistaken, allowing these frameworks to access non-public members only works with the default Java security manager. Doesn't it mean that custom code can also gain access to non-public member via reflection by calling setAccessible(), which would compromise security?
Which begs this question: What is the best practice when setting the access level for injection methods?

Typically a class needs to opt-in to a persistence mechanism. For instance, Java serialisatoin requires a class to implement java.io.Serializable. It is the responsibility of classes that implement Serializable to ensure that they are secure. Where a library allows poking of privates through an external configuration file, then that should not be trusted - reflection is really dangerous and its use is usually messed up.
Of course if you do find a vulnerability, please report it to the appropriate group.

If you're running untrusted code in the same JVM as your application, and you're using the default security manager settings, then yeah, that could be a security hole. This is something you need to be aware of, but in practice, this situation is pretty rare.

Related

Can I enforce visibility using java.security?

This follows on from this question, which is about Groovy (a superset/modernisation of Java), where there is, seemingly, essentially no information-hiding and no encapsulation whatsoever.
But in Java too of course there is reflection, meaning that private, protected and package-private are essentially pointless, or worse: create a false sense of security.
In Java, is there any way to enforce visibility, of some kind, not necessarily in the sense of specifically enforcing the above visibility modifiers, and package-private, using a SecurityManager? I've only just started looking into the latter and I can't see any very obvious way of accomplishing something like that. But it would seem that some developers must ship code where some classes and methods do not have completely public visibility... so how is it done?
PS in the Lucene package, with which I'm a bit familiar, I notice that quite a lot of classes turn out to be final (which has sometimes caused me some head-scratching...) but I'm pretty sure, although not certain, that reflection can be used to squash that modifier
Can I write my classes to be setAccessible-proof regardless of SecurityManager configuration? ... Or am I at the mercy of whoever manages the configuration?
You can't and you most certainly are.
Anybody who has access to your code can configure their JVM and SecurityManager as they please. (more details below)
Is setAcessible legitimate? Why does it exist?
The Java core classes use it as an easy way to access stuff that has to remain private for security reasons. As an example, the Java Serialization framework uses it to invoke private object constructors when deserializing objects. Someone mentioned System.setErr, and it would be a good example, but curiously the System class methods setOut/setErr/setIn all use native code for setting the value of the final field.
Another obvious legitimate use are the frameworks (persistence, web frameworks, injection) that need to peek into the insides of objects.
And finally...
Java access modifiers are not intended to be a security mechanism.
So what can I actually do?
You should take a deeper look into Security Providers section of the Java SE Security documentation:
Applications do not need to implement security themselves. Rather,
they can request security services from the Java platform. Security
services are implemented in providers
The access control architecture in the Java platform protects access to sensitive resources (for example, local files) or sensitive application code (for example, methods in a class). All access control decisions are mediated by a security manager, represented by the java.lang.SecurityManager class. A SecurityManager must be installed into the Java runtime in order to activate the access control checks.
Java applets and Java™ Web Start applications are automatically run with a SecurityManager installed. However, local applications executed via the java command are by default not run with a SecurityManager installed. In order to run local applications with a SecurityManager, either the application itself must programmatically set one via the setSecurityManager method (in the java.lang.System class), or java must be invoked with a -Djava.security.manager argument on the command line.
I recommend you read further about this on the official security documentation
https://docs.oracle.com/javase/7/docs/technotes/guides/security/overview/jsoverview.html

Is it advantageous to create a Spring bean when I can access the only static method directly with class name

I think my understanding of spring beans is a bit off.
I was working on my project and I was thinking about this situation.
Say I have class Foo
class Foo(){
public void doSomething(Object a , Object b){ // input parameters does not matter actually.
//do something
}
}
If I am using this class in another class like :
class Scheduler{
....
#Autowired
private Foo foo;
someMethod(){
foo.doSomeThind(a,b);
}
....
}
In the above case Instead of Autowiring the Foo, I can make doSomeThing static and directly use Foo.doSomeThing(a,b)
I was just wondering if there any advantage of creating a bean or if there any disadvantage of using static methods like this?
If they are same, When should I go for spring bean and when should do I simply use a static method?
Static methods are ok for small utility functions. The limitation of static code is that you can't change it's behavior without changing code itself.
Spring, on the other hand, gives you flexibility.
IoC. Your classes don't know about the exact implementation of their dependencies, they just rely on the API defined by interface. All connections are specified in configuration, that can be different for production/test/other.
Power of metaprogramming. You can change the behavior of your methods by merely marking them (via annotations of in xml). Thus, you can wrap method in transactions, make it asynchronous or scheduled, add custom AOP interceptors, etc.
Spring can instrument your POJO method to make it an endpoint to remote web service/RPC.
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/
Methods in Spring beans can benefit from dependency injection whereas static methods cannot. So, an ideal candidate for static method is the one that does things more or less independently and is not envisioned to ever need any other dependency (say a DAO or Service)
People use Spring not because of some narrow specific futures that cannot be replaced by static classes or DI or whatever. People use Spring because of a more abstracted features and ideas it provide out of the box.
Here is a nice quote from Someone`s blog:
Following are some of the major benefits offered by the Spring Framework:
Spring Enables POJO Programming. Spring enables programmers to develop enterprise-class applications using POJOs. With Spring, you are able to choose your own services and persistence framework. You program in POJOs and add enterprise services to them with configuration files. You build your program out of POJOs and configure it, and the rest is hidden from you.
Spring Provides Better Leverage. With Spring, more work can be done with each line of code. You code in a more fast way, and maintain less. There’s no transaction processing. Spring allows you to build configuration code to handle that. You don’t have to close the session to manage resources. You don’t have to do configuration on your own. Besides you are free to manage the exceptions at the most appropriate place not facing the necessity of managing them at this level as the exceptions are unchecked.
Dependency Injection Helps Testability. Spring greatly improves your testability through a design pattern called Dependency Injection (DI). DI lets you code a production dependency and a test dependency. Testing of a Spring based application is easy because all the related environment and dependent code is moved into the framework.
Inversion of Control Simplifies JDBC. JDBC applications are quite verbose and time-taking. What may help is a good abstraction layer. With Spring you can customize a default JDBC method with a query and an anonymous inner class to lessen much of the hard work.
Spring’s coherence. Spring is a combination of ideas into a coherent whole, along with an overall architectural vision to facilitate effective use, so it is much better to use Spring than create your own equivalent solution.
Basis on existing technologies. The spring framework is based on existing technologies like logging framework, ORM framework, Java EE, JDK timers, Quartz and other view related technologies.
During unit testing you have more flexibility using bean because you can easily mock your bean methods. However, that is not the same with static methods where you may have to resort to PowerMock (which I recommend you stay away from if you can).
It actually depends on the role of the component you are referring to: Is this feature:
An internal tooling: you can use static (you wouldn't wrap Math.abs or String.trim in a bean)
Or a module of the project: design it to be a bean/module-class (a DAO class is best modular to be able to change/mock it easily)
Globally, you should decide w.r.t your project design what are beans and what are not. I think many dev put too much stuff inside bean by default and forget that every bean is an public api that will be more difficult to maintain when refactoring (i.e. restrained visibility is a good thing).
In general, there are already several answers describing the advantages of using spring beans, so I won't develop on that. And also note that you don't need spring to use bean/module design. Then here are the main reasons not to use it:
type-safety: Spring bean are connected "only" at runtime. Not using it, you (can) get much more guaranties at compile time
It can be easier to track your code as there is no indirection due to IoC
You don't need the additional spring dependency/ies which get quite heavy
Obviously, the (3) is correct only if you don't use spring at all in your project/lib.
Also, The (1) and (2) really depend on how you code. And the most important is to have and maintain a clean, readable code. Spring provides a framework that forces you to follow some standard that many people like. I personally don't because of (1) and (2), but I have seen that in heterogeneous dev teams it is better to use it than nothing. So, if not using spring, you have to follow some strong coding guidelines.

Understanding Java reflection drawbacks

I am trying to understand the drawbacks as mentioned in Java docs
Security Restrictions
Reflection requires a runtime permission which may not be present when
running under a security manager.
What are the runtime permissions that reflection needs? What is security manager in this context? Is this drawback specific to Applets only?
Exposure of Internals
Since reflection allows code to perform operations that would be
illegal in non-reflective code, such as accessing private fields and
methods, the use of reflection can result in unexpected side-effects,
which may render code dysfunctional and may destroy portability.
Reflective code breaks abstractions and therefore may change behavior
with upgrades of the platform.
How reflection can break abstraction? and how does it affect with upgrades of the platform.
Please help me in clarifying these. Thanks a lot.
First you should always ask to yourself why reflection in your code. Aren't you able to do the operations without reflection. If YES then only you should use reflection. Reflection uses meta information about class,variables and methods this increase overhead, performance issue and security threat.
To understand the drawback of reflection in detail visit http://modernpathshala.com/Forum/Thread/Interview/310/what-are-the-drawbacks-of-reflection
Security "sandboxes" aren't limited to applets. Many other environments which permit less-than-completely-trusted "plug-in" code -- webservers, IDEs, and so on -- limit what the plug-ins can do to protect themselves from errors in the plug-in (not to mention deliberately malicious code).
A framework class called dependency container was used to analyzes the dependencies of a class. With this analysis, it was able to create an instance of the class and inject the objects into the defined dependencies via Java Reflections. This eliminated the hard dependencies. That way the class could be tested in isolation, ex. by using mock objects. This was Dagger 1.
Main disadvantages of this process were two folds. First, the Reflection is slowing itself and second, it used to perform dependency resolution at runtime, leading to unexpected crashes.

CDI - Injecting Classes at runtime

I'm working on a project, where it is needed to load some classes at runtime. The classes to load are parts of CDI-Containers and have to be able to inject some stuff. The "loading class" itself is a part of a CDI-Container as well.
Now comes my problem. It is possible to load and instantiate any class via reflection, but in this case it would not be possible for the classes to be loaded to get anything injected. So it is needed to get an instance of these classes as it would be internally done by the server like when we would use the annotation #javax.inject.Inject.
Is there any way to load the classes of another CDI-container in a way that they can still work with Injections (otherwise it would not make any sense^^)? Maybe there is any kind of Class which is responsible for for handling all of these classes so that I can simply tell it the name of the class to load (as I would do it with reflections)... ?
Thanks
You can use the BeanManager API to query and laod contextual references based on bean types.
Review your design carefully, as it sounds like you're entering into "procedural style" programming rather than OO. This is likely the first of many problems with your design you're likely to encounter.
I have an idea that might work though; can you make these classes implement a certain interface? If they do, you can use normal #Inject annotations in your code with the interface, then stuff the class implementation into a /lib directory on a server. This, combined with CDI alternatives may be able to get you what you want.
A better approach may be to use reflection and some kind of factory...

Dynamic object registration in Java

I would like to add some dynamic behavior to an application, preferably without resorting to reflection, so I am looking at object registration.
The approach I am thinking is simple: in a class (say Base) which gets to be loaded early enough, a registry (e.g., a HashMap) of plugin objects will be maintained, each of which will later on be used for invoking some of their methods.
The question is, how to register those plugins in Base without any prior knowledge of their existence (so that the application can be dynamically extended via more such plugins). Not knowing them beforehand means a ClassLoader or any reference to their classes cannot be used, thus even with static initialization, registration code cannot be added (since the plugin classes will not be loaded early enough, so the Base class will start executing without knowing them).
Is there any simple solution to the above scenario?
There's several ways of implementing plugin mechanisms, ultimately you need to either scan for implementations of an interface or annotations. Is it important to you that you implement this yourself? There's already libraries that do this (jspf for example).
If you're not interested in reflection, then the code must either adhere to a known interface. Otherwise you'll need to use reflection somewhere to map between what the plugin class(es) provide, and what the "base" code knows how to call.
could you use something like spring and dependency injection ? if you can, each plug in could be a initializing bean so its loaded on start up and in its init method call back to the base to register itself, if not through a direct dependency injection. that obviously uses reflection in background so not sure if that excludes this as your preferred solution...
on another note, typically, looking for classes is not fool proof esp if you could have multiple class loaders :-(

Categories