Hangfire: How to restrict allowed methods in Hangfire Server

Created on 16 Apr 2019  路  5Comments  路  Source: HangfireIO/Hangfire

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?

question

Most helpful comment

All 5 comments

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.

https://github.com/HangfireIO/Hangfire/blob/23d81f5ca61c3238d7da3591fd2f5d386dd0532e/src/Hangfire.Core/Client/BackgroundJobFactory.cs#L112

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thurfir picture thurfir  路  4Comments

pwueje picture pwueje  路  4Comments

tompazourek picture tompazourek  路  3Comments

nsnail picture nsnail  路  3Comments

cbmek picture cbmek  路  3Comments