I'd like to restrict which jobs are processed by Hangfire server to a certain set of whitelisted methods or classes. For example, if client A queues a Hangfire job that uses a non-whitelisted method, then server B should not execute it.
I thought of using Job Filters for this purpose
class AllowedJobFilter : JobFilterAttribute
{
var getMethodInfo(Action a)
{
return a.Method;
}
void OnPerforming(PerformingContext context) {
// Only allow jobs which run Console.WriteLine()
var allowedMethods = new List<MethodInfo>() {
getMethodInfo(Console.WriteLine),
};
if (!allowedMethods.Contains(context.BackgroundJob.Job.Method)
{
throw Exception("Method is not allowed");
}
}
...
GlobalConfiguration.Configuration
.UseFilter(new AllowedJobFilter())
I'm not sure this approach will work as expected (since there's nothing that says Hangfire can't catch and ignore exceptions from the JobFilterAttribute), and this approach will fail the job instead of skipping it, which may not be desirable. Is there a better way to restrict which jobs can run on a server?
How come you can't control/enforce what jobs are enqueued/scheduled by your clients? Maybe remove their low-level access to Hangfire and only provide access to a wrapper-layer which forwards the job to Hangfire if it meets the whitelist requirements.
I do plan to do so but I prefer to layer security. I don't want it to be possible to execute completely arbitrary code on the workers if the database or client is compromised.
You can implement the OnCreating method in your JobFilter and set context.Canceled to true. As you can see here jobs can be ignored during creation using this approach.
You should be able to set Canceled as well in the OnPerforming as stated here https://github.com/HangfireIO/Hangfire/blob/23d81f5ca61c3238d7da3591fd2f5d386dd0532e/src/Hangfire.Core/Server/BackgroundJobPerformer.cs#L147
Thanks! This seems like it should work. Would this be worth adding to the JobFilter documentation? I'd be happy to look into the details in the code and document it.
Most helpful comment
You should be able to set Canceled as well in the OnPerforming as stated here https://github.com/HangfireIO/Hangfire/blob/23d81f5ca61c3238d7da3591fd2f5d386dd0532e/src/Hangfire.Core/Server/BackgroundJobPerformer.cs#L147