예제 #1
0
def test_register_site_command():
    # preset register client command response
    c = Client(config_location)
    c.oxd_id = None
    assert_is_none(c.oxd_id)
    c.register_site()
    assert_is_not_none(c.oxd_id)
예제 #2
0
def test_register_site_command():
    # preset register client command response
    c = Client(config_location)
    c.oxd_id = None
    assert_is_none(c.oxd_id)
    c.register_site()
    assert_is_not_none(c.oxd_id)
예제 #3
0
def oxd_login():
    if current_user.is_authenticated:
        return redirect(url_for("index.home"))

    config = current_app.config["OXD_CLIENT_CONFIG_FILE"]

    if not os.path.exists(config):
        flash("Unable to locate oxd client config file.".format(config),
              "warning")
        return redirect(url_for("index.home"))

    oxc = Client(config)

    try:
        auth_url = oxc.get_authorization_url()
    except OxdServerError as exc:
        print exc  # TODO: use logging
        flash("Failed to process the request due to error in OXD server.",
              "warning")
    except socket.error as exc:
        print exc  # TODO: use logging
        flash("Unable to connect to OXD server.", "warning")
    else:
        return redirect(auth_url)
    return redirect(url_for("index.home"))
예제 #4
0
def test_get_tokens_raises_error_if_response_has_error(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "error"
    mock_send.return_value.data.error = "MockError"
    mock_send.return_value.data.error_description = "No Tokens in Mock"

    with assert_raises(RuntimeError):
        c.get_tokens_by_code("code", "state")
예제 #5
0
def test_get_user_info_raises_error_on_oxd_error(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "error"
    mock_send.return_value.data.error = "MockError"
    mock_send.return_value.data.error_description = "No Claims for mock"

    with assert_raises(RuntimeError):
        c.get_user_info("some_token")
예제 #6
0
def test_logout_raises_error_when_oxd_return_error(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "error"
    mock_send.return_value.data.error = "MockError"
    mock_send.return_value.data.error_description = "Logout Mock Error"

    with assert_raises(RuntimeError):
        c.get_logout_uri()
예제 #7
0
def test_get_user_info_raises_error_on_oxd_error(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "error"
    mock_send.return_value.data.error = "MockError"
    mock_send.return_value.data.error_description = "No Claims for mock"

    with assert_raises(RuntimeError):
        c.get_user_info("some_token")
예제 #8
0
def test_get_tokens_raises_error_if_response_has_error(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "error"
    mock_send.return_value.data.error = "MockError"
    mock_send.return_value.data.error_description = "No Tokens in Mock"

    with assert_raises(RuntimeError):
        c.get_tokens_by_code("code", "state")
예제 #9
0
def test_logout_raises_error_when_oxd_return_error(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "error"
    mock_send.return_value.data.error = "MockError"
    mock_send.return_value.data.error_description = "Logout Mock Error"

    with assert_raises(RuntimeError):
        c.get_logout_uri()
예제 #10
0
def test_uma_rp_get_gat():
    c = Client(uma_config)
    scopes = [
        "http://photoz.example.com/dev/actions/view",
        "http://photoz.example.com/dev/actions/add"
    ]
    gat = c.uma_rp_get_gat(scopes)
    assert_is_instance(gat, str)
예제 #11
0
def test_get_user_info(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "ok"
    mock_send.return_value.data.claims = {"name": "mocky"}
    token = "tokken"
    command = {"command": "get_user_info", "params": {"oxd_id": c.oxd_id, "access_token": token}}
    claims = c.get_user_info(token)
    mock_send.assert_called_with(command)
    assert_equal(claims, {"name": "mocky"})
예제 #12
0
def oxd_login_callback():
    """Callback for OXD authorization_callback.
    """
    config = current_app.config["OXD_CLIENT_CONFIG_FILE"]
    oxc = Client(config)
    code = request.args.get('code')
    state = request.args.get('state')

    try:
        # these following API calls may raise RuntimeError caused by internal
        # error in oxd server.
        tokens = oxc.get_tokens_by_code(code, state)
        resp = oxc.get_user_info(tokens["access_token"])

        # ``user_name`` item is in ``user_name`` scope, hence
        # accessing this attribute may raise KeyError
        username = resp["user_name"][0]

        # ``role`` item is in ``permission`` scope, hence
        # accessing this attribute may raise KeyError
        role = ''
        if 'role' in resp:
            role = resp["role"][0].strip("[]")

        # disallow role other than ``cluster_manager``
        if username == 'admin' or role == "cluster_manager":
            user = User(username, "")
            login_user(user)
            return redirect(url_for("index.home"))

        else:
            flash("Invalid user's role.", "warning")

    except KeyError as exc:
        print exc  # TODO: use logging
        if exc.message == "user_name":
            msg = "user_name scope is not enabled in OIDC client"
        elif exc.message == "role":
            msg = "permission scope is not enabled in OIDC client " \
                  "or missing role attribute in user's info"
        flash(msg, "warning")
    except OxdServerError as exc:
        print exc  # TODO: use logging
        flash("Failed to process the request due to error in OXD server.",
              "warning")
    except socket.error as exc:
        print exc  # TODO: use logging
        flash("Unable to connect to OXD server.", "warning")

    logout_user()
    logout_resp = make_response(render_template("invalid_login.html"))
    logout_resp.set_cookie('sub', 'null', expires=0)
    logout_resp.set_cookie('JSESSIONID', 'null', expires=0)
    logout_resp.set_cookie('session_state', 'null', expires=0)
    logout_resp.set_cookie('session_id', 'null', expires=0)
    return logout()
    return render_template('invalid_login.html')
예제 #13
0
def test_get_tokens_by_code(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "ok"
    mock_send.return_value.data = "mock-token"
    code = "code"
    state = "state"
    command = {"command": "get_tokens_by_code", "params": {"oxd_id": c.oxd_id, "code": code, "state": state}}
    token = c.get_tokens_by_code(code, state)
    mock_send.assert_called_with(command)
    assert_equal(token, "mock-token")
예제 #14
0
def test_uma_rs_protect():
    c = Client(uma_config)
    resources = [
        {
            "path": "/photo",
            "conditions": [{"httpMethods": ["GET"], "scopes": ["http://photoz.example.com/dev/actions/view"]}],
        }
    ]

    assert_true(c.uma_rs_protect(resources))
예제 #15
0
def test_uma_rs_protect():
    c = Client(uma_config)
    resources = [{
        "path":
        "/photo",
        "conditions": [{
            "httpMethods": ["GET"],
            "scopes": ["http://photoz.example.com/dev/actions/view"]
        }]
    }]

    assert_true(c.uma_rs_protect(resources))
예제 #16
0
def test_get_user_info(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "ok"
    mock_send.return_value.data.claims = {"name": "mocky"}
    token = "tokken"
    command = {"command": "get_user_info",
               "params": {
                   "oxd_id": c.oxd_id,
                   "access_token": token
                   }}
    claims = c.get_user_info(token)
    mock_send.assert_called_with(command)
    assert_equal(claims, {"name": "mocky"})
예제 #17
0
def test_get_tokens_by_code_by_url(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "ok"
    mock_send.return_value.data.access_token = "mock-token"
    url = "https://client.example.com/callback#state=demo123&code=d1e2m3o4"\
          "&scopes=openid%20profile"
    command = {"command": "get_tokens_by_code",
               "params": {
                   "oxd_id": c.oxd_id,
                   "url": url
                   }}
    access_token = c.get_tokens_by_code_by_url(url)
    mock_send.assert_called_with(command)
    assert_equal(access_token, "mock-token")
예제 #18
0
def test_get_tokens_by_code(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "ok"
    mock_send.return_value.data = "mock-token"
    code = "code"
    state = "state"
    command = {
        "command": "get_tokens_by_code",
        "params": {
            "oxd_id": c.oxd_id,
            "code": code,
            "state": state
        }
    }
    token = c.get_tokens_by_code(code, state)
    mock_send.assert_called_with(command)
    assert_equal(token, "mock-token")
예제 #19
0
def test_initializes_with_config():
    c = Client(config_location)
    assert_equal(c.config.get('oxd', 'port'), '8099')
    assert_is_instance(c.msgr, Messenger)
    assert_equal(c.application_type, "web")
    assert_equal(c.authorization_redirect_uri,
                 "https://client.example.com/callback")
    assert_is_instance(c.oxd_id, str)
예제 #20
0
def test_logout(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "ok"
    mock_send.return_value.data.uri = "https://example.com/end_session"

    params = {"oxd_id": c.oxd_id}
    command = {"command": "get_logout_uri", "params": params}

    # called with no optional params
    uri = c.get_logout_uri()
    mock_send.assert_called_with(command)

    # called with OPTIONAL id_token_hint
    uri = c.get_logout_uri("some_id")
    command["params"]["id_token_hint"] = "some_id"
    mock_send.assert_called_with(command)
    assert_equal(uri, "https://example.com/end_session")

    # called wiht OPTIONAL id_token_hint + post_logout_redirect_uri
    uri = c.get_logout_uri("some_id", "https://some.site/logout")
    command["params"]["post_logout_redirect_uri"] = "https://some.site/logout"
    mock_send.assert_called_with(command)

    # called wiht OPTIONAL id_token_hint + post_logout_redirect_uri + state
    uri = c.get_logout_uri("some_id", "https://some.site/logout", "some-s")
    command["params"]["state"] = "some-s"
    mock_send.assert_called_with(command)

    # called wiht OPTIONAL id_token_hint + post_logout_redirect_uri
    uri = c.get_logout_uri("some_id", "https://some.site/logout", "some-s",
                           "some-ss")
    command["params"]["session_state"] = "some-ss"
    mock_send.assert_called_with(command)
예제 #21
0
def teardown_package():
    this_dir = os.path.dirname(os.path.realpath(__file__))
    configs = [
        os.path.join(this_dir, 'data', 'initial.cfg'),
        os.path.join(this_dir, 'data', 'umaclient.cfg')
    ]
    for config in configs:
        c = Client(config)
        c.config.set('oxd', 'id', '')
예제 #22
0
def test_get_auth_url_accepts_optional_params():
    c = Client(config_location)
    # acr values
    auth_url = c.get_authorization_url(["basic", "gplus"])
    assert_in('basic', auth_url)
    assert_in('gplus', auth_url)

    # prompt
    auth_url = c.get_authorization_url(["basic"], "login")
    assert_in('basic', auth_url)
    assert_in('prompt', auth_url)

    # scope
    auth_url = c.get_authorization_url(["basic"], None,
                                       ["openid", "profile", "email"])
    assert_in('openid', auth_url)
    assert_in('profile', auth_url)
    assert_in('email', auth_url)
예제 #23
0
def test_openid_commands(config_file):
    """function that runs the commands in a interactive manner

    :param config_file: config file location
    """
    c = Client(config_file)

    print "\n=> Registering client using register_site()"
    oxd_id = c.register_site()
    logging.info("Received: %s", oxd_id)

    print "\n=> Update site registration"
    updated = c.update_site()
    c.config.set("client", "scope", "openid,profile")
    logging.info("Received: %s", updated)

    print "\n=> Getting auth URL"
    auth_url = c.get_authorization_url()
    print "Visit this URL in your browser: ", auth_url
    logging.info("Received: %s", auth_url)

    print "\n=> Getting tokens by code"
    callback_url = raw_input("Enter redirected URL to parse tokens: ")
    parsed = urlparse.urlparse(callback_url)
    params = urlparse.parse_qs(parsed.query)
    tokens = c.get_tokens_by_code(params['code'][0], params['state'][0])
    logging.info("Received: %s", tokens)

    print "\n=> Getting user info"
    claims = c.get_user_info(tokens['access_token'])
    logging.info("Received: %s", claims)

    print "\n=> Getting new access token using refresh token"
    new_token = c.get_access_token_by_refresh_token(tokens["refresh_token"])
    logging.info("Received: %s", new_token)

    print "\n=> Getting Logout URI"
    logout_uri = c.get_logout_uri()
    logging.info("Received: %s", logout_uri)
    print "Visit this URL to logout: ", logout_uri

    print "\n=> Remove Site"
    oxd_id = c.remove_site()
    logging.info("Received: %s", oxd_id)
예제 #24
0
def test_get_tokens_raises_error_for_invalid_args():
    c = Client(config_location)
    # Empty code should raise error
    with assert_raises(RuntimeError):
        c.get_tokens_by_code("", ["openid"], "state")

    # Empty list for scopes should raise error
    with assert_raises(RuntimeError):
        c.get_tokens_by_code("code", [], "state")

    # raise error when scopes is not a list
    with assert_raises(RuntimeError):
        c.get_tokens_by_code("code", "openid", "state")
예제 #25
0
def logout():
    logout_user()

    if os.path.exists(current_app.config["OXD_CLIENT_CONFIG_FILE"]):

        config = current_app.config["OXD_CLIENT_CONFIG_FILE"]
        oxc = Client(config)

        # If site is not registered, first register it
        if not oxc.config.get('oxd', 'id'):
            oxc.register_site()

        logout_url = oxc.get_logout_uri()
        return redirect(logout_url)

    pw_file = os.path.join(current_app.config['DATA_DIR'], '.pw')

    if os.path.exists(pw_file):
        os.remove(pw_file)

    return redirect(url_for("auth.login"))
예제 #26
0
def test_logout(mock_send):
    c = Client(config_location)
    mock_send.return_value.status = "ok"
    mock_send.return_value.data.uri = "https://example.com/end_session"

    params = {"oxd_id": c.oxd_id}
    command = {"command": "get_logout_uri", "params": params}

    # called with no optional params
    uri = c.get_logout_uri()
    mock_send.assert_called_with(command)

    # called with OPTIONAL id_token_hint
    uri = c.get_logout_uri("some_id")
    command["params"]["id_token_hint"] = "some_id"
    mock_send.assert_called_with(command)
    assert_equal(uri, "https://example.com/end_session")

    # called wiht OPTIONAL id_token_hint + post_logout_redirect_uri
    uri = c.get_logout_uri("some_id", "https://some.site/logout")
    command["params"]["post_logout_redirect_uri"] = "https://some.site/logout"
    mock_send.assert_called_with(command)

    # called wiht OPTIONAL id_token_hint + post_logout_redirect_uri + state
    uri = c.get_logout_uri("some_id", "https://some.site/logout", "some-s")
    command["params"]["state"] = "some-s"
    mock_send.assert_called_with(command)

    # called wiht OPTIONAL id_token_hint + post_logout_redirect_uri
    uri = c.get_logout_uri("some_id", "https://some.site/logout", "some-s", "some-ss")
    command["params"]["session_state"] = "some-ss"
    mock_send.assert_called_with(command)
예제 #27
0
def test_get_auth_url_accepts_optional_params():
    c = Client(config_location)
    # acr values
    auth_url = c.get_authorization_url(["basic", "gplus"])
    assert_in("basic", auth_url)
    assert_in("gplus", auth_url)

    # prompt
    auth_url = c.get_authorization_url(["basic"], "login")
    assert_in("basic", auth_url)
    assert_in("prompt", auth_url)

    # scope
    auth_url = c.get_authorization_url(["basic"], None, ["openid", "profile", "email"])
    assert_in("openid", auth_url)
    assert_in("profile", auth_url)
    assert_in("email", auth_url)

    # hd
    auth_url = c.get_authorization_url(None, None, None, "https://test.com")
    assert_in("https://test.com", auth_url)
    assert_in("hd", auth_url)
예제 #28
0
def test_setup_client(config_file):
    c = Client(config_file)

    print "\n=> Setup Client"
    response = c.setup_client()
    logging.info("Received: %s", response)

    print "\n=> Get Client Token"
    # Set auto_update to False to prevent launching of new thread. auto_update
    # is helpful for long running apps, but unnecessary for this test script
    token = c.get_client_token(auto_update=False)
    logging.info("Received: %s", token)

    print "\n=> Introspect Access Token"
    introspection = c.introspect_access_token(token['access_token'])
    logging.info("Received: %s", introspection)

    print "\n=> Remove Site"
    oxd_id = c.remove_site()
    logging.info("Received: %s", oxd_id)
예제 #29
0
def test_uma_rp_authorize_rpt_throws_errors():
    c = Client(uma_config)
    rpt = 'invalid_rpt'
    ticket = 'invalid_ticket'
    response = c.uma_rp_authorize_rpt(rpt, ticket)
    assert_equal(response.status, 'error')
예제 #30
0
def test_uma_rp_authorize_rpt():
    c = Client(uma_config)
    rpt = 'dummy_rpt'
    ticket = 'dummy_ticket'
    status = c.uma_rp_authorize_rpt(rpt, ticket)
    assert_true(status)
예제 #31
0
def test_get_authorization_url():
    c = Client(config_location)
    auth_url = c.get_authorization_url()
    assert_in('callback', auth_url)
예제 #32
0
def test_update_site_registration():
    c = Client(config_location)
    c.config.set("client", "post_logout_redirect_uri", "https://client.example.com/")
    status = c.update_site_registration()
    assert_true(status)
예제 #33
0
def test_uma_rp_get_gat():
    c = Client(uma_config)
    scopes = ["http://photoz.example.com/dev/actions/view", "http://photoz.example.com/dev/actions/add"]
    gat = c.uma_rp_get_gat(scopes)
    assert_is_instance(gat, str)
예제 #34
0
def test_get_user_info_raises_erro_on_invalid_args():
    c = Client(config_location)
    # Empty code should raise error
    with assert_raises(RuntimeError):
        c.get_user_info("")
예제 #35
0
def test_register_raises_runtime_error_for_oxd_error_response():
    config = os.path.join(this_dir, "data", "no_oxdid.cfg")
    c = Client(config)
    with assert_raises(RuntimeError):
        c.register_site()
예제 #36
0
def test_get_auth_url_accepts_acrvalues_as_optional_params():
    c = Client(config_location)
    auth_url = c.get_authorization_url(["basic", "gplus"])
    assert_in('basic', auth_url)
    assert_in('gplus', auth_url)
예제 #37
0
def test_get_authorization_url():
    c = Client(config_location)
    auth_url = c.get_authorization_url()
    assert_in("callback", auth_url)
예제 #38
0
def test_get_authorization_url_works_wihtout_explicit_site_registration():
    c = Client(config_location)
    c.oxd_id = None  # assume the client isn't registered
    auth_url = c.get_authorization_url()
    assert_in("callback", auth_url)
예제 #39
0
def test_uma_rp_get_rpt_force_new():
    c = Client(uma_config)
    c.register_site()
    rpt2 = c.uma_rp_get_rpt(True)
    assert_is_instance(rpt2, str)
예제 #40
0
def test_uma_rp_get_rpt():
    c = Client(uma_config)
    c.register_site()
    rpt = c.uma_rp_get_rpt()
    assert_is_instance(rpt, str)
예제 #41
0
def test_uma_rp_authorize_rpt_throws_errors():
    c = Client(uma_config)
    rpt = "invalid_rpt"
    ticket = "invalid_ticket"
    response = c.uma_rp_authorize_rpt(rpt, ticket)
    assert_equal(response.status, "error")
예제 #42
0
def test_register_raises_runtime_error_for_oxd_error_response():
    config = os.path.join(this_dir, 'data', 'no_oxdid.cfg')
    c = Client(config)
    with assert_raises(RuntimeError):
        c.register_site()
예제 #43
0
def test_uma_rp_authorize_rpt():
    c = Client(uma_config)
    rpt = "dummy_rpt"
    ticket = "dummy_ticket"
    status = c.uma_rp_authorize_rpt(rpt, ticket)
    assert_true(status)
예제 #44
0
def test_get_authorization_url_works_wihtout_explicit_site_registration():
    c = Client(config_location)
    c.oxd_id = None  # assume the client isn't registered
    auth_url = c.get_authorization_url()
    assert_in('callback', auth_url)
예제 #45
0
def test_update_site_registration():
    c = Client(config_location)
    c.config.set('client', 'post_logout_redirect_uri',
                 'https://client.example.com/')
    status = c.update_site_registration()
    assert_true(status)
예제 #46
0
def test_get_user_info_raises_erro_on_invalid_args():
    c = Client(config_location)
    # Empty code should raise error
    with assert_raises(RuntimeError):
        c.get_user_info("")
예제 #47
0
def test_uma_rp_get_rpt():
    c = Client(uma_config)
    c.register_site()
    rpt = c.uma_rp_get_rpt()
    assert_is_instance(rpt, str)
예제 #48
0
def run_commands(config):
    """function that runs the commands for UMA RS app context

    :param config: config file location
    :return: None
    """
    c = Client(config)

    print "\n=> Setup client"
    oxd_id = c.setup_client()
    logging.info("Received: %s", oxd_id)

    print "\n=> Get Client Token"
    tokens = c.get_client_token(auto_update=False)
    logging.info("Received: %s", tokens)

    print "\n=> Protecting Resource: "
    rset = ResourceSet()
    r = rset.add("/photoz")
    r.set_scope("GET", "https://photoz.example.com/uma/scope/view")
    print rset
    protected = c.uma_rs_protect(rset.dump())
    logging.info("Received: %s", protected)

    print "\n=> Checking Access for URL /photoz, with method GET"
    access_status = c.uma_rs_check_access(rpt=None,
                                          path='/photoz',
                                          http_method='GET')
    print "\n=> Checking Access Response:", access_status
    logging.info('Received: %s', access_status)

    print "\n=> Get RPT (Need Info Error)"
    need_info = c.uma_rp_get_rpt(ticket=access_status['ticket'])
    logging.info('Received: %s', need_info)

    print "\n=> Get Claims Gathering Url"
    claims_url = c.uma_rp_get_claims_gathering_url(
        ticket=need_info['details']['ticket'])
    print "Visit this URL in your browser: ", claims_url
    logging.info('Received: %s', claims_url)

    print "\n=> Get RPT"
    callback_url = raw_input(
        "Enter redirected URL to parse ticket and state: ")
    parsed = urlparse.urlparse(callback_url)
    params = urlparse.parse_qs(parsed.query)
    rpt_resp = c.uma_rp_get_rpt(ticket=params['ticket'][0],
                                state=params['state'][0])
    logging.info("Received: %s", rpt_resp)

    print "\n=> Introspect RPT"
    introspection = c.introspect_rpt(rpt=rpt_resp['access_token'])
    logging.info('Received: %s', introspection)

    print "\n=> Checking Access for URL /photoz, with RPT and method GET"
    access = c.uma_rs_check_access(rpt=rpt_resp['access_token'],
                                   path='/photoz',
                                   http_method='GET')
    print "\n=> Checking Access Response:", access
    logging.info('Received: %s', access)

    print "\n=> Protecting Resource with Scope_expression"
    rset = ResourceSet()
    r = rset.add("/photo")
    scope_expr = {
        "rule": {
            "and": [{
                "or": [{
                    "var": 0
                }, {
                    "var": 1
                }]
            }, {
                "var": 2
            }]
        },
        "data": [
            "http://photoz.example.com/dev/actions/all",
            "http://photoz.example.com/dev/actions/add",
            "http://photoz.example.com/dev/actions/internalClient"
        ]
    }
    r.set_expression("GET", scope_expr)
    print rset
    protected = c.uma_rs_protect(rset.dump())
    logging.info("Received: %s", protected)

    print "\n=> Checking Access for URL /photo, with scope_expression"
    access_status = c.uma_rs_check_access(rpt=None,
                                          path='/photo',
                                          http_method='GET')
    print "\n=> Checking Access Response:", access_status
    logging.info('Received: %s', access_status)
예제 #49
0
def test_uma_rp_get_rpt_force_new():
    c = Client(uma_config)
    c.register_site()
    rpt2 = c.uma_rp_get_rpt(True)
    assert_is_instance(rpt2, str)