Fix: Run both sonar and clm scans in parallel
[ccsdk/cds.git] / ms / py-executor / resource_resolution / grpc / authorization.py
1 """Copyright 2020 Deutsche Telekom.
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 """
15 from collections import namedtuple
16 from typing import Any, Callable, List
17
18 from grpc import ClientCallDetails, StreamStreamClientInterceptor
19
20
21 class NewClientCallDetails(
22     namedtuple("_ClientCallDetails", ("method", "timeout", "metadata", "credentials")), ClientCallDetails
23 ):
24     """Namedtuple class to store metadata.
25
26     It's impossible to change original metadata in ClientCallDetails object
27     passed as a parameter to intercept method, so this class is going to get
28     original metadata tuple and add the authorization one.
29     """
30
31     pass
32
33
34 class AuthTokenInterceptor(StreamStreamClientInterceptor):
35     """Interceptor class to set authorization header.
36
37     Set authorization header (but it can be any header also) for a gRPC call.
38     """
39
40     def __init__(self, token: str, header: str = "authorization") -> None:
41         """Initialize interceptor.
42
43         Set token and header which should be set into call. By default header is "authorization".
44         Header have to be lowercase.
45
46         Args:
47             token (str): Token value to be set.
48             header (str, optional): Header name. It must be lowercase. Defaults to "authorization".
49         """
50         self.token: str = token
51         if not header.islower():
52             raise ValueError("Header must be lowercase.")
53         self.header: str = header
54
55     def intercept_stream_stream(
56         self, continuation: Callable, client_call_details: ClientCallDetails, request_iterator: Any
57     ) -> Any:
58         """Add header into metadata."""
59         metadata: List = list(client_call_details.metadata) if client_call_details.metadata is not None else []
60         metadata.append((self.header, self.token,))
61         new_client_call_details: NewClientCallDetails = NewClientCallDetails(
62             client_call_details.method, client_call_details.timeout, metadata, client_call_details.credentials
63         )
64         return continuation(new_client_call_details, request_iterator)