Skip to content

Commit

Permalink
Merge pull request #139 from whdalsrnt/master
Browse files Browse the repository at this point in the history
feat: apply internal authentication
  • Loading branch information
whdalsrnt authored Jan 6, 2024
2 parents 2619084 + 88fb404 commit 38360c3
Show file tree
Hide file tree
Showing 3 changed files with 172 additions and 129 deletions.
9 changes: 7 additions & 2 deletions src/spaceone/core/handler/authentication_handler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
import logging

from spaceone.core import cache
from spaceone.core import cache, config
from spaceone.core.connector.space_connector import SpaceConnector
from spaceone.core.auth.jwt import JWTAuthenticator, JWTUtil
from spaceone.core.transaction import get_transaction
Expand Down Expand Up @@ -43,9 +43,11 @@ def verify(self, params: dict) -> None:

@cache.cacheable(key="handler:authentication:{domain_id}:public-key", alias="local")
def _get_public_key(self, domain_id: str) -> str:
system_token = config.get_global("TOKEN")

_LOGGER.debug(f"[_get_public_key] get jwk from identity service: {domain_id}")
response = self.identity_conn.dispatch(
"Domain.get_public_key", {"domain_id": domain_id}
"Domain.get_public_key", {"domain_id": domain_id}, token=system_token
)

return response["public_key"]
Expand All @@ -54,13 +56,16 @@ def _get_public_key(self, domain_id: str) -> str:
key="handler:authentication:{domain_id}:client:{client_id}", alias="local"
)
def _check_app(self, client_id, domain_id) -> list:
system_token = config.get_global("TOKEN")

_LOGGER.debug(f"[_check_app] check app from identity service: {client_id}")
response = self.identity_conn.dispatch(
"App.check",
{
"client_id": client_id,
"domain_id": domain_id,
},
token=system_token,
)

return response.get("permissions", [])
Expand Down
55 changes: 35 additions & 20 deletions src/spaceone/core/pygrpc/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,25 @@ def service_name(self):
return self.pb2.DESCRIPTOR.services_by_name[self.__class__.__name__].full_name

def _load_grpc_messages(self):
service_desc: ServiceDescriptor = self._desc_pool.FindServiceByName(self.service_name)
service_desc: ServiceDescriptor = self._desc_pool.FindServiceByName(
self.service_name
)
for method_desc in service_desc.methods:
self._grpc_messages[method_desc.name] = {
'request': method_desc.input_type.name,
'response': method_desc.output_type.name
"request": method_desc.input_type.name,
"response": method_desc.output_type.name,
}

def _check_variables(self):
if not hasattr(self, 'pb2'):
raise Exception(f'gRPC Servicer has not set <pb2> variable. (servicer={self.__class__.__name__})')
if not hasattr(self, "pb2"):
raise Exception(
f"gRPC Servicer has not set <pb2> variable. (servicer={self.__class__.__name__})"
)

if not hasattr(self, 'pb2_grpc'):
raise Exception(f'gRPC Servicer has not set <pb2_grpc> variable. (servicer={self.__class__.__name__})')
if not hasattr(self, "pb2_grpc"):
raise Exception(
f"gRPC Servicer has not set <pb2_grpc> variable. (servicer={self.__class__.__name__})"
)

def _get_grpc_servicer(self):
grpc_servicer = None
Expand All @@ -63,14 +69,18 @@ def _get_grpc_servicer(self):
grpc_servicer = base_class

if grpc_servicer is None:
raise Exception(f'gRPC servicer is not set. (servicer={self.__class__.__name__})')
raise Exception(
f"gRPC servicer is not set. (servicer={self.__class__.__name__})"
)

return grpc_servicer

def _set_grpc_method(self):
grpc_servicer = self._get_grpc_servicer()

for f_name, f_object in inspect.getmembers(self.__class__, predicate=inspect.isfunction):
for f_name, f_object in inspect.getmembers(
self.__class__, predicate=inspect.isfunction
):
if hasattr(grpc_servicer, f_name):
setattr(self, f_name, self._grpc_method(f_object))

Expand All @@ -79,10 +89,10 @@ def _error_method(error, context):
if not isinstance(error, ERROR_BASE):
error = ERROR_UNKNOWN(message=error)

if not error.meta.get('skip_error_log'):
_LOGGER.error(f'(Error) => {error.message} {error}', exc_info=True)
if not error.meta.get("skip_error_log"):
_LOGGER.error(f"(Error) => {error.message} {error}", exc_info=True)

details = f'{error.error_code}: {error.message}'
details = f"{error.error_code}: {error.message}"
context.abort(grpc.StatusCode[error.status_code], details)

def _generate_response(self, response_iterator, context):
Expand Down Expand Up @@ -118,8 +128,7 @@ def _get_metadata(context):
for key, value in context.invocation_metadata():
metadata[key.strip()] = value.strip()

metadata.update({'peer': context.peer()})

metadata.update({"peer": context.peer()})
return metadata

def _generate_message(self, request_iterator):
Expand All @@ -128,9 +137,13 @@ def _generate_message(self, request_iterator):

def parse_request(self, request_or_iterator, context):
if isinstance(request_or_iterator, Iterable):
return self._generate_message(request_or_iterator), self._get_metadata(context)
return self._generate_message(request_or_iterator), self._get_metadata(
context
)
else:
return self._convert_message(request_or_iterator), self._get_metadata(context)
return self._convert_message(request_or_iterator), self._get_metadata(
context
)

def empty(self):
return Empty()
Expand All @@ -139,17 +152,19 @@ def dict_to_message(self, response: dict):
# Get grpc method name from call stack
method_name = inspect.stack()[1][3]

response_message_name = self._grpc_messages[method_name]['response']
response_message_name = self._grpc_messages[method_name]["response"]

if hasattr(self.pb2, response_message_name):
response_message = getattr(self.pb2, response_message_name)()
elif response_message_name == 'Struct':
elif response_message_name == "Struct":
response_message = Struct()
else:
raise Exception(f'Not found response message in pb2. (message={response_message_name})')
raise Exception(
f"Not found response message in pb2. (message={response_message_name})"
)

return ParseDict(response, response_message)

@staticmethod
def get_minimal(params: dict):
return params.get('query', {}).get('minimal', False)
return params.get("query", {}).get("minimal", False)
Loading

0 comments on commit 38360c3

Please sign in to comment.