Package: django-header-filter
django-header-filterdjango-header-filterimplements header-based filtering for Django
applications. That is, it allows to reject requests whose headers are
not compliant to a user-defined set of rules.Compatibilitydjango-header-filteris compatible with:Python 3.5, 3,6, 3.7, 3.8Django 1.11, 2.0, 2.1, 2.2Installation$pipinstalldjango-header-filterQuickstartImagine you need to make sure that every request routed to a specific
view has a header namedX-PlanetwithMarsas value.This constraint can be implemented as follows:# views.pyfromdjango.httpimportHttpResponsefromheader_filterimportEnforce,Header,header_rules@header_rules([Enforce(Header('HTTP_X_PLANET','Mars'))])defdo_things(request):# ...returnHttpResponse()In short:the@header_rulesdecorator applies a list ofrulesto the viewin the example that list is made up of one single rule,Enforce,
which allows the request to be handed over to the view only if the
respectivematcherholds true (otherwise a400 Bad Requestresponse
is returned to the client)theHeadermatcher is responsible for checking whether a header
compliant to your needs belongs to the request or notMatchersMatchers are the basic building blocks for defining header-based
filters. Their job is to check whether user-defined header combinations
belong to the request or not.django-header-filterprovides the following matchers:HeaderTheHeadermatcher must be instantiated with two arguments: the first
argument is thenameof the header; the second one is itsvalue.The header name must be a string.NOTE: header names in Django are usually different from the ones
that a client actually sends, due to some string manipulations that
happen server side (refer to thedocsfor details). Matchers do
nothing to guess the original names, so be sure to initialize them with
the right format (e.g.X-PlanetbecomesHTTP_X_PLANETwhen used for
aHeadermatcher instantiation).The type of the header value may be one of the following:a stringa compiled regular expression object (as returned byre.compile())an iterable of stringsTheHeadermatcher will check whether a header with the given name and
value actually exists. As far as the value is concerned, the matching
logic depends on its type:exact match for stringsregexp match for regular expression objectsmembership for iterablesimportrefromheader_filterimportHeader# matches X-Planet: MarsHeader('HTTP_X_PLANET','Mars')# matches X-Planet: Mars or X-Planet: MercuryHeader('HTTP_X_PLANET',re.compile(r'^M.*'))# matches X-Planet: Mars or X-Planet: VenusHeader('HTTP_X_PLANET',['Mars','Venus'])HeaderRegexpTheHeaderRegexpmatcher is similar to theHeadermatcher, but the
arguments it takes at instantiation may be:compiled regular expression objectsregexp pattern stringsboth for name and value.importrefromheader_filterimportHeaderRegexp# matches X-Planet: Mars and X-Planet: MercuryHeaderRegexp(r'^HTTP_X_PLANET$',re.compile(r'^M.*'))# same as aboveHeaderRegexp(re.compile(r'^HTTP_X_PLANET$'),r'^M.*')Matchers are composableMatchers can be aggregated into composite matchers by means of bitwise
operators:&(and)|(or)^(xor)~(not)A composite matcher allows for checks that cannot be expressed by just
using the matchers described above.fromheader_filterimportHeader# matches if X-Planet: Mars and X-Rover: Curiosity are both presentHeader('HTTP_X_PLANET','Mars')&Header('HTTP_X_ROVER','Curiosity')# matches if at least one of X-Planet: Mars and X-Rover: Curiosity is presentHeader('HTTP_X_PLANET','Mars')|Header('HTTP_X_ROVER','Curiosity')# matches if exactly one of X-Planet: Mars and X-Rover: Curiosity is presentHeader('HTTP_X_PLANET','Mars')^Header('HTTP_X_ROVER','Curiosity')# matches if X-Planet: Mars is not present~Header('HTTP_X_PLANET','Mars')From the usage point of view, there's no difference between a simple
matcher and a composite one: both can be used in the same contexts.
Besides, there's no limit in how much matchers can be combined: simple
matchers can be combined into composites, which in turn can be used as
atoms for further composition.fromheader_filterimportHeader# matches if X-Planet: Mars and X-Rover: Curiosity aren't both present~(Header('HTTP_X_PLANET','Mars')&Header('HTTP_X_ROVER','Curiosity'))# matches if# X-Planet: Mars is not present, and# exactly one of X-Rover: Curiosity and X-Aliens: false is present(~Header('HTTP_X_PLANET','Mars')&(Header('HTTP_X_ROVER','Curiosity')^Header('HTTP_X_ALIENS','false')))Matchers support string representationA matcher can be inspected by printing its string representation.fromheader_filterimportHeadermatcher1=Header('HTTP_X_PLANET','Mars')matcher2=Header('HTTP_X_ROVER','Curiosity')composite=~(matcher1&matcher2)print(repr(composite))# ~(Header('HTTP_X_PLANET', 'Mars') & Header('HTTP_X_ROVER', 'Curiosity'))RulesRules rely on matchers to implement actual header-based filtering.django-header-filterprovides two rules:EnforceandForbid. Both
require a matcher to be instantiated, but behave differently:Enforcerejects requests whose headersdo notcomply with its
matcherForbidrejects requests whose headersdocomply with its
matcherfromheader_filterimportEnforce,Forbid,Header# rejects requests *lacking* an X-Planet: Mars headerEnforce(Header('HTTP_X_PLANET','Mars'))# rejects requests *containing* an X-Planet: Mars headerForbid(Header('HTTP_X_PLANET','Mars'))Rules can use matchers of any type (simple or composite).Custom reject responsesBy default rules reject requests with adjango.http.HttpResponseBadRequestresponse.
The default behavior can be overridden by passing an optional argument
at rule instantiation, namedreject_response. The argument must be an
instance of a Django Response, which will be returned to the client
whenever the rule triggers the rejection of a request.fromdjango.httpimportHttpResponseNotFoundfromheader_filterimportEnforce,Header# rejects requests *lacking* an X-Planet: Mars header with a 404 responseEnforce(Header('HTTP_X_PLANET','Mars'),reject_response=HttpResponseNotFound(reason='Sorry!'))@header_rulesdecoratorThe@header_rulesdecorator binds a list of rules to a view. The
decorator checks the headers of every request routed to that view
against each rule of the list, in order. The first rule that results in
a rejection determines the response that will be sent back to the
client. If no rule triggers a rejection, the request is handed over to
the view for regular processing.fromdjango.httpimportHttpResponsefromheader_filterimportEnforce,Forbid,Header,header_rules# requests *lacking* an X-Planet: Mars header or *containing* an# X-Rover: Curiosity header will be rejected@header_rules([Enforce(Header('HTTP_X_PLANET','Mars')),Forbid(Header('HTTP_X_ROVER','Curiosity')),])defdo_things(request):# ...returnHttpResponse()@header_rulesworks fine with class-based views as well, by means of@method_decorator.fromdjango.httpimportHttpResponsefromdjango.utils.decoratorsimportmethod_decoratorfromdjango.viewsimportViewfromheader_filterimportEnforce,Forbid,Header,header_rulesclassDoThings(View):# requests *lacking* an X-Planet: Mars header or *containing* an# X-Rover: Curiosity header will be rejected@method_decorator(header_rules([Enforce(Header('HTTP_X_PLANET','Mars')),Forbid(Header('HTTP_X_ROVER','Curiosity')),]))defget(self,request,*args,**kwargs):# ...returnHttpResponse()HeaderFilterMiddlewareBy using theHeaderFilterMiddlewaremiddleware, a list of rules can be
applied globally, at application level. Every request will be then
checked against the global rule list, independently of views.For this to work you need to properly tweak your Django settings module,
as follows:# settings.pyfromheader_filterimportEnforce,HeaderMIDDLEWARE=[# ...'header_filter.HeaderFilterMiddleware',# ...]HEADER_FILTER_RULES=[Enforce(Header('HTTP_X_PLANET','Mars')),# ...additional rules...]LicenseSee:LICENSEMIT LicenseCopyright (c) 2019 Fabio SangiovanniPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.