Esempio n. 1
0
    def test_task_context_user_after_authentication(self, insanic_application,
                                                    test_user,
                                                    test_user_token_factory):
        import aiotask_context

        token = test_user_token_factory(id=test_user.id, level=test_user.level)

        class TokenView(InsanicView):
            async def get(self, request, *args, **kwargs):
                user = aiotask_context.get(settings.TASK_CONTEXT_REQUEST_USER)
                assert user is not None
                assert user == dict(test_user)
                request_user = request.user
                assert user == dict(request_user)

                service = request.service
                assert str(service).startswith("AnonymousService")

                return json({"hi": "hello"})

        insanic_application.add_route(TokenView.as_view(), "/")
        request, response = insanic_application.test_client.get(
            "/",
            headers={
                "Authorization": token,
                settings.INTERNAL_REQUEST_USER_HEADER:
                to_header_value(test_user),
            },
        )

        assert response.status == 200
Esempio n. 2
0
    async def test_task_context_service_http_dispatch_injection(
        self,
        insanic_application,
        test_client,
        test_service_token_factory,
        monkeypatch,
    ):
        import aiotask_context
        import asyncio
        from insanic.loading import get_service

        monkeypatch.setattr(settings, "SERVICE_CONNECTIONS", ["userip"])
        UserIPService = get_service("userip")

        class TokenView(InsanicView):
            async def get(self, request, *args, **kwargs):
                context_user = aiotask_context.get(
                    settings.TASK_CONTEXT_REQUEST_USER)
                request_user = request.user
                handlers.jwt_decode_handler(request.auth)

                token = UserIPService.service_token
                assert token is not None

                assert dict(request_user) == context_user
                return json({"user": dict(request_user)})

        insanic_application.add_route(TokenView.as_view(), "/")

        client = await test_client(insanic_application)

        users = []
        requests = []

        for i in range(10):
            user = User(id=i, level=UserLevels.STAFF, is_authenticated=True)

            token = test_service_token_factory()
            requests.append(
                client.get(
                    "/",
                    headers={
                        "Authorization":
                        token,
                        settings.INTERNAL_REQUEST_USER_HEADER:
                        to_header_value(user),
                    },
                ))
            users.append(user)

        responses = await asyncio.gather(*requests)

        for i in range(10):
            r = responses[i]
            resp = await r.json()
            assert r.status == 200, resp

            assert resp["user"]["id"] == str(users[i].id)
Esempio n. 3
0
    async def test_task_context_service_multiple_after_authentication(
            self, insanic_application, test_client,
            test_service_token_factory):
        import aiotask_context
        import asyncio

        class TokenView(InsanicView):
            async def get(self, request, *args, **kwargs):
                user = aiotask_context.get(settings.TASK_CONTEXT_REQUEST_USER)
                assert user is not None

                request_user = request.user
                assert user == dict(request_user)

                payload = handlers.jwt_decode_handler(request.auth)
                assert "user" not in payload
                assert user == dict(request_user)

                return json({"user": user})

        insanic_application.add_route(TokenView.as_view(), "/")

        client = await test_client(insanic_application)
        #
        # insanic_application.run(host='127.0.0.1', port=unused_port)
        requests = []
        for i in range(10):
            user = User(id=i, level=UserLevels.STAFF, is_authenticated=True)

            token = test_service_token_factory()
            requests.append(
                client.get(
                    "/",
                    headers={
                        "Authorization":
                        token,
                        settings.INTERNAL_REQUEST_USER_HEADER:
                        to_header_value(user),
                    },
                ))

        responses = await asyncio.gather(*requests)

        for i in range(10):
            r = responses[i]
            assert r.status == 200

            resp = await r.json()
            assert resp["user"]["id"] == str(i)
Esempio n. 4
0
    def _inject_headers(self, headers: dict):
        # need to coerce to str
        headers = {k: str(v) for k, v in headers.items()}
        headers.update(
            {"date": get_utc_datetime().strftime("%a, %d %b %y %T %z")})

        # inject user information to request headers
        user = context_user()
        headers.update({
            settings.INTERNAL_REQUEST_USER_HEADER.lower():
            to_header_value(user)
        })
        # inject correlation_id
        correlation_id = context_correlation_id()
        headers.update(
            {settings.REQUEST_ID_HEADER_FIELD.lower(): correlation_id})

        return Headers(headers)
Esempio n. 5
0
    async def test_task_context_service_anonymous_http_dispatch_injection(
        self,
        insanic_application,
        test_client,
        test_service_token_factory,
        monkeypatch,
    ):
        import aiotask_context
        import asyncio
        from insanic.loading import get_service

        monkeypatch.setattr(settings, "SERVICE_CONNECTIONS", ["userip"])
        UserIPService = get_service("userip")

        class TokenView(InsanicView):
            permission_classes = [
                AllowAny,
            ]

            async def get(self, request, *args, **kwargs):
                context_user = aiotask_context.get(
                    settings.TASK_CONTEXT_REQUEST_USER)
                request_user = request.user
                handlers.jwt_decode_handler(request.auth)

                token = UserIPService.service_token
                assert token is not None

                jwt.decode(
                    token,
                    settings.SERVICE_TOKEN_KEY,
                    verify=False,
                    algorithms=[settings.JWT_SERVICE_AUTH_ALGORITHM],
                )

                assert dict(request_user) == context_user
                return json({"user": dict(request_user)})

        insanic_application.add_route(TokenView.as_view(), "/")

        client = await test_client(insanic_application)

        users = []
        requests = []

        for _ in range(10):
            user = AnonymousUser
            token = test_service_token_factory()
            requests.append(
                client.get(
                    "/",
                    headers={
                        "Authorization":
                        token,
                        settings.INTERNAL_REQUEST_USER_HEADER:
                        to_header_value(user),
                    },
                ))
            users.append(user)

        responses = await asyncio.gather(*requests)

        for i in range(10):
            r = responses[i]
            resp = await r.json()
            assert r.status == 200, resp

            assert resp["user"]["id"] == users[i].id
Esempio n. 6
0
 def headers(self):
     return {
         settings.INTERNAL_REQUEST_USER_HEADER:
         to_header_value(test_user)
     }