Пример #1
0
def test_mode2path():
    path = mode2path({"test_id": "test_id"})
    assert path == "test_id/_/_/_/normal"

    path = mode2path({"test_id": "test_id", "claims": ["aggregated"]})
    assert path == "test_id/_/_/_/aggregated"

    path = mode2path({'behavior': ['iat', 'issi'], 'enc_alg': 'RSA1_5',
                      'enc_enc': 'A128CBC-HS256', 'sign_alg': 'RS256',
                      'claims': ['normal', 'aggregated'], 'test_id': 'test_id'})
    assert path == ("test_id/RS256/RSA1_5:A128CBC-HS256/iat,issi/"
                    "normal,aggregated")
Пример #2
0
def test_mode2path():
    path = mode2path({"test_id": "test_id"})
    assert path == "test_id/_/_/_/normal"

    path = mode2path({"test_id": "test_id", "claims": ["aggregated"]})
    assert path == "test_id/_/_/_/aggregated"

    path = mode2path({
        'behavior': ['iat', 'issi'],
        'enc_alg': 'RSA1_5',
        'enc_enc': 'A128CBC-HS256',
        'sign_alg': 'RS256',
        'claims': ['normal', 'aggregated'],
        'test_id': 'test_id'
    })
    assert path == ("test_id/RS256/RSA1_5:A128CBC-HS256/iat,issi/"
                    "normal,aggregated")
Пример #3
0
def do_flow(iss, cinfo, mode, flow, static=None):
    """

    :param iss:
    :param cinfo:
    :param mode:
    :param flow:
    :return:
    """

    cli = Client()
    for arg, val in cinfo.items():
        setattr(cli, arg, val)

    _path = mode2path(mode)
    if iss.endswith("/"):
        url = "%s%s" % (iss, _path)
    else:
        url = "%s/%s" % (iss, _path)

    pcr = {}

    for action, args in flow:
        if action == "discover":
            if args:
                issuer = cli.discover(args)
            else:
                issuer = cli.discover(url)
        elif action == "provider_info":
            if not issuer:
                issuer = url
            pcr = cli.provider_config(issuer)
        elif action == "registration":
            try:
                _endp = pcr["registration_endpoint"]
            except KeyError:
                _endp = static["registration_endpoint"]
            _ = cli.register(_endp)
        elif action == "authn_req":
            state = rndstr()
            resp = cli.do_authorization_request(
                state=state, request_args=args)
            print resp
        elif action == "token_req":
            pass
        elif action == "userinfo_req":
            pass

    return
Пример #4
0
def do_flow(iss, cinfo, mode, flow, static=None):
    """

    :param iss:
    :param cinfo:
    :param mode:
    :param flow:
    :return:
    """

    cli = Client()
    for arg, val in cinfo.items():
        setattr(cli, arg, val)

    _path = mode2path(mode)
    if iss.endswith("/"):
        url = "%s%s" % (iss, _path)
    else:
        url = "%s/%s" % (iss, _path)

    pcr = {}

    for action, args in flow:
        if action == "discover":
            if args:
                issuer = cli.discover(args)
            else:
                issuer = cli.discover(url)
        elif action == "provider_info":
            if not issuer:
                issuer = url
            pcr = cli.provider_config(issuer)
        elif action == "registration":
            try:
                _endp = pcr["registration_endpoint"]
            except KeyError:
                _endp = static["registration_endpoint"]
            _ = cli.register(_endp)
        elif action == "authn_req":
            state = rndstr()
            resp = cli.do_authorization_request(state=state, request_args=args)
            print resp
        elif action == "token_req":
            pass
        elif action == "userinfo_req":
            pass

    return
Пример #5
0
def application(environ, start_response):
    """
    :param environ: The HTTP application environment
    :param start_response: The application to run when the handling of the
        request is done
    :return: The response as a list of lines
    """
    global OAS
    session = environ['beaker.session']
    path = environ.get('PATH_INFO', '').lstrip('/')
    response_encoder = ResponseEncoder(environ=environ,
                                       start_response=start_response)
    parameters = parse_qs(environ["QUERY_STRING"])

    if path == "robots.txt":
        return static(environ, start_response, "static/robots.txt")

    if path.startswith("static/"):
        return static(environ, start_response, path)
    elif path.startswith("log"):
        return display_log(environ, start_response)
    elif path.startswith("_static/"):
        return static(environ, start_response, path)
    
    trace = Trace()

    if path == "test_list":
        return rp_test_list(environ, start_response)
    elif path == "":
        return registration(environ, start_response)
    elif path == "generate_client_credentials":
        client_id, client_secret = generate_static_client_credentials(parameters)
        return response_encoder.return_json(
            json.dumps({"client_id": client_id,
                        "client_secret": client_secret}))
    elif path == "claim":
        _oas = session["op"]
        authz = environ["HTTP_AUTHORIZATION"]
        try:
            assert authz.startswith("Bearer")
        except AssertionError:
            resp = BadRequest()
        else:
            tok = authz[7:]
            try:
                _claims = _oas.claim_access_token[tok]
            except KeyError:
                resp = BadRequest()
            else:
                del _oas.claim_access_token[tok]
                resp = Response(json.dumps(_claims), content='application/json')
        return resp(environ, start_response)

    mode, endpoint = extract_mode(path)

    if endpoint == ".well-known/webfinger":
        _p = urlparse(parameters["resource"][0])
        if _p.scheme in ["http", "https"]:
            mode = {"test_id": _p.path[1:]}
        elif _p.scheme == "acct":
            _l, _ = _p.path.split('@')
            mode = {"test_id": _l}
        else:
            resp = ServiceError("Unknown scheme: {}".format(_p.scheme))
            return resp(environ, start_response)

    if mode:
        session["test_id"] = mode["test_id"]

    if "op" not in session:
        session["op"] = setup_op(mode, COM_ARGS, OP_ARG)
        session["mode_path"] = mode2path(mode)
    else:  # may be a new mode
        _path = mode2path(mode)
        if session["mode_path"] != _path:
            session["op"] = setup_op(mode, COM_ARGS, OP_ARG)
            session["mode_path"] = _path

    for regex, callback in URLS:
        match = re.search(regex, endpoint)
        if match is not None:
            trace.request("PATH: %s" % endpoint)
            trace.request("METHOD: %s" % environ["REQUEST_METHOD"])
            try:
                trace.request(
                    "HTTP_AUTHORIZATION: %s" % environ["HTTP_AUTHORIZATION"])
            except KeyError:
                pass

            try:
                environ['oic.url_args'] = match.groups()[0]
            except IndexError:
                environ['oic.url_args'] = endpoint

            LOGGER.info("callback: %s" % callback)
            try:
                if hasattr(callback, 'func'):
                    return callback.func(environ, start_response, session, trace)
                else:
                    return callback(environ, start_response, session, trace)
            except Exception as err:
                print >> sys.stderr, "%s" % err
                message = traceback.format_exception(*sys.exc_info())
                print >> sys.stderr, message
                LOGGER.exception("%s" % err)
                resp = ServiceError("%s" % err)
                return resp(environ, start_response)

    LOGGER.debug("unknown side: %s" % endpoint)
    resp = NotFound("Couldn't find the side you asked for!")
    return resp(environ, start_response)
Пример #6
0
def application(environ, start_response):
    """
    :param environ: The HTTP application environment
    :param start_response: The application to run when the handling of the
        request is done
    :return: The response as a list of lines
    """
    global OAS
    session = environ['beaker.session']
    path = environ.get('PATH_INFO', '').lstrip('/')
    response_encoder = ResponseEncoder(environ=environ,
                                       start_response=start_response)
    parameters = parse_qs(environ["QUERY_STRING"])

    if path == "robots.txt":
        return static(environ, start_response, "static/robots.txt")

    if path.startswith("static/"):
        return static(environ, start_response, path)
    elif path.startswith("log"):
        return display_log(environ, start_response)
    elif path.startswith("_static/"):
        return static(environ, start_response, path)
    
    trace = Trace()

    if path == "test_list":
        return rp_test_list(environ, start_response)
    elif path == "":
        return registration(environ, start_response)
    elif path == "generate_client_credentials":
        client_id, client_secret = generate_static_client_credentials(parameters)
        return response_encoder.return_json(
            json.dumps({"client_id": client_id,
                        "client_secret": client_secret}))
    elif path == "claim":
        _oas = session["op"]
        authz = environ["HTTP_AUTHORIZATION"]
        try:
            assert authz.startswith("Bearer")
        except AssertionError:
            resp = BadRequest()
        else:
            tok = authz[7:]
            try:
                _claims = _oas.claim_access_token[tok]
            except KeyError:
                resp = BadRequest()
            else:
                del _oas.claim_access_token[tok]
                resp = Response(json.dumps(_claims), content='application/json')
        return resp(environ, start_response)

    mode, endpoint = extract_mode(path)

    if endpoint == ".well-known/webfinger":
        _p = urlparse(parameters["resource"][0])
        if _p.scheme in ["http", "https"]:
            mode = {"test_id": _p.path[1:]}
        elif _p.scheme == "acct":
            _l, _ = _p.path.split('@')
            mode = {"test_id": _l}
        else:
            resp = ServiceError("Unknown scheme: {}".format(_p.scheme))
            return resp(environ, start_response)

    if mode:
        session["test_id"] = mode["test_id"]

    if "op" not in session:
        session["op"] = setup_op(mode, COM_ARGS, OP_ARG)
        session["mode_path"] = mode2path(mode)
    else:  # may be a new mode
        _path = mode2path(mode)
        if session["mode_path"] != _path:
            session["op"] = setup_op(mode, COM_ARGS, OP_ARG)
            session["mode_path"] = _path

    for regex, callback in URLS:
        match = re.search(regex, endpoint)
        if match is not None:
            trace.request("PATH: %s" % endpoint)
            trace.request("METHOD: %s" % environ["REQUEST_METHOD"])
            try:
                trace.request(
                    "HTTP_AUTHORIZATION: %s" % environ["HTTP_AUTHORIZATION"])
            except KeyError:
                pass

            try:
                environ['oic.url_args'] = match.groups()[0]
            except IndexError:
                environ['oic.url_args'] = endpoint

            LOGGER.info("callback: %s" % callback)
            try:
                return callback(environ, start_response, session, trace)
            except Exception as err:
                print >> sys.stderr, "%s" % err
                message = traceback.format_exception(*sys.exc_info())
                print >> sys.stderr, message
                LOGGER.exception("%s" % err)
                resp = ServiceError("%s" % err)
                return resp(environ, start_response)

    LOGGER.debug("unknown side: %s" % endpoint)
    resp = NotFound("Couldn't find the side you asked for!")
    return resp(environ, start_response)