async def test_lti_13_login_handler_invokes_redirect_method(monkeypatch, lti13_auth_params, make_mock_request_handler):
    """
    Does the LTI13LoginHandler call the redirect function once it
    receiving the post request?
    """
    monkeypatch.setenv('LTI13_AUTHORIZE_URL', 'http://my.lms.platform/api/lti/authorize_redirect')
    local_handler = make_mock_request_handler(LTI13LoginHandler)
    local_utils = LTIUtils()
    local_utils.convert_request_to_dict(lti13_auth_params)
    with patch.object(
        LTIUtils, 'convert_request_to_dict', return_value=local_utils.convert_request_to_dict(lti13_auth_params)
    ):
        with patch.object(LTI13LaunchValidator, 'validate_login_request', return_value=True):
            with patch.object(LTI13LoginHandler, 'authorize_redirect', return_value=None) as mock_redirect:
                LTI13LoginHandler(local_handler.application, local_handler.request).post()
                assert mock_redirect.called
async def test_lti_13_login_handler_empty_authorize_url_env_var_raises_environment_error(
    monkeypatch, lti13_login_params, lti13_login_params_dict, make_mock_request_handler
):
    """
    Does the LTI13LoginHandler raise a missing argument error if request body doesn't have any
    arguments?
    """
    monkeypatch.setenv('LTI13_AUTHORIZE_URL', '')
    local_handler = make_mock_request_handler(LTI13LoginHandler)
    local_utils = LTIUtils()
    with patch.object(
        LTIUtils, 'convert_request_to_dict', return_value=lti13_login_params_dict
    ) as mock_convert_request_to_dict:
        with patch.object(LTI13LaunchValidator, 'validate_launch_request', return_value=True):
            with patch.object(LTI13LoginHandler, 'redirect', return_value=None):
                with pytest.raises(EnvironmentError):
                    LTI13LoginHandler(local_handler.application, local_handler.request).post()
Example #3
0
async def test_lti_13_login_handler_calls_authorize_redirect_with_correct_values(
    monkeypatch, lti13_auth_params_dict, make_mock_request_handler
):
    """
    Does the LTI13LoginHandler correctly set all variables needed for the redict method
    after receiving it from the validator?
    """
    expected = lti13_auth_params_dict
    monkeypatch.setenv(
        "LTI13_AUTHORIZE_URL", "http://my.lms.platform/api/lti/authorize_redirect"
    )
    local_handler = make_mock_request_handler(LTI13LoginHandler)
    state_id = uuid4().hex
    expected_state = _serialize_state({"state_id": state_id, "next_url": ""})
    with patch.object(
        LTIUtils, "convert_request_to_dict", return_value=lti13_auth_params_dict
    ):
        with patch.object(
            LTI13LaunchValidator, "validate_login_request", return_value=True
        ):
            with patch.object(
                LTI13LoginHandler, "get_state", return_value=expected_state
            ):
                with patch.object(
                    LTI13LoginHandler, "authorize_redirect", return_value=None
                ) as mock_auth_redirect:
                    nonce_raw = hashlib.sha256(expected_state.encode())
                    expected_nonce = nonce_raw.hexdigest()

                    LTI13LoginHandler(
                        local_handler.application, local_handler.request
                    ).post()
                    assert mock_auth_redirect.called

                    mock_auth_redirect.assert_called_with(
                        client_id=expected["client_id"],
                        login_hint=expected["login_hint"],
                        lti_message_hint=expected["lti_message_hint"],
                        redirect_uri="https://127.0.0.1/hub/oauth_callback",
                        state=expected_state,
                        nonce=expected_nonce,
                    )
Example #4
0
async def test_lti_13_login_handler_sets_state_with_next_url_obtained_from_target_link_uri(
    monkeypatch, lti13_login_params, make_mock_request_handler
):
    """
    Do we get the expected nonce value result after hashing the state and returning the
    hexdigest?
    """
    monkeypatch.setenv(
        "LTI13_AUTHORIZE_URL", "http://my.lms.platform/api/lti/authorize_redirect"
    )
    lti13_login_params["target_link_uri"] = [
        (
            lti13_login_params["target_link_uri"][0].decode()
            + "?next=/user-redirect/lab"
        ).encode()
    ]
    local_handler = make_mock_request_handler(LTI13LoginHandler)

    decoded_dict = LTIUtils().convert_request_to_dict(lti13_login_params)
    with patch.object(LTIUtils, "convert_request_to_dict", return_value=decoded_dict):
        with patch.object(
            LTI13LaunchValidator, "validate_login_request", return_value=True
        ):
            with patch.object(
                LTI13LoginHandler, "authorize_redirect", return_value=None
            ):
                expected_state_json = {
                    "state_id": "6f0ec1569a3a402dac61626361d0c125",
                    "next_url": "/user-redirect/lab",
                }

                login_instance = LTI13LoginHandler(
                    local_handler.application, local_handler.request
                )
                login_instance.post()
                assert login_instance._state
                state_decoded = _deserialize_state(login_instance._state)
                state_decoded["next_url"] == expected_state_json["next_url"]
Example #5
0
async def test_lti_13_login_handler_invokes_convert_request_to_dict_method(
    monkeypatch, lti13_login_params, lti13_login_params_dict, make_mock_request_handler
):
    """
    Does the LTI13LoginHandler call the LTIUtils convert_request_to_dict function once it
    receiving the post request?
    """
    monkeypatch.setenv(
        "LTI13_AUTHORIZE_URL", "http://my.lms.platform/api/lti/authorize_redirect"
    )
    local_handler = make_mock_request_handler(LTI13LoginHandler)
    with patch.object(
        LTIUtils, "convert_request_to_dict", return_value=lti13_login_params_dict
    ) as mock_convert_request_to_dict:
        with patch.object(
            LTI13LaunchValidator, "validate_login_request", return_value=True
        ):
            with patch.object(
                LTI13LoginHandler, "authorize_redirect", return_value=None
            ):
                LTI13LoginHandler(
                    local_handler.application, local_handler.request
                ).post()
                assert mock_convert_request_to_dict.called
Example #6
0
    async def authenticate(  # noqa: C901
        self, handler: LTI13LoginHandler, data: Dict[str, str] = None
    ) -> Dict[str, str]:
        """
        Overrides authenticate from base class to handle LTI 1.3 authentication requests.

        Args:
          handler: handler object
          data: authentication dictionary

        Returns:
          Authentication dictionary
        """
        lti_utils = LTIUtils()
        validator = LTI13LaunchValidator()

        # get jwks endpoint and token to use as args to decode jwt. we could pass in
        # self.endpoint directly as arg to jwt_verify_and_decode() but logging the
        self.log.debug('JWKS platform endpoint is %s' % self.endpoint)
        id_token = handler.get_argument('id_token')
        self.log.debug('ID token issued by platform is %s' % id_token)

        # extract claims from jwt (id_token) sent by the platform. as tool use the jwks (public key)
        # to verify the jwt's signature.
        jwt_decoded = await validator.jwt_verify_and_decode(id_token, self.endpoint, False, audience=self.client_id)
        self.log.debug('Decoded JWT is %s' % jwt_decoded)

        if validator.validate_launch_request(jwt_decoded):
            course_id = jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/context']['label']
            course_id = lti_utils.normalize_string(course_id)
            self.log.debug('Normalized course label is %s' % course_id)
            username = ''
            if 'email' in jwt_decoded and jwt_decoded['email']:
                username = lti_utils.email_to_username(jwt_decoded['email'])
            elif 'name' in jwt_decoded and jwt_decoded['name']:
                username = jwt_decoded['name']
            elif 'given_name' in jwt_decoded and jwt_decoded['given_name']:
                username = jwt_decoded['given_name']
            elif 'family_name' in jwt_decoded and jwt_decoded['family_name']:
                username = jwt_decoded['family_name']
            elif (
                'https://purl.imsglobal.org/spec/lti/claim/lis' in jwt_decoded
                and 'person_sourcedid' in jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']
                and jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']['person_sourcedid']
            ):
                username = jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']['person_sourcedid'].lower()
            elif (
                'lms_user_id' in jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/custom']
                and jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/custom']['lms_user_id']
            ):
                username = str(jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/custom']['lms_user_id'])
            self.log.debug('username is %s' % username)
            # ensure the username is normalized
            self.log.debug('username is %s' % username)
            if username == '':
                raise HTTPError('Unable to set the username')

            # set role to learner role (by default) if instructor or learner/student roles aren't
            # sent with the request
            user_role = 'Learner'
            for role in jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/roles']:
                if role.find('Instructor') >= 1:
                    user_role = 'Instructor'
                elif role.find('Learner') >= 1 or role.find('Student') >= 1:
                    user_role = 'Learner'
            self.log.debug('user_role is %s' % user_role)

            launch_return_url = ''
            if (
                'https://purl.imsglobal.org/spec/lti/claim/launch_presentation' in jwt_decoded
                and 'return_url' in jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/launch_presentation']
            ):
                launch_return_url = jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/launch_presentation'][
                    'return_url'
                ]
            # if there is a resource link request then process additional steps
            if not validator.is_deep_link_launch(jwt_decoded):
                await process_resource_link(self.log, course_id, jwt_decoded)

            lms_user_id = jwt_decoded['sub'] if 'sub' in jwt_decoded else username

            # ensure the user name is normalized
            username_normalized = lti_utils.normalize_string(username)
            self.log.debug('Assigned username is: %s' % username_normalized)

            return {
                'name': username_normalized,
                'auth_state': {
                    'course_id': course_id,
                    'user_role': user_role,
                    'lms_user_id': lms_user_id,
                    'launch_return_url': launch_return_url,
                },  # noqa: E231
            }
Example #7
0
    async def authenticate(  # noqa: C901
            self,
            handler: LTI13LoginHandler,
            data: Dict[str, str] = None) -> Dict[str, str]:
        """
        Overrides authenticate from base class to handle LTI 1.3 authentication requests.

        Args:
          handler: handler object
          data: authentication dictionary

        Returns:
          Authentication dictionary
        """
        lti_utils = LTIUtils()
        validator = LTI13LaunchValidator()

        # get jwks endpoint and token to use as args to decode jwt. we could pass in
        # self.endpoint directly as arg to jwt_verify_and_decode() but logging the
        self.log.debug("JWKS platform endpoint is %s" % self.endpoint)
        id_token = handler.get_argument("id_token")
        self.log.debug("ID token issued by platform is %s" % id_token)

        # extract claims from jwt (id_token) sent by the platform. as tool use the jwks (public key)
        # to verify the jwt's signature.
        jwt_decoded = await validator.jwt_verify_and_decode(
            id_token, self.endpoint, False, audience=self.client_id)
        self.log.debug("Decoded JWT is %s" % jwt_decoded)

        if validator.validate_launch_request(jwt_decoded):
            course_id = jwt_decoded[
                "https://purl.imsglobal.org/spec/lti/claim/context"]["label"]
            course_id = lti_utils.normalize_string(course_id)
            self.log.debug("Normalized course label is %s" % course_id)
            username = ""
            if "email" in jwt_decoded and jwt_decoded["email"]:
                username = lti_utils.email_to_username(jwt_decoded["email"])
            elif "name" in jwt_decoded and jwt_decoded["name"]:
                username = jwt_decoded["name"]
            elif "given_name" in jwt_decoded and jwt_decoded["given_name"]:
                username = jwt_decoded["given_name"]
            elif "family_name" in jwt_decoded and jwt_decoded["family_name"]:
                username = jwt_decoded["family_name"]
            elif ("https://purl.imsglobal.org/spec/lti/claim/lis"
                  in jwt_decoded and "person_sourcedid" in
                  jwt_decoded["https://purl.imsglobal.org/spec/lti/claim/lis"]
                  and
                  jwt_decoded["https://purl.imsglobal.org/spec/lti/claim/lis"]
                  ["person_sourcedid"]):
                username = jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/lis"][
                        "person_sourcedid"].lower()
            elif ("lms_user_id" in jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/custom"]
                  and jwt_decoded[
                      "https://purl.imsglobal.org/spec/lti/claim/custom"]
                  ["lms_user_id"]):
                username = str(jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/custom"]
                               ["lms_user_id"])

            # set role to learner role (by default) if instructor or learner/student roles aren't
            # sent with the request
            user_role = "Learner"
            for role in jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/roles"]:
                if role.find("Instructor") >= 1:
                    user_role = "Instructor"
                elif role.find("Learner") >= 1 or role.find("Student") >= 1:
                    user_role = "Learner"
            self.log.debug("user_role is %s" % user_role)

            launch_return_url = ""
            if ("https://purl.imsglobal.org/spec/lti/claim/launch_presentation"
                    in jwt_decoded and "return_url" in jwt_decoded[
                        "https://purl.imsglobal.org/spec/lti/claim/launch_presentation"]
                ):
                launch_return_url = jwt_decoded[
                    "https://purl.imsglobal.org/spec/lti/claim/launch_presentation"][
                        "return_url"]
            # if there is a resource link request then process additional steps
            if not validator.is_deep_link_launch(jwt_decoded):
                await process_resource_link_lti_13(self.log, course_id,
                                                   jwt_decoded)

            lms_user_id = jwt_decoded[
                "sub"] if "sub" in jwt_decoded else username

            # ensure the username is normalized
            self.log.debug("username is %s" % username)
            if not username:
                raise HTTPError(400, "Unable to set the username")

            # ensure the user name is normalized
            username_normalized = lti_utils.normalize_string(username)
            self.log.debug("Assigned username is: %s" % username_normalized)

            return {
                "name": username_normalized,
                "auth_state": {
                    "course_id": course_id,
                    "user_role": user_role,
                    "lms_user_id": lms_user_id,
                    "launch_return_url": launch_return_url,
                },  # noqa: E231
            }
    async def authenticate(  # noqa: C901
            self,
            handler: LTI13LoginHandler,
            data: Dict[str, str] = None) -> Dict[str, str]:
        """
        Overrides authenticate from base class to handle LTI 1.3 authentication requests.

        Args:
          handler: handler object
          data: authentication dictionary

        Returns:
          Authentication dictionary
        """
        lti_utils = LTIUtils()
        validator = LTI13LaunchValidator()

        # get jwks endpoint and token to use as args to decode jwt. we could pass in
        # self.endpoint directly as arg to jwt_verify_and_decode() but logging the
        self.log.debug('JWKS platform endpoint is %s' % self.endpoint)
        id_token = handler.get_argument('id_token')
        self.log.debug('ID token issued by platform is %s' % id_token)

        # extract claims from jwt (id_token) sent by the platform. as tool use the jwks (public key)
        # to verify the jwt's signature.
        jwt_decoded = await validator.jwt_verify_and_decode(
            id_token, self.endpoint, False, audience=self.client_id)
        self.log.debug('Decoded JWT is %s' % jwt_decoded)

        if validator.validate_launch_request(jwt_decoded):
            course_id = jwt_decoded[
                'https://purl.imsglobal.org/spec/lti/claim/context']['label']
            self.log.debug('Normalized course label is %s' % course_id)
            username = ''
            if 'email' in jwt_decoded.keys() and jwt_decoded.get('email'):
                username = lti_utils.email_to_username(jwt_decoded['email'])
            elif 'name' in jwt_decoded.keys() and jwt_decoded.get('name'):
                username = jwt_decoded.get('name')
            elif 'given_name' in jwt_decoded.keys() and jwt_decoded.get(
                    'given_name'):
                username = jwt_decoded.get('given_name')
            elif 'family_name' in jwt_decoded.keys() and jwt_decoded.get(
                    'family_name'):
                username = jwt_decoded.get('family_name')
            elif ('person_sourcedid' in
                  jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']
                  and
                  jwt_decoded['https://purl.imsglobal.org/spec/lti/claim/lis']
                  ['person_sourcedid']):
                username = jwt_decoded[
                    'https://purl.imsglobal.org/spec/lti/claim/lis'][
                        'person_sourcedid'].lower()
            if username == '':
                raise HTTPError('Unable to set the username')
            self.log.debug('username is %s' % username)

            # assign a workspace type, if provided, otherwise defaults to jupyter classic nb
            workspace_type = ''
            if ('https://purl.imsglobal.org/spec/lti/claim/custom'
                    in jwt_decoded and jwt_decoded[
                        'https://purl.imsglobal.org/spec/lti/claim/custom']
                    is not None):
                if ('workspace_type' in jwt_decoded[
                        'https://purl.imsglobal.org/spec/lti/claim/custom']
                        and jwt_decoded[
                            'https://purl.imsglobal.org/spec/lti/claim/custom']
                    ['workspace_type'] is not None):
                    workspace_type = jwt_decoded[
                        'https://purl.imsglobal.org/spec/lti/claim/custom'][
                            'workspace_type']
            if workspace_type not in WORKSPACE_TYPES:
                workspace_type = 'notebook'
            self.log.debug('workspace type is %s' % workspace_type)

            user_role = ''
            for role in jwt_decoded[
                    'https://purl.imsglobal.org/spec/lti/claim/roles']:
                if role.find('Instructor') >= 1:
                    user_role = 'Instructor'
                elif role.find('Learner') >= 1 or role.find('Student') >= 1:
                    user_role = 'Learner'
            # set role to learner role if instructor or learner/student roles aren't
            # sent with the request
            if user_role == '':
                user_role = 'Learner'
            self.log.debug('user_role is %s' % user_role)

            lms_user_id = jwt_decoded[
                'sub'] if 'sub' in jwt_decoded else username
            # Values for the send-grades functionality
            course_lineitems = ''
            if 'https://purl.imsglobal.org/spec/lti-ags/claim/endpoint' in jwt_decoded:
                course_lineitems = jwt_decoded[
                    'https://purl.imsglobal.org/spec/lti-ags/claim/endpoint'][
                        'lineitems']

            return {
                'name': username,
                'auth_state': {
                    'course_id': course_id,
                    'user_role': user_role,
                    'workspace_type': workspace_type,
                    'course_lineitems': course_lineitems,
                    'user_role': user_role,
                    'lms_user_id': lms_user_id,
                },  # noqa: E231
            }