Exemple #1
0
 def testHandleApiCallNotEnabled(self):
   """Raises if no matching ACL and enabled_by_default=False."""
   config_lib.CONFIG.Set("API.RendererACLFile", "")
   auth_mgr = api_call_renderers.SimpleAPIAuthorizationManager()
   self.mock_renderer.enabled_by_default = False
   with mock.patch.object(api_call_renderers, "API_AUTH_MGR", auth_mgr):
     with self.assertRaises(access_control.UnauthorizedAccess):
       api_call_renderers.HandleApiCall(self.mock_renderer, "",
                                        token=self.token)
Exemple #2
0
  def testHandleApiCallNotEnabledWithACL(self):
    """Matching ACL and enabled_by_default=False is allowed."""
    acls = """
renderer: "ApiCallRenderer"
users:
- "test"
"""
    with mock.patch.object(__builtin__, "open", mock.mock_open(read_data=acls)):
      auth_mgr = api_call_renderers.SimpleAPIAuthorizationManager()

    self.mock_renderer.enabled_by_default = False
    with mock.patch.object(api_call_renderers, "API_AUTH_MGR", auth_mgr):
      api_call_renderers.HandleApiCall(self.mock_renderer, "", token=self.token)

    self.mock_renderer.Render.assert_called_once_with("", token=self.token)
Exemple #3
0
def RenderHttpResponse(request):
    """Handles given HTTP request with one of the available API renderers."""

    renderer, route_args = GetRendererForHttpRequest(request)

    strip_type_info = False

    if request.method == "GET":
        if request.GET.get("strip_type_info", ""):
            strip_type_info = True

        if renderer.args_type:
            unprocessed_request = request.GET
            if hasattr(unprocessed_request, "dict"):
                unprocessed_request = unprocessed_request.dict()

            args = renderer.args_type()
            for type_info in args.type_infos:
                if type_info.name in route_args:
                    args.Set(type_info.name, route_args[type_info.name])
                elif type_info.name in unprocessed_request:
                    args.Set(type_info.name,
                             unprocessed_request[type_info.name])

            if renderer.additional_args_types:
                if not hasattr(args, "additional_args"):
                    raise RuntimeError(
                        "Renderer %s defines additional arguments types "
                        "but its arguments object does not have "
                        "'additional_args' field." % renderer)

                if hasattr(renderer.additional_args_types, "__call__"):
                    additional_args_types = renderer.additional_args_types()
                else:
                    additional_args_types = renderer.additional_args_types

                args.additional_args = FillAdditionalArgsFromRequest(
                    unprocessed_request, additional_args_types)

        else:
            args = None
    elif request.method == "POST":
        try:
            payload = json.loads(request.body)
            args = renderer.args_type(**payload)

            for type_info in args.type_infos:
                if type_info.name in route_args:
                    args.Set(type_info.name, route_args[type_info.name])
        except Exception as e:  # pylint: disable=broad-except
            logging.exception("Error while parsing POST request %s (%s): %s",
                              request.path, request.method, e)

            return BuildResponse(500, dict(message=str(e)))
    else:
        raise RuntimeError("Unsupported method: %s." % request.method)

    token = BuildToken(request, renderer.max_execution_time)

    try:
        rendered_data = api_call_renderers.HandleApiCall(renderer,
                                                         args,
                                                         token=token)

        if strip_type_info:
            rendered_data = StripTypeInfo(rendered_data)

        return BuildResponse(200, rendered_data)
    except access_control.UnauthorizedAccess as e:
        logging.exception("Access denied to %s (%s) with %s: %s", request.path,
                          request.method, renderer.__class__.__name__, e)

        return BuildResponse(403, dict(message="Access denied by ACL"))
    except Exception as e:  # pylint: disable=broad-except
        logging.exception("Error while processing %s (%s) with %s: %s",
                          request.path, request.method,
                          renderer.__class__.__name__, e)

        return BuildResponse(500, dict(message=str(e)))
Exemple #4
0
def RenderHttpResponse(request):
    """Handles given HTTP request with one of the available API renderers."""

    renderer, route_args = GetRendererForHttpRequest(request)

    if request.method == "GET":

        if renderer.args_type:
            unprocessed_request = request.GET
            if hasattr(unprocessed_request, "dict"):
                unprocessed_request = unprocessed_request.dict()

            args = renderer.args_type()
            for type_info in args.type_infos:
                if type_info.name in route_args:
                    args.Set(type_info.name, route_args[type_info.name])
                elif type_info.name in unprocessed_request:
                    args.Set(type_info.name,
                             unprocessed_request[type_info.name])

            if renderer.additional_args_types:
                if not hasattr(args, "additional_args"):
                    raise RuntimeError(
                        "Renderer %s defines additional arguments types "
                        "but its arguments object does not have "
                        "'additional_args' field." % renderer)

                if hasattr(renderer.additional_args_types, "__call__"):
                    additional_args_types = renderer.additional_args_types()
                else:
                    additional_args_types = renderer.additional_args_types

                args.additional_args = FillAdditionalArgsFromRequest(
                    unprocessed_request, additional_args_types)

        else:
            args = None
    elif request.method == "POST":
        payload = json.loads(request.raw_post_data)
        args = renderer.args_type(**payload)
    else:
        raise RuntimeError("Unsupported method: %s." % request.method)

    token = BuildToken(request, renderer.max_execution_time)

    try:
        rendered_data = api_call_renderers.HandleApiCall(renderer,
                                                         args,
                                                         token=token)

        response = http.HttpResponse(content_type="application/json")
        response.write(")]}'\n")  # XSSI protection
        response.write(json.dumps(rendered_data))
    except Exception as e:  # pylint: disable=broad-except
        response = http.HttpResponse(status=500)
        response.write(")]}'\n")  # XSSI protection
        response.write(json.dumps(dict(message=str(e))))

        logging.exception("Error while processing %s (%s) with %s: %s",
                          request.path, request.method,
                          renderer.__class__.__name__, e)

    return response