def test_ok(self):
        response = ApiGatewayResponse().ok()

        assert response.present() == {
            "statusCode": 204,
            "headers": {},
            "body": None,
        }
    def test_auth_error(self):
        response = ApiGatewayResponse().auth_error()

        assert response.present() == {
            "statusCode": 401,
            "headers": {},
            "body": None,
        }
    def test_not_found(self):
        response = ApiGatewayResponse().not_found()

        assert response.present() == {
            "statusCode": 404,
            "headers": {},
            "body": None,
        }
Example #4
0
    def execute(self, environment, event):
        path = event["input"]["path"]
        http_method = event["input"]["requestContext"]["httpMethod"]
        response = ApiGatewayResponse()
        if http_method == "GET":
            if path == "/oauth/authorization_grant":
                query_strings = event["input"][
                    "multiValueQueryStringParameters"]
                code = query_strings.get("code", None)
                state = query_strings.get("state", None)
                if (code is not None and state is not None and len(code) == 1
                        and len(state) == 1):
                    response = UserInstall(
                        client_id=environment["CLIENT_ID"],
                        client_secret=environment["CLIENT_SECRET"],
                        redirect_uri=environment["REDIRECT_URI"],
                        user_token_store=StubUserTokenStore(),
                    ).execute(code[0], state[0])
                else:
                    logging.debug("missing code or state")
                    response.not_found()
            else:
                response.not_found()
        else:
            request = ApiGatewayRequest(event)
            response = HandleEvent(
                environment=environment,
                headers=request.headers(),
                raw_body=request.raw_body(),
            ).execute()

        return response.present()
    def test_redirect(self):
        url = "https://example.com"
        response = ApiGatewayResponse().redirect(url=url)

        assert response.present() == {
            "statusCode": 307,
            "headers": {
                "Location": url
            },
            "body": None,
        }
    def test_ok_with_html_body(self):
        body = "<html>"
        response = ApiGatewayResponse().ok_html(body)

        assert response.present() == {
            "statusCode": 200,
            "headers": {
                "Content-Type": "text/html"
            },
            "body": body,
        }
    def test_ok_with_body(self):
        body = dict(test="testing")
        response = ApiGatewayResponse().ok(body)

        assert response.present() == {
            "statusCode": 200,
            "headers": {
                "Content-Type": "application/json"
            },
            "body": '{"test": "testing"}',
        }
Example #8
0
def test_invalid_request_is_blocked():
    response = HandleEvent(
        environment={
            "SLACK_SIGNING_SECRET": "foo"
        },
        headers={},
        raw_body=json.dumps({"this is a test": "foobar"}),
    ).execute()

    assert response.present() == ApiGatewayResponse().auth_error().present()
def test_execute_returns_ok_if_event_not_found_error():
    secret = "some secret"
    event = "{}"
    response = HandleEvent(
        environment={"SLACK_SIGNING_SECRET": secret},
        headers=event_signature_headers(secret, event),
        raw_body=event,
    ).execute()

    # we do not want to error if the slack events api sends a event that is not supported
    assert response.present() == ApiGatewayResponse().ok().present()
Example #10
0
def test_handle_user_change_event(test_file):
    event = test_file("example_user_updated_event.json")
    secret = "foobar"

    response = HandleEvent(
        environment={
            "SLACK_SIGNING_SECRET": secret
        },
        headers=event_signature_headers(secret, event),
        raw_body=event,
    ).execute()

    assert response.present() == ApiGatewayResponse().ok().present()
Example #11
0
    def execute(self, code, state):
        logging.debug(
            "received authorization_grant code '%s'",
            code,
        )
        logging.debug(
            "received authorization_grant state '%s'",
            state,
        )
        gateway_response = slack.authorisation_grant(
            client_id=self.__client_id,
            client_secret=self.__client_secret,
            code=code,
            redirect_uri=self.__redirect_uri,
        )
        response = ApiGatewayResponse()
        if not gateway_response.success:
            logging.warning("returning auth error due to gateway failure")
            return response.auth_error()

        if gateway_response.scope == EXPECTED_SCOPE:
            body = RedirectUriPageRenderer(
                install_path="", redirect_uri_path=""
            ).render_success_page(app_id="fakeappid", team_id=None)
            user = User(
                team_id=gateway_response.team,
                user_id=gateway_response.user,
                token=gateway_response.token,
            )
            self.__user_token_store.store(user)
            return response.ok_html(body)
        else:
            logging.warning(
                f"scope differs from expected scope {gateway_response.scope} != {EXPECTED_SCOPE}"
            )
            return response.auth_error()
Example #12
0
def test_handle_url_verification_event(test_file):
    event = test_file("example_url_verification_event.json")
    secret = "foobar"

    response = HandleEvent(
        environment={
            "SLACK_SIGNING_SECRET": secret
        },
        headers=event_signature_headers(secret, event),
        raw_body=event,
    ).execute()

    expected_body = {
        "challenge": "3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P"
    }
    assert response.present() == ApiGatewayResponse().ok(
        expected_body).present()
def test_execute_returns_ok_if_event_callback_not_found_error(caplog):
    secret = "some secret"
    event = json.dumps(
        {
            "type": "event_callback",
            "event": {"type": "NOT SUPPORTED EVENT"},
        }
    )
    with caplog.at_level(logging.ERROR):
        response = HandleEvent(
            environment={"SLACK_SIGNING_SECRET": secret},
            headers=event_signature_headers(secret, event),
            raw_body=event,
        ).execute()

    assert f"unsupported event_callback" in caplog.text, "log does not exist"
    # we do not want to error if the slack events api sends a event that is not supported
    assert response.present() == ApiGatewayResponse().ok().present()
Example #14
0
    def execute(self):
        response = ApiGatewayResponse()
        if not VerifyRequest(signing_secret=self.signing_secret).execute(
                self.raw_body, self.headers):
            response.auth_error()
            return response

        body = json.loads(self.raw_body)

        type = body.get("type")
        if type == "url_verification":
            response_body = UrlVerification().execute(body)
            response.ok(response_body)
        elif type == "event_callback":
            event = body["event"]
            logging.info(f"Received event: {event['type']}")
            if event["type"] == "user_change":
                UpdateAllProfiles(
                    user_link_store=self.user_link_store,
                    user_token_store=self.user_token_store,
                ).execute(body)
                response.ok()
            elif event["type"] == "tokens_revoked":
                UserUninstall(
                    user_link_store=self.user_link_store,
                    user_token_store=self.user_token_store,
                ).execute(body)
                response.ok()
            else:
                logging.error("unsupported event_callback %s", event)
                response.ok()
        else:
            logging.error("event not supported %s", body)
            response.ok()

        return response
    def test_throw_exception_if_response_not_set(self):
        response = ApiGatewayResponse()

        with pytest.raises(NoResponseSetError):
            response.present()