| 1 |
# Copyright 2020 The 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 |
"""Server of the Python AsyncIO example of customizing authentication mechanism.""" |
| 15 |
|
| 16 |
import argparse |
| 17 |
import asyncio |
| 18 |
import logging |
| 19 |
from typing import Awaitable, Callable, Tuple |
| 20 |
|
| 21 |
import _credentials |
| 22 |
import grpc |
| 23 |
|
| 24 |
helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( |
| 25 |
"helloworld.proto") |
| 26 |
|
| 27 |
_LOGGER = logging.getLogger(__name__) |
| 28 |
_LOGGER.setLevel(logging.INFO) |
| 29 |
|
| 30 |
_LISTEN_ADDRESS_TEMPLATE = 'localhost:%d' |
| 31 |
_SIGNATURE_HEADER_KEY = 'x-signature' |
| 32 |
|
| 33 |
|
| 34 |
class SignatureValidationInterceptor(grpc.aio.ServerInterceptor): |
| 35 |
|
| 36 |
def __init__(self): |
| 37 |
|
| 38 |
def abort(ignored_request, context: grpc.aio.ServicerContext) -> None: |
| 39 |
context.abort(grpc.StatusCode.UNAUTHENTICATED, 'Invalid signature') |
| 40 |
|
| 41 |
self._abort_handler = grpc.unary_unary_rpc_method_handler(abort) |
| 42 |
|
| 43 |
async def intercept_service( |
| 44 |
self, continuation: Callable[[grpc.HandlerCallDetails], |
| 45 |
Awaitable[grpc.RpcMethodHandler]], |
| 46 |
handler_call_details: grpc.HandlerCallDetails |
| 47 |
) -> grpc.RpcMethodHandler: |
| 48 |
# Example HandlerCallDetails object: |
| 49 |
# _HandlerCallDetails( |
| 50 |
# method=u'/helloworld.Greeter/SayHello', |
| 51 |
# invocation_metadata=...) |
| 52 |
method_name = handler_call_details.method.split('/')[-1] |
| 53 |
expected_metadata = (_SIGNATURE_HEADER_KEY, method_name[::-1]) |
| 54 |
if expected_metadata in handler_call_details.invocation_metadata: |
| 55 |
return await continuation(handler_call_details) |
| 56 |
else: |
| 57 |
return self._abort_handler |
| 58 |
|
| 59 |
|
| 60 |
class SimpleGreeter(helloworld_pb2_grpc.GreeterServicer): |
| 61 |
|
| 62 |
async def SayHello(self, request: helloworld_pb2.HelloRequest, |
| 63 |
unused_context) -> helloworld_pb2.HelloReply: |
| 64 |
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) |
| 65 |
|
| 66 |
|
| 67 |
async def run_server(port: int) -> Tuple[grpc.aio.Server, int]: |
| 68 |
# Bind interceptor to server |
| 69 |
server = grpc.aio.server(interceptors=(SignatureValidationInterceptor(),)) |
| 70 |
helloworld_pb2_grpc.add_GreeterServicer_to_server(SimpleGreeter(), server) |
| 71 |
|
| 72 |
# Loading credentials |
| 73 |
server_credentials = grpc.ssl_server_credentials((( |
| 74 |
_credentials.SERVER_CERTIFICATE_KEY, |
| 75 |
_credentials.SERVER_CERTIFICATE, |
| 76 |
),)) |
| 77 |
|
| 78 |
# Pass down credentials |
| 79 |
port = server.add_secure_port(_LISTEN_ADDRESS_TEMPLATE % port, |
| 80 |
server_credentials) |
| 81 |
|
| 82 |
await server.start() |
| 83 |
return server, port |
| 84 |
|
| 85 |
|
| 86 |
async def main() -> None: |
| 87 |
parser = argparse.ArgumentParser() |
| 88 |
parser.add_argument('--port', |
| 89 |
nargs='?', |
| 90 |
type=int, |
| 91 |
default=50051, |
| 92 |
help='the listening port') |
| 93 |
args = parser.parse_args() |
| 94 |
|
| 95 |
server, port = await run_server(args.port) |
| 96 |
logging.info('Server is listening at port :%d', port) |
| 97 |
await server.wait_for_termination() |
| 98 |
|
| 99 |
|
| 100 |
if __name__ == '__main__': |
| 101 |
logging.basicConfig(level=logging.INFO) |
| 102 |
asyncio.run(main()) |