1# Copyright 2017 gRPC authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Interceptor that ensures a specific header is present.""" 15 16import grpc 17 18 19def _unary_unary_rpc_terminator(code, details): 20 21 def terminate(ignored_request, context): 22 context.abort(code, details) 23 24 return grpc.unary_unary_rpc_method_handler(terminate) 25 26 27class RequestHeaderValidatorInterceptor(grpc.ServerInterceptor): 28 29 def __init__(self, header, value, code, details): 30 self._header = header 31 self._value = value 32 self._terminator = _unary_unary_rpc_terminator(code, details) 33 34 def intercept_service(self, continuation, handler_call_details): 35 if (self._header, 36 self._value) in handler_call_details.invocation_metadata: 37 return continuation(handler_call_details) 38 else: 39 return self._terminator 40