Ejemplo n.º 1
0
def test_extract_mode():
    mod, path = extract_mode("test_id")
    assert mod == {"test_id": "test_id"}
    assert path == ""

    mod, path = extract_mode(OIDCONF_PATTERN % "test_id")
    assert mod == {"test_id": "test_id"}
    assert path == '.well-known/openid-configuration'

    mod, path = extract_mode("/test_id/_/_/_/normal")
    assert mod == {"test_id": "test_id", "claims": ["normal"]}
    assert path == ''

    mod, path = extract_mode("/test_id/_/_/_/normal/token")
    assert mod == {"test_id": "test_id", "claims": ["normal"]}
    assert path == 'token'

    mod, path = extract_mode(
        "/test_id/RS256/RSA1_5:A128CBC-HS256/iat/normal/token")
    assert mod == {
        'behavior': ['iat'],
        'enc_alg': 'RSA1_5',
        'enc_enc': 'A128CBC-HS256',
        'sign_alg': 'RS256',
        'claims': ['normal'],
        'test_id': 'test_id'
    }
    assert path == 'token'

    mod, path = extract_mode(
        "/test_id/RS256/RSA1_5:A128CBC-HS256/iat,issi/normal,aggregated/token")
    assert mod == {
        'behavior': ['iat', 'issi'],
        'enc_alg': 'RSA1_5',
        'enc_enc': 'A128CBC-HS256',
        'sign_alg': 'RS256',
        'claims': ['normal', 'aggregated'],
        'test_id': 'test_id'
    }
    assert path == 'token'
Ejemplo n.º 2
0
def test_extract_mode():
    mod, path = extract_mode("test_id")
    assert mod == {"test_id": "test_id"}
    assert path == ""

    mod, path = extract_mode(OIDCONF_PATTERN % "test_id")
    assert mod == {"test_id": "test_id"}
    assert path == '.well-known/openid-configuration'

    mod, path = extract_mode("/test_id/_/_/_/normal")
    assert mod == {"test_id": "test_id", "claims": ["normal"]}
    assert path == ''

    mod, path = extract_mode("/test_id/_/_/_/normal/token")
    assert mod == {"test_id": "test_id", "claims": ["normal"]}
    assert path == 'token'

    mod, path = extract_mode(
        "/test_id/RS256/RSA1_5:A128CBC-HS256/iat/normal/token")
    assert mod == {'behavior': ['iat'],
                   'enc_alg': 'RSA1_5',
                   'enc_enc': 'A128CBC-HS256',
                   'sign_alg': 'RS256',
                   'claims': ['normal'],
                   'test_id': 'test_id'}
    assert path == 'token'

    mod, path = extract_mode(
        "/test_id/RS256/RSA1_5:A128CBC-HS256/iat,issi/normal,aggregated/token")
    assert mod == {'behavior': ['iat', 'issi'],
                   'enc_alg': 'RSA1_5',
                   'enc_enc': 'A128CBC-HS256',
                   'sign_alg': 'RS256',
                   'claims': ['normal', 'aggregated'],
                   'test_id': 'test_id'}
    assert path == 'token'
Ejemplo n.º 3
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)
Ejemplo n.º 4
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)