When do we use denyAll in spring security - java

I am a bit confused as to why someone would use #PreAuthorize("denyAll") for a method. As per the spring security documentation, it always evaluates to false.
If we are not going to allow access to a particular method, what is the point of keeping such a method. Why not comment it out? Or is it that it can still be accessed from within the same class?
I am trying to understand under what scenario such a requirement would arise.

One small clarification that I found in general for deny all was
#DenyAll annotation can be used to restrict business interface access from anyone, logged in or not. The method is still invokable from within the bean class itself.
So the jist is it can be used for a method which is public for some reason or have been exposed (perhaps it implements an interface) but should never be called directly from outside. However they can be called from inside(within the class).
here is the link
One real example that I can give you is (which is quite related with my work). We have 2 business unit with same code base. Now in one unit there is a feature where some mobile reseller can directly call a service which cancels the voucher directly to the operator end but in the other unit we needed to block this due to some business rule. Since we use the same interface in both system so in one system we blocked its usage using denyall
Hope this gives you a clear idea.

I decorate my service classes in this way which requires the individual inner service methods to override the denying class level PreAuth annotation. This ensures that each method in the class will be appropriately secured w/a fallback to denyAll.
I know this is old but I stumbled on it looking for the syntax for #PreAuthorize('denyAll') and thought I'd throw my 2cents in.

Related

understanding how custom metrics publisher work on hystrix

I am struggling a little bit to understand how to implement a Hystrix Metrics Publisher plugin.
Having read the documentation, it is still not clear how things are supposed to work together.
My goal is to write a plugin that will collect every metrics published by hystrix and write these metrics to a file on disk.
This file will later be collected and processed by an external tool giving us a good historical basis of the circuit’s behavior and problems.
The system where hystrix is running is a normal spring application. This said, I am also somewhat new on the java platform (although I am comfortable with the java language).
I thought that a first step towards understanding how the plugin could be implemented would be looking at the already implemented publishers. With this in mind, I looked at some of the implementations of hystrix-contrib directory.
I have chosen hystrix-codahale-metrics-publisher and hystrix-servo-metrics-publisher.
Both of them have a main class (servo is HystrixServoMetricsPublisher) which seems to register for receiving all possible kinds of metrics and some classes to deal with each kind of metric.
By looking at what I will call the main class, I see that, for example, there is a method called getMetricsPublisherForCommand that must return an implementation of the interface HystrixMetricsPublisherCommand.
Now questions start:
Question 1 I am assuming that once a plugin is registered every execution of every command on the context where the plugin is registered, and by the word command we can understand every execution of the execute() method of every class which inherits from HistrixCommand on that context, will generate a call to the getMetricsPublisherForCommand() method of my plugin. Is it true?
If so, there are a lot of low level implementations in hystrix such as thread pools and other, Should my getMetricsPublisherForCommand() implementation be thread-safe or I am guaranteed to receive calls in a sequential order? On what thread will my getMetricsPublisherForCommand() be executed?
Question 2 By looking at the documentation I am still not sure about what exactly the implementation of HystrixMetricsPublisherCommand to be returned by getMetricsPublisherForCommand() has to do. This is due to the fact that the HystrixMetricsPublisherCommand interface only specifies a method called initialize (). if it specified a method called, say, publish() I would conclude that the hystrix engine would call my custom getMetricsPublisherForCommand() method to get a metrics publisher on which it would call a publish() method to perform the custom publishing. But the initialize () method seens to be called only once when this given object is returned and I have found no other method the engine would call afterwards.
Also, by reading the documentation, I am under the impression that the implementation of HystrixMetricsPublisherCommand returned by getMetricsPublisherForCommand() will be somehow a singleton which completely breaks my understanding about how the thing is supposed to work.
The documentation say this:
The initialize() method will be called once-and-only-once to indicate when this instance can register with external services, start publishing metrics etc.
If you look at the servopublisher however you will notice that, unless I am completely and absolutely confused, the publishing stuff is performed right from the constructor. Now, if initialize() will be called to make some setup, how can I code my logic from the constructor where, unless the object is a singleton, it will be executed before any method including initialize () will have a chance to be called? In the other hand ,,, if this is a singleton, how can it run its constructor for every hystrix command?
May be I have missed something, I don't know ... but I need to understand conceptually what is going on here in order to implement my logic the right way. Thanks for your patience and I hope I have made myself clear enough in this long question.
First, recommend staying within the one (concise) question format.
Second, recommend using an existing implementation such as the default CodaHale (formerly DropWizard) implementation (which publishes to Graphite repository for Grafana consumption for example) to get it working.
HystrixPlugins.reset();
final WebApplicationContext springContext =
WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
HystrixPlugins plugins = HystrixPlugins.getInstance();
plugins.registerCommandExecutionHook(...);
// Good idea to use properties to enable/disable metrics generally...
// Using Spring type example...
if (hystrixMetricsEnabled.get()) {
plugins.registerMetricsPublisher(new HystrixCodaHaleMetricsPublisher(
getRegistry(springContext, sce.getServletContext())));
...
Otherwise the Hystrix documentation and full source of classes involved are publicly available:
https://github.com/Netflix/Hystrix/wiki/Plugins#metricspublisher

CDI Interceptors: How to intercept `this` calls or get the current proxy object?

I have a class that users will inherit from and implement two methods: navigateForwards() and navigateBackwards() (it's a wizard-like web application).
The user may want to add interceptors to these methods.
Another class (let's say it's part of a framework) will find the appropriate subclass, select() it and call the navigate(String) method which will call either navigateForwards() or navigateBackwards(). At that point interceptors won't work anymore since it's an unproxied method call. I could add interceptors to the navigate() method, but that's not the method subclasses are interested in overriding.
Is there an easy way to tell CDI to intercept a method that otherwise wouldn't be intercepted?
I came up with a couple of general approaches to solve this but none of them seems very promising:
Somehow get the proxy object that called me. That would require some sort of self-injection that replicates the select() call made in the "framework" class.
Get the list of interceptors for the method from CDI and call them manually. Somehow.
Use DeltaSpike's EnableInterceptorsProxyFactory http://deltaspike.apache.org/documentation/proxy.html to wrap this. That could be slow and/or uncover other limitations.
There may be another option with CDI extensions, but I'm not sure what an extension is capable of.
I've already tried turning everything upside-down and using decorators instead of a base class in the hopes that a call to the delegate object would get intercepted but it didn't, at least not in JBoss EAP 6.x (most likely 6.4, but it could be an earlier version when I tested).
The simplest solution I found (which for some obscure reason hadn't occurred to me before) is making navigate() static and passing the object explicitly (e.g. as self).
Looking from the outside the class gets a bit weird since it looks like it could have a regular non-static method but has a static one. OTOH it does the job and is easy to understand. I needed the current proxy object so I passed it in. It's trivial and it keeps interceptor behavior.
There are just a few calls that have to be changed in my project, but other projects will have different needs so it isn't a general solution unfortunately. That's why I am not accepting my own answer.

Unit Testable convention for Service "Helper Classes" in DDD pattern

I'm fairly new to Java and joining a project that leverages the DDD pattern (supposedly). I come from a strong python background and am fairly anal about unit test driven design. That said, one of the challenges of moving to Java is the testability of Service layers.
Our REST-like project stack is laid out as follows:
ServiceHandlers which handles request/response, etc and calls specific implementations of IService (eg. DocumentService)
DocumentService - handles auditing, permission checking, etc with methods such as makeOwner(session, user, doc)
Currently, something like DocumentService has repository dependencies injected via guice. In a public method like DocumentService.makeOwner, we want to ensure the session user is an admin as well as check if the target user is already an owner (leveraging the injected repositories). This results in some dupe code - one for both users involved to resolve the user and ensure membership, permissions, etc etc. To eliminate this redundant code, I want make a sort of super simpleisOwner(user, doc) call that I can concisely mock out for various test scenarios (such as throwing the exception when the user can't be resolved, etc). Here is where my googling fails me.
If I put this in the same class as DocumentService, I can't mock it while testing makeOwner in the same class (due to Mockito limitations) even though it somewhat feels like it should go here (option1).
If I put it in a lower class like DocumentHelpers, it feels slightly funny but I can easily mock it out. Also, DocumentHelpers needs the injected repository as well, which is fine with guice. (option 2)
I should add that there are numerous spots of this nature in our infant code base that are untestable currently because methods are non-statically calling helper-like methods in the same *Service class not used by the upper ServiceHandler class. However, at this stage, I can't tell if this is poor design or just fine.
So I ask more experienced Java developers:
Does introducing "Service Helpers" seem like a valid solution?
Is this counter to DDD principals?
If not, is there are more DDD-friendly naming convention for this aside from "Helpers"?
3 bits to add:
My googling has mostly come up with debates over "helpers" as static utility methods for stateless operations like date formatting, which doesn't fit my issue.
I don't want to use PowerMock since it breaks code coverage and is pretty ugly to use.
In python I'd probably call the "Service Helper" layer described above as internal_api, but that seems to have a different meaning in Java, especially since I need the classes to be public to unit test them.
Any guidance is appreciated.
That the user who initiates the action must be an admin looks like an application-level access control concern. DDD doesn't have much of an opinion about how you should do that. For testability and separation of concerns purposes, it might be a better idea to have some kind of separate non-static class than a method in the same service or a static helper though.
Checking that the future owner is already an owner (if I understand correctly) might be a different animal. It could be an invariant in your domain. If so, the preferred way is to rely on an Aggregate to enforce that rule. However, it's not clear from your description whether Document is an aggregate and if it or another aggregate contains the data needed to tell if a user is owner.
Alternatively, you could verify the rule at the Application layer level but it means that your domain model could go inconsistent if the state change is triggered by something else than that Application layer.
As I learn more about DDD, my question doesn't seem to be all that DDD related and more just about general hierarchy of the code structure and interactions of the layers. We ended up going with a separate DocumentServiceHelpers class that could be mocked out. This contains methods like isOwner that we can mock to return true or false as needed to test our DocumentService handling more easily. Thanks to everyone for playing along.

Limit access of a java class to some packages

I have a Java class which have some confidential information which I don't want to provide to any unauthorized class.
I want to access this class in some packages (classes from this packages are going to utilize confidential information), So that my secure class should be accessible in these packages.
Is there any way where I can check if caller of method is a authorized class from authorized package or not?
I know public/private/default all things (so please don't ask me to use it), but those are not useful here, because I want a class to be accessible in some packages(not one/same).
I feel that you are going in the wrong direction. It might be a design problem.
The security requirement is your business logic. You should implement your security policy somehow, not rely on the java language level visibility modifier or caller package names. since if you give your jar to someone, he can anyway get access to your "confidencial" class.
And moreover, a class is a type, something abstract. it should not contain "data". well sure sometimes conf information was written as static variable etc. However if some data is sensitive, it should not be written in class. It could be stored in database or encrypted file and so on. Once a request to the sensitive information comes, you check your implemented security policy, if it is allowed to access those data.
just my 2cents
The visibility modifiers in Java are not a security tool, but an OO design tool. Whatever you might do, if someone uses your class, it can access any private members of any class using reflection.
If your objects contain confidential information, leave these objects in your secure server.
You can create an Exception (no need for it to be thrown) and use the getStackTrace() to analize the call stack. I always found it ugly, though.
That said, anything that you put in a client machine is vulnerable to that machine; if you have something really confidential protect it in your server; make it available only as a service.
You can use the proxy pattern, implemented by the Proxy class in Java - it is designed exactly for your purpose.
Here is a how-to.
EDIT : AFAIK, you cannot use the regular Proxy mechanism for static methods, as the proxy and the proxied class must implement a common interface. However, there are more advanced tools, which may help you like javassist. Unfortunately I'm not familiar with it myself.
You might be able to leverage aspectj here. It's theoretically possible to intercept the call to a given classes' methods based on the current flow scope, and have the aspect throw an exception or something. I'm no aspectj expert though, but the "cflow" pointcut qualifier would be your most likely bet. Maybe something like this
! cflow(call(* com.mycom.AllowedClient.*))
I haven't tested this kind of pointcut, but i believe it would work.
You'd probably want compile time weaving in this case though (as opposed to load time weaving).
As a side note, i agree with some of the others that i think this is the wrong approach to take. You protect data. You protected function access based on logged in user permissions. You typically don't protect function calls from other classes.
Guideline 4-2 / EXTEND-2: Limit the accessibility of packages
Containers may hide implementation code by adding to the package.access security property. This property prevents untrusted classes from other class loaders linking and using reflection on the specified package hierarchy. Care must be taken to ensure that packages cannot be accessed by untrusted contexts before this property has been set.
This example code demonstrates how to append to the package.access security property. Note that it is not thread-safe. This code should generally only appear once in a system.
private static final String PACKAGE_ACCESS_KEY = "package.access";
static {
String packageAccess = Security.getProperty(PACKAGE_ACCESS_KEY);
Security.setProperty(PACKAGE_ACCESS_KEY,
(packageAccess == null || packageAccess.trim().isEmpty()
? "" : packageAccess + ",")
+ "xx.example.product.implementation.");
}

The missing "framework level" access modifier

Here's the scenario. As a creator of publicly licensed, open source APIs, my group has created a Java-based web user interface framework (so what else is new?). To keep things nice and organized as one should in Java, we have used packages with naming convention
org.mygroup.myframework.x, with the x being things like components, validators, converters, utilities, and so on (again, what else is new?).
Now, somewhere in class org.mygroup.myframework.foo.Bar is a method void doStuff() that I need to perform logic specific to my framework, and I need to be able to call it from a few other places in my framework, for example org.mygroup.myframework.far.Boo. Given that Boo is neither a subclass of Bar nor in the exact same package, the method doStuff() must be declared public to be callable by Boo.
However, my framework exists as a tool to allow other developers to create simpler more elegant R.I.A.s for their clients. But if com.yourcompany.yourapplication.YourComponent calls doStuff(), it could have unexpected and undesirable consequences. I would
prefer that this never be allowed to happen. Note that Bar contains other methods that are genuinely public.
In an ivory tower world, we would re-write the Java language and insert a tokenized analogue to default access, that would allow any class in a package structure of our choice to access my method, maybe looking similar to:
[org.mygroup.myframework.*] void doStuff() { .... }
where the wildcard would mean any class whose package begins with org.mygroup.myframework can call, but no one else.
Given that this world does not exist, what other good options might we have?
Note that this is motivated by a real-life scenario; names have been changed to protect the guilty. There exists a real framework where peppered throughout its Javadoc one will find public methods commented as "THIS METHOD IS INTERNAL TO MYFRAMEWORK AND NOT
PART OF ITS PUBLIC API. DO NOT CALL!!!!!!" A little research shows these methods are called from elsewhere within the framework.
In truth, I am a developer using the framework in question. Although our application is deployed and is a success, my team experienced so many challenges that we want to convince our bosses to never use this framework again. We want to do this in a well thought out presentation of the poor design decisions made by the framework's developers, and not just as a rant. This issue would be one (of several) of our points, but we just can't put a finger on how we might have done it differently. There has already been some lively discussion here at my workplace, so I wondered what the rest of the world would think.
Update: No offense to the two answerers so far, but I think you've missed the mark, or I didn't express it well. Either way allow me to try to illuminate things. Put as simply as I can, how should the framework's developers have refactored the following. Note this is a really rough example.
package org.mygroup.myframework.foo;
public class Bar {
/** Adds a Bar component to application UI */
public boolean addComponentHTML() {
// Code that adds the HTML for a Bar component to a UI screen
// returns true if successful
// I need users of my framework to be able to call this method, so
// they can actually add a Bar component to their application's UI
}
/** Not really public, do not call */
public void doStuff() {
// Code that performs internal logic to my framework
// If other users call it, Really Bad Things could happen!
// But I need it to be public so org.mygroup.myframework.far.Boo can call
}
}
Another update: So I just learned that C# has the "internal" access modifier. So perhaps a better way to have phrased this question might have been, "How to simulate/ emulate internal access in Java?" Nevertheless, I am not in search of new answers. Our boss ultimately agreed with the concerns mentioned above
You get closest to the answer when you mention the documentation problem. The real issue isn't that you can't "protect" your internal methods; rather, it is that the internal methods pollute your documentation and introduce the risk that a client module may call an internal method by mistake.
Of course, even if you did have fine grained permissions, you still aren't going to be able to prevent a client module from calling internal methods---the jvm doesn't protect against reflection based calls to private methods anyway.
The approach I use is to define an interface for each problematic class, and have the class implement it. The interface can be documented solely in terms of client modules, while the implementing class can provide what internal documentation you desire. You don't even have to include the implementation javadoc in your distribution bundle if you don't want to, but either way the boundary is clearly demarcated.
As long as you ensure that at runtime only one implementation is loaded per documentation-interface, a modern jvm will guarantee you don't suffer any performance penalty for using it; and, you can load harness/stub versions during testing for an added bonus.
The only idea that I can think in order to supply this missing "Framework level access modifier" is CDI and a better design.
If you have to use a method from very different classes and packages in various (but few) situations THERE WILL BE certainly a way to redesign those classes in order to make those methods "private" and inacessible.
There is no support in Java language for such kind of access level (you would like something like "internal" with namespace). You can only restrict access to package level (or the known inheritance public-protected-private model).
From my experience, you can use Eclipse convention:
create a package called "internal" that all class hierarchy (including sub-packages) of this package will be considered as non-API code and could be changed anytime with no guarantee for your users. In that non-API code, use public methods whenever you like. Since it is only a convention and it is not enforced by the JVM or Java compiler, you cannot prevent users from using the code, but at least let them know that these classes were not meant to be used by 3rd parties.
By the way, in Eclipse platform source code, there is a complex plugin model that enforces you not to use internal code of other plugins by implementing custom class loader for each plugin that prevents loading classes that should be "internal" in these plugins.
Interfaces and dynamic proxies are sometimes used to make sure you only expose methods that you do want to expose.
However that comes at a fairly hefty performance cost, if your methods are called very often.
Using the #Deprecated annotation might also be an option, although it won't stop external users invoking your "framework private" methods, they can't say they hadn't been warned.
In general I don't think you should worry about your users deliberately shooting themselves in the foot too much, so long as you made it clear to them that they shouldn't use something.

Categories