Esempio n. 1
0
File: tool.py Progetto: rohe/otest
    def set_profile(self, info):
        try:
            old = from_profile(self.sh.profile)

            new = from_profile(to_profile(info))
            for attr in ['enc', 'extra', 'none', 'return_type', 'sig', 'form_post']:
                old[attr] = new[attr]

            # Store new configuration
            try:
                rest = self.sh.extra['rest']
            except KeyError:
                self.conv.tool_conf.update(compress_profile(old))
            else:
                qp = [quote_plus(p) for p in [self.sh.iss, self.sh.tag]]
                _, _conf = rest.read_conf(*qp)
                _conf['tool'].update(compress_profile(old))
                rest.store(qp[0], qp[1], _conf)

                # This will fail if no test has been run before the conf
                # is changed
                try:
                    self.conv.tool_conf = _conf['tool']
                except AttributeError:
                    pass

            # reset all test flows
            self.flows.test_info = {}
            self.flows.complete = {}
            self.sh.reset_session(profile=old['profile'])
            # Back to test list
            return self.inut.flow_list()
        except Exception as err:
            return self.inut.err_response("profile", err)
Esempio n. 2
0
def test_match_usage():
    assert match_usage({'usage': {
        'extra': True
    }}, **from_profile(PROFILE[0])) is False

    assert match_usage(
        {
            "usage": {
                "return_type": ["C", "IT", "CI", "CIT", "CT"],
                "extra": True
            }
        }, **from_profile(PROFILE[0])) is False

    assert match_usage(
        {"usage": {
            "return_type": ["C", "I", "IT", "CI", "CT", "CIT"]
        }}, **from_profile(PROFILE[0]))

    assert match_usage({"usage": {
        "return_type": ["CI", "CT", "CIT"]
    }}, **from_profile(PROFILE[0])) is False

    assert match_usage(
        {"usage": {
            "return_type": ["C", "CI", "CT", "CIT"],
            "enc": True
        }}, **from_profile(PROFILE[0]))
Esempio n. 3
0
    def create(self, **kwargs):
        logging.info('create test tool configuration')
        # construct profile
        profile = to_profile(kwargs)
        _ent_conf = create_model(profile, ent_info_path=self.ent_info_path)
        state = {}

        if not do_discovery(profile):
            _ent_conf['client']['provider_info']['issuer'] = kwargs['iss']

        if not do_registration(profile):
            # need to create a redirect_uri, means I need to register a port
            _port = self.app.assigned_ports.register_port(
                kwargs['iss'], kwargs['tag'])
            if self.app.test_tool_base.endswith('/'):
                _base = self.app.test_tool_base[:-1]
            else:
                _base = self.app.test_tool_base
            _ent_conf['client']['registration_response'][
                'redirect_uris'] = '{}:{}/authz_cb'.format(_base, _port)

        uqp, qp = unquote_quote(kwargs['iss'], kwargs['tag'])
        _ent_conf['tool']['issuer'] = uqp[0]
        _ent_conf['tool']['tag'] = uqp[1]
        _ent_conf['tool']['profile'] = profile

        _ent_conf.update(from_profile(profile))
        logging.info("Test tool config: {}".format(_ent_conf))

        self.rest.write(qp[0], qp[1], _ent_conf)
        # Do a redirect
        raise cherrypy.HTTPRedirect('/action/update?iss={}&tag={}'.format(
            qp[0], qp[1]))
Esempio n. 4
0
def update_config(conf, tool_params):
    # provider_info and registration_response
    dicts = {'tool': conf['tool']}
    _prof = conf['tool']['profile']
    _spec = from_profile(conf['tool']['profile'])
    _spec['return_type'] = abbr_return_type(_spec['return_type'])
    del dicts['tool']['profile']
    dicts['tool'].update(_spec)

    for item in tool_params:
        if item == 'profile':
            continue
        if item not in dicts['tool']:
            dicts['tool'][item] = ''

    multi = {'tool': ['acr_values', 'claims_locales', 'ui_locales']}
    for typ in ['provider_info', 'registration_response']:
        multi[typ] = multi_value(typ)
        try:
            dicts[typ] = conf['client'][typ]
        except KeyError:
            try:
                dicts[typ] = update(typ, conf[typ])
            except KeyError:
                pass

    state = {
        'tool': {'immutable': ['issuer', 'tag', 'register', 'discover',
                               'webfinger'],
                 'required': ['return_type', 'contact_email']}}

    notes = ''
    if _spec['webfinger']:
        state['tool']['required'].extend(['webfinger_email',
                                          'webfinger_url'])
        notes = ("If <i>webfinger</i> is True then one of "
                 "<i>webfinger_email</i> and <i>webfinger_url</i> "
                 "<b>MUST</b> have a value.")

    if 'registration_response' in dicts:
        state['registration_response'] = {
            'immutable': ['redirect_uris'],
            'required': ['client_id', 'client_secret']}

    if 'provider_info' in dicts:
        _req = ['authorization_endpoint', 'jwks_uri',
                'response_types_supported', 'subject_types_supported',
                'id_token_signing_alg_values_supported']

        state['provider_info'] = {'immutable': ['issuer']}

        if return_type(_prof) not in ['I', 'IT']:
            _req.append('token_endpoint')

        state['provider_info']['required'] = _req

    return dicts, state, multi, notes
Esempio n. 5
0
def update_config(conf, tool_params):
    # provider_info and registration_response
    dicts = {'tool': conf['tool']}
    _prof = conf['tool']['profile']
    _spec = from_profile(conf['tool']['profile'])
    _spec['return_type'] = abbr_return_type(_spec['return_type'])
    del dicts['tool']['profile']
    dicts['tool'].update(_spec)

    for item in tool_params:
        if item == 'profile':
            continue
        if item not in dicts['tool']:
            dicts['tool'][item] = ''

    multi = {'tool': ['acr_values', 'claims_locales', 'ui_locales']}
    for typ in ['provider_info', 'registration_response']:
        multi[typ] = multi_value(typ)
        try:
            dicts[typ] = conf['client'][typ]
        except KeyError:
            try:
                dicts[typ] = update(typ, conf[typ])
            except KeyError:
                pass

    state = {
        'tool': {'immutable': ['issuer', 'tag', 'register', 'discover',
                               'webfinger'],
                 'required': ['return_type', 'contact_email']}}

    notes = ''
    if _spec['webfinger']:
        state['tool']['required'].extend(['webfinger_email',
                                          'webfinger_url'])
        notes = ("If <i>webfinger</i> is True then one of "
                 "<i>webfinger_email</i> and <i>webfinger_url</i> "
                 "<b>MUST</b> have a value.")

    if 'registration_response' in dicts:
        state['registration_response'] = {
            'immutable': ['redirect_uris'],
            'required': ['client_id', 'client_secret']}

    if 'provider_info' in dicts:
        _req = ['authorization_endpoint', 'jwks_uri',
                'response_types_supported', 'subject_types_supported',
                'id_token_signing_alg_values_supported']

        state['provider_info'] = {'immutable': ['issuer']}

        if return_type(_prof) not in ['I', 'IT']:
            _req.append('token_endpoint')

        state['provider_info']['required'] = _req

    return dicts, state, multi, notes
Esempio n. 6
0
def test_match_usage():
    assert match_usage({'usage': {'extra': True}},
                       **from_profile(PROFILE[0])) is False

    assert match_usage({"usage": {
        "return_type": ["C", "IT", "CI", "CIT", "CT"],
        "extra": True}}, **from_profile(PROFILE[0])) is False

    assert match_usage({"usage": {
        "return_type": ["C", "I", "IT", "CI", "CT", "CIT"]}},
        **from_profile(PROFILE[0]))

    assert match_usage({"usage": {
        "return_type": ["CI", "CT", "CIT"]}},
        **from_profile(PROFILE[0])) is False

    assert match_usage({"usage": {
        "return_type": ["C", "CI", "CT", "CIT"],
        "enc": True}},
        **from_profile(PROFILE[0]))
Esempio n. 7
0
    def matches_profile(self, profile):
        """
        Return a list of test IDs that all match the profile
        :param profile:
        :return:
        """

        _tids = []
        _use = from_profile(profile)
        for tid, spec in self.items():
            if match_usage(spec, **_use):
                _tids.append(tid)
        return _tids
Esempio n. 8
0
File: flow.py Progetto: rohe/otest
    def matches_profile(self, profile):
        """
        Return a list of test IDs that all match the profile
        :param profile:
        :return:
        """

        _tids = []
        _use = from_profile(profile)
        for tid, spec in self.items():
            if match_usage(spec, **_use):
                _tids.append(tid)
        return _tids
Esempio n. 9
0
 def mandatory_to_implement(self, tid, profile):
     _use = from_profile(profile)
     _use['return_type'] = _use['return_type'][0]
     spec = self[tid]
     try:
         _mti = spec["MTI"]
     except KeyError:
         pass
     else:
         if _use['return_type'][0] in _mti:
             if _use['register'] and 'DYN' in _mti:
                 if _use['discover'] and 'CNF' in _mti:
                     return True
     return False
Esempio n. 10
0
File: flow.py Progetto: rohe/otest
 def mandatory_to_implement(self, tid, profile):
     _use = from_profile(profile)
     _use['return_type'] = _use['return_type'][0]
     spec = self[tid]
     try:
         _mti = spec["MTI"]
     except KeyError:
         pass
     else:
         if _use['return_type'][0] in _mti:
             if _use['register'] and 'DYN' in _mti:
                 if _use['discover'] and 'CNF' in _mti:
                     return True
     return False
Esempio n. 11
0
    def set_profile(self, info):
        try:
            old = from_profile(self.sh.profile)

            new = from_profile(to_profile(info))
            for attr in [
                    'enc', 'extra', 'none', 'return_type', 'sig', 'form_post'
            ]:
                old[attr] = new[attr]

            # Store new configuration
            try:
                rest = self.sh.extra['rest']
            except KeyError:
                self.conv.tool_conf.update(compress_profile(old))
            else:
                qp = [quote_plus(p) for p in [self.sh.iss, self.sh.tag]]
                _, _conf = rest.read_conf(*qp)
                _conf['tool'].update(compress_profile(old))
                rest.store(qp[0], qp[1], _conf)

                # This will fail if no test has been run before the conf
                # is changed
                try:
                    self.conv.tool_conf = _conf['tool']
                except AttributeError:
                    pass

            # reset all test flows
            self.flows.test_info = {}
            self.flows.complete = {}
            self.sh.reset_session(profile=old['profile'])
            # Back to test list
            return self.inut.flow_list()
        except Exception as err:
            return self.inut.err_response("profile", err)
Esempio n. 12
0
    def create(self, **kwargs):
        logger.info('create test tool configuration: {} {}'.format(
            kwargs['iss'], kwargs['tag']))

        uqp, qp = unquote_quote(kwargs['iss'], kwargs['tag'])
        if not uqp[0].startswith('https://') and not uqp[0].startswith(
                'http://'):
            err = 'issuer value must start with "https://" or "http://"'
            logger.error(err)
            return as_bytes('Sorry failed to create: {}'.format(err))

        # construct profile
        try:
            profile = to_profile(kwargs)
        except KeyError as err:
            logger.error(err)
            return as_bytes('Sorry failed to create: {}'.format(err))

        _ent_conf = create_model(profile, ent_info_path=self.ent_info_path)

        if not do_discovery(profile):
            _ent_conf['client']['provider_info']['issuer'] = kwargs['iss']

        if not do_registration(profile):
            # need to create a redirect_uri, means I need to register a port
            _port = self.app.assigned_ports.register_port(
                kwargs['iss'], kwargs['tag'])
            if self.app.test_tool_base.endswith('/'):
                _base = self.app.test_tool_base[:-1]
            else:
                _base = self.app.test_tool_base
            _ent_conf['client']['registration_response'][
                'redirect_uris'] = '[ "{}:{}/authz_cb", "{}:{}/authz_post" ]'.format(
                    _base, _port, _base, _port)

        _ent_conf['tool']['issuer'] = uqp[0]
        _ent_conf['tool']['tag'] = uqp[1]
        _ent_conf['tool']['profile'] = profile

        _ent_conf.update(from_profile(profile))
        logger.info("Test tool config: {}".format(_ent_conf))

        self.rest.write(qp[0], qp[1], _ent_conf)
        # Do a redirect
        raise cherrypy.HTTPRedirect('/action/update?iss={}&tag={}'.format(
            qp[0], qp[1]))
Esempio n. 13
0
    def create(self, **kwargs):
        logger.info(
            'create test tool configuration: {} {}'.format(kwargs['iss'],
                                                           kwargs['tag']))

        uqp, qp = unquote_quote(kwargs['iss'], kwargs['tag'])
        if not uqp[0].startswith('https://') and not uqp[0].startswith('http://'):
            err = 'issuer value must start with "https://" or "http://"'
            logger.error(err)
            return as_bytes('Sorry failed to create: {}'.format(err))

        # construct profile
        try:
            profile = to_profile(kwargs)
        except KeyError as err:
            logger.error(err)
            return as_bytes('Sorry failed to create: {}'.format(err))

        _ent_conf = create_model(profile, ent_info_path=self.ent_info_path)

        if not do_discovery(profile):
            _ent_conf['client']['provider_info']['issuer'] = kwargs['iss']

        if not do_registration(profile):
            # need to create a redirect_uri, means I need to register a port
            _port = self.app.assigned_ports.register_port(kwargs['iss'],
                                                          kwargs['tag'])
            if self.app.test_tool_base.endswith('/'):
                _base = self.app.test_tool_base[:-1]
            else:
                _base = self.app.test_tool_base
            _ent_conf['client']['registration_response'][
                'redirect_uris'] = '[ "{}:{}/authz_cb", "{}:{}/authz_post" ]'.format(_base, _port, _base, _port)

        _ent_conf['tool']['issuer'] = uqp[0]
        _ent_conf['tool']['tag'] = uqp[1]
        _ent_conf['tool']['profile'] = profile

        _ent_conf.update(from_profile(profile))
        logger.info("Test tool config: {}".format(_ent_conf))

        self.rest.write(qp[0], qp[1], _ent_conf)
        # Do a redirect
        raise cherrypy.HTTPRedirect(
            '/action/update?iss={}&tag={}'.format(qp[0], qp[1]))
Esempio n. 14
0
def log_path(session, test_id=None):
    _conv = session["conv"]

    try:
        iss = _conv.entity.provider_info["issuer"]
    except TypeError:
        return ""
    else:
        qiss = quote_plus(iss)

    path = with_or_without_slash(os.path.join("log", qiss))
    if path is None:
        path = os.path.join("log", qiss)

    prof = ".".join(from_profile(session["profile"].split(".")))

    if not os.path.isdir("%s/%s" % (path, prof)):
        os.makedirs("%s/%s" % (path, prof))

    if test_id is None:
        test_id = session["testid"]

    return "%s/%s/%s" % (path, prof, test_id)
Esempio n. 15
0
 def match_profile(self, test_id):
     return match_usage(self.flows[test_id], **from_profile(self.sh.profile))
Esempio n. 16
0
def test_from_to_code():
    for ex, val in TESTS.items():
        f = from_profile(ex)
        assert f == val
        t = to_profile(f)
        assert t == ex
Esempio n. 17
0
 def match_profile(self, test_id):
     return match_usage(self.flows[test_id],
                        **from_profile(self.sh.profile))
Esempio n. 18
0
        'client_factory': Factory(Client), 'tool_conf': CONF.TOOL
    }

    if cargs.test_id:
        rtypes = []
        try:
            rtypes = FLOWS[cargs.test_id]['usage']['return_type']
        except KeyError:
            print('No such test ID')
            exit()

        if cargs.profile:
            # profile is of the form A.B.C.D.E
            # The first item represents the return_type
            rtypes = []
            _use = from_profile(cargs.profile)
            #_use['return_type'] = _use['return_type'][0]
            if match_usage(FLOWS[cargs.test_id], **_use):
                rtypes.append(_use['return_type'])
            kwargs['tool_conf']['profile'] = cargs.profile

        if len(rtypes) == 1:
            run_return_types(cargs.test_id, cargs.id, kwargs, rtypes)
        else:
            _res = run_return_types(cargs.test_id, cargs.id, kwargs, rtypes)
            if cargs.exit and _res is False:
                exit()
    else:
        if cargs.profile:
            rtypes = [cargs.profile]
        else:
Esempio n. 19
0
        'client_factory': Factory(Client), 'tool_conf': CONF.TOOL
    }

    if cargs.test_id:
        rtypes = []
        try:
            rtypes = FLOWS[cargs.test_id]['usage']['return_type']
        except KeyError:
            print('No such test ID')
            exit()

        if cargs.profile:
            # profile is of the form A.B.C.D.E
            # The first item represents the return_type
            rtypes = []
            _use = from_profile(cargs.profile)
            _use['return_type'] = _use['return_type'][0]
            if match_usage(FLOWS[cargs.test_id], **_use):
                rtypes.append(_use['return_type'])
            kwargs['tool_conf']['profile'] = cargs.profile

        if len(rtypes) == 1:
            run_return_types(cargs.test_id, cargs.id, kwargs, rtypes)
        else:
            _res = run_return_types(cargs.test_id, cargs.id, kwargs, rtypes)
            if cargs.exit and _res is False:
                exit()
    else:
        if cargs.profile:
            rtypes = [cargs.profile]
        else:
Esempio n. 20
0
def test_from_to_code():
    for ex, val in TESTS.items():
        f = from_profile(ex)
        assert f == val
        t = to_profile(f)
        assert t == ex