Example #1
0
    def run(
        self,
        tempdir: str,
        emit: t.Callable[[str, int, str, str], None],
        process_completed: ProcessCompletedCallback,
    ) -> None:
        """Run checkstyle

        Arguments are the same as for :py:meth:`Linter.run`.
        """
        tempdir = os.path.dirname(tempdir)

        with tempfile.NamedTemporaryFile('w') as cfg:
            module: ET.Element = defused_xml_fromstring(self.config)
            assert module is not None
            assert module.attrib.get('name') == 'Checker'
            module.append(
                module.__class__('property', {
                    'name': 'basedir',
                    'value': '${basedir}'
                }))
            cfg.write("""<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
          "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
          "https://checkstyle.org/dtds/configuration_1_3.dtd">\n""")
            cfg.write(ET.tostring(module, encoding='unicode'))
            cfg.flush()

            out = _run_command(
                format_list(
                    app.config['CHECKSTYLE_PROGRAM'],
                    config=cfg.name,
                    files=tempdir,
                ))
            process_completed(out)
            if out.returncode == 254:
                raise LinterCrash(
                    'The given submission could not be parsed as valid java', )

            output: ET.Element = defused_xml_fromstring(out.stdout)
            assert output is not None

            for file_el in output:
                if file_el.tag != 'file':  # pragma: no cover
                    continue
                filename = file_el.attrib['name']
                for error_el in file_el:
                    if error_el.tag != 'error':  # pragma: no cover
                        continue
                    attrib = error_el.attrib
                    emit(
                        filename,
                        int(attrib['line']),
                        attrib.get('severity', 'warning'),
                        attrib['message'],
                    )
Example #2
0
    def validate_config(cls: t.Type['PMD'], config: str) -> None:
        """Check if the given config is valid for PMD.

        This also does some extra checks to make sure some invalid properties
        are not present.

        :param config: The config to check.
        """
        try:
            xml_config: ET.Element = defused_xml_fromstring(config)
            assert xml_config is not None
        except:
            logger.warning('Error', exc_info=True)
            raise ValidationException(
                'The given xml config could not be parsed.',
                f'The config {config} could not be parsed as xml.'
            )
        stack: t.List[ET.Element] = [xml_config]

        while stack:
            cur = stack.pop()
            stack.extend(cur)
            class_el = cur.attrib.get('class')
            if class_el is None:
                continue
            if 'xpathrule' in class_el.lower().split('.'):
                raise ValidationException(
                    'XPath rules cannot be used.', (
                        'The given config is invalid as XPath rules are'
                        ' not allowed.'
                    )
                )
Example #3
0
    def validate_config(cls: t.Type['Checkstyle'], config: str) -> None:
        """Check if the given config is valid for checkstyle.

        This also does some extra checks to make sure some invalid properties
        are not present.

        :param config: The config to check.
        """
        try:
            xml_config: ET.Element = defused_xml_fromstring(config)
            assert xml_config is not None
        except:
            raise ValidationException(
                'The given xml config could not be parsed.',
                f'The config {config} could not be parsed as xml.'
            )
        if xml_config.tag != 'module' or xml_config.attrib.get(
            'name'
        ) != 'Checker':
            raise ValidationException(
                'The given config is not valid.',
                'The given top module of the config should be Checker.'
            )
        for sub_el in xml_config:
            validate_func = cls._get_validate_func(sub_el.tag)
            if validate_func is None:
                raise ValidationException(
                    'The given config is not valid',
                    f'Unknown tag "{sub_el.tag}" encountered'
                )
            validate_func(sub_el)
Example #4
0
def test_direct_deep_link_launch(test_client, describe, logged_in, admin_user):
    with describe('setup'), logged_in(admin_user):
        canvas_provider = helpers.create_lti1p3_provider(
            test_client,
            'Canvas',
            iss='https://canvas.instructure.com',
            client_id=str(uuid.uuid4()) + '_lms=' + 'Canvas')
        return_url = f'https://{uuid.uuid4()}.com'
        deep_link_data = {
            lti1p3.claims.MESSAGE_TYPE: 'LtiDeepLinkingRequest',
            lti1p3.claims.DEEP_LINK: {
                'data': 'DP_DATA',
                'deep_link_return_url': return_url,
                'accept_types': ['ltiResourceLink'],
                'accept_presentation_document_targets': 'PRES',
            },
        }
        canvas_launch_data = make_launch_data(
            merge(CANVAS_DATA, deep_link_data), canvas_provider, {})

    with describe('deep link to canvas should directly return resource'):
        _, launch = do_oidc_and_lti_launch(test_client,
                                           canvas_provider,
                                           canvas_launch_data,
                                           status=DEEP_LINK)
        form = launch.data
        parsed = defused_xml_fromstring(form.decode('utf8'))
        assert parsed.tag == 'html'
        form, = parsed.findall('body/form')
        assert form.attrib['action'] == return_url
        assert form.attrib['method'] == 'POST'
        child, = form.getchildren()
        assert child.attrib['name'] == 'JWT'
        assert child.attrib['type'] == 'hidden'
        jwt_value = child.attrib['value']
        assert jwt.decode(jwt_value, verify=False)
Example #5
0
def get_metadata(provider_id: uuid.UUID
                 ) -> t.Union[t.Tuple[str, int], Response]:
    """Get the metadata xml for SP connected to the given provider.

    While this URL should always return a valid XML it might be IP restricted,
    and is not part of the public API.

    :param provider_id: The id of the provider for which you want to generate
        the XML.

    :returns: The generated XML or an error page.
    """
    req = _prepare_flask_request()
    auth = _init_saml_auth(
        req, helpers.get_or_404(models.Saml2Provider, provider_id)
    )
    settings = auth.get_settings()
    metadata = settings.get_sp_metadata()

    tree: ET.Element = defused_xml_fromstring(metadata)
    NSMAP = {
        **OneLogin_Saml2_Constants.NSMAP,
        'mdui': MDUI_NAMESPACE,
    }

    def make_tag(ns: str, tagname: str) -> str:
        return '{{{}}}{}'.format(NSMAP.get(ns), tagname)

    desc = tree.find('.//md:SPSSODescriptor', NSMAP)
    assert desc is not None
    ext = desc.find('./md:Extensions'.format(), NSMAP)
    if ext is None:
        ext = desc.makeelement(make_tag('md', 'Extensions'), {})
        desc.insert(0, ext)

    uiinfo = ext.makeelement(make_tag('mdui', 'UIInfo'), {})

    for lang in ['en', *current_app.config['SSO_METADATA_EXTRA_LANGUAGES']]:
        display_name = uiinfo.makeelement(
            make_tag('mdui', 'DisplayName'), {'xml:lang': lang}
        )
        display_name.text = 'CodeGrade'
        uiinfo.append(display_name)

        description = uiinfo.makeelement(
            make_tag('mdui', 'Description'), {'xml:lang': lang}
        )
        description.text = 'Deliver engaging feedback on code.'
        uiinfo.append(description)

        info_url = uiinfo.makeelement(
            make_tag('mdui', 'InformationURL'), {'xml:lang': lang}
        )
        info_url.text = current_app.config['EXTERNAL_URL']
        uiinfo.append(info_url)

    logo = uiinfo.makeelement(
        make_tag('mdui', 'Logo'), {
            'height': '249',
            'width': '1263'
        }
    )
    logo.text = furl.furl(current_app.config['EXTERNAL_URL']
                          ).add(path='static/img/codegrade-inv.png').tostr()
    uiinfo.append(logo)

    ext.append(uiinfo)

    metadata = ET.tostring(tree)
    errors = settings.validate_metadata(metadata)

    if errors:  # pragma: no cover
        return _make_error(
            'Error generating metadata',
            flask.escape(readable_join([str(err) for err in errors])),
        )
    else:
        resp = flask.make_response(metadata, 200)
        resp.headers['Content-Type'] = 'text/xml'
        return resp