Ejemplo n.º 1
0
def _setup_ga4gh_info(db_session,
                      rsa_private_key,
                      kid,
                      access_1_expires=None,
                      access_2_expires=None):
    """
    Setup some testing data.

    Args:
        access_1_expires (str, optional): expiration for the Proxy Group ->
            Google Bucket Access Group for user 1, defaults to None
        access_2_expires (str, optional): expiration for the Proxy Group ->
            Google Bucket Access Group for user 2, defaults to None
    """
    test_user = add_test_ras_user(db_session)
    _, visa1 = add_visa_manually(db_session,
                                 test_user,
                                 rsa_private_key,
                                 kid,
                                 expires=access_1_expires)
    _, visa2 = add_visa_manually(db_session,
                                 test_user,
                                 rsa_private_key,
                                 kid,
                                 expires=access_2_expires)

    return {
        "ga4gh_visas": {
            "1": visa1.id,
            "2": visa2.id,
            "test_user": test_user
        }
    }
Ejemplo n.º 2
0
def test_update_visa_empty_passport_returned(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    rsa_public_key,
    kid,
):
    """
    Test to handle empty passport sent from RAS
    """
    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": "abcd-asdj-sajpiasj12iojd-asnoin",
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": "admin_user",
        "email": "",
        "passport_jwt_v11": "",
    }
    mock_userinfo.return_value = userinfo_response

    test_user = add_test_user(db_session)
    add_visa_manually(db_session, test_user, rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    pkey_cache = {
        "https://stsstg.nih.gov": {
            kid: rsa_public_key,
        }
    }
    ras_client.update_user_visas(test_user, pkey_cache=pkey_cache)

    query_visa = db_session.query(GA4GHVisaV1).first()
    assert query_visa == None
Ejemplo n.º 3
0
def test_update_visa_empty_visa_returned(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    kid,
    kid_2,
):
    """
    Test to check if the db is emptied if the ras userinfo sends back an empty visa
    """

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": "abcd-asdj-sajpiasj12iojd-asnoin",
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": "admin_user",
        "email": "",
    }
    userinfo_response["ga4gh_passport_v1"] = []

    mock_userinfo.return_value = userinfo_response

    test_user = add_test_user(db_session)
    add_visa_manually(db_session, test_user, rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    ras_client.update_user_visas(test_user)

    query_visa = db_session.query(GA4GHVisaV1).first()
    assert query_visa == None
Ejemplo n.º 4
0
def test_update_visa_token(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    rsa_public_key,
    kid,
    mock_arborist_requests,
    no_app_context_no_public_keys,
):
    """
    Test to check visa table is updated when getting new visa
    """

    # ensure we don't actually try to reach out to external sites to refresh public keys
    def validate_jwt_no_key_refresh(*args, **kwargs):
        kwargs.update({"attempt_refresh": False})
        return validate_jwt(*args, **kwargs)

    # ensure there is no application context or cached keys
    temp_stored_public_keys = flask.current_app.jwt_public_keys
    temp_app_context = flask.has_app_context
    del flask.current_app.jwt_public_keys

    def return_false():
        return False

    flask.has_app_context = return_false

    mock_arborist_requests(
        {f"arborist/user/{TEST_RAS_USERNAME}": {
            "PATCH": (None, 204)
        }})

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": TEST_RAS_SUB,
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": TEST_RAS_USERNAME,
        "email": "",
    }

    test_user = add_test_ras_user(db_session)
    existing_encoded_visa, _ = add_visa_manually(db_session, test_user,
                                                 rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    # use default user and passport
    subjects_to_passports = get_subjects_to_passports(
        kid=kid, rsa_private_key=rsa_private_key)

    userinfo_response["passport_jwt_v11"] = subjects_to_passports[
        TEST_RAS_SUB]["encoded_passport"]
    mock_userinfo.return_value = userinfo_response

    pkey_cache = {
        "https://stsstg.nih.gov": {
            kid: rsa_public_key,
        }
    }
    ras_client.update_user_authorization(
        test_user,
        pkey_cache=pkey_cache,
        db_session=db_session,
    )

    # restore public keys and context
    flask.current_app.jwt_public_keys = temp_stored_public_keys
    flask.has_app_context = temp_app_context

    query_visas = [
        item.ga4gh_visa
        for item in db_session.query(GA4GHVisaV1).filter_by(user=test_user)
    ]

    # at this point we expect the existing visa to stay around (since it hasn't expired)
    # and the new visa should also show up
    assert len(query_visas) == 2
    assert existing_encoded_visa in query_visas
    for visa in subjects_to_passports[TEST_RAS_SUB]["encoded_visas"]:
        assert visa in query_visas
Ejemplo n.º 5
0
def test_visa_update_cronjob(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    db_session,
    rsa_private_key,
    rsa_public_key,
    kid,
    mock_arborist_requests,
    no_app_context_no_public_keys,
):
    """
    Test to check visa table is updated when updating visas using cronjob
    """
    mock_arborist_requests(
        {f"arborist/user/{TEST_RAS_USERNAME}": {
            "PATCH": (None, 204)
        }})
    # reset users table
    db_session.query(User).delete()
    db_session.query(GA4GHVisaV1).delete()
    db_session.commit()

    n_users = 3
    n_users_no_visas = 2

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"

    def _get_token_response_for_user(*args, **kwargs):
        token_response = {
            "access_token": f"{args[0].id}",
            "id_token": f"{args[0].id}-id12345abcdef",
            "refresh_token": f"{args[0].id}-refresh12345abcdefg",
        }
        return token_response

    mock_get_token.side_effect = _get_token_response_for_user

    user_id_to_ga4gh_info = {}

    for i in range(1, n_users + 1):
        username = "******".format(i)
        test_user = add_test_ras_user(db_session,
                                      username,
                                      subject_id=username)
        encoded_visa, visa = add_visa_manually(db_session,
                                               test_user,
                                               rsa_private_key,
                                               kid,
                                               sub=username)
        user_id_to_ga4gh_info[str(test_user.id)] = {
            "encoded_visa": encoded_visa
        }

        passport_header = {
            "type": "JWT",
            "alg": "RS256",
            "kid": kid,
        }
        new_passport = {
            "iss":
            "https://stsstg.nih.gov",
            "sub":
            username,
            "iat":
            int(time.time()),
            "scope":
            "openid ga4gh_passport_v1 email profile",
            "exp":
            int(time.time()) + 1000,
            "ga4gh_passport_v1":
            [user_id_to_ga4gh_info[str(test_user.id)]["encoded_visa"]],
        }

        userinfo_response = {
            "sub": username,
            "name": "",
            "preferred_username": "******",
            "UID": "",
            "UserID": username + "_USERNAME",
            "email": "",
        }
        encoded_passport = jwt.encode(
            new_passport,
            key=rsa_private_key,
            headers=passport_header,
            algorithm="RS256",
        ).decode("utf-8")
        user_id_to_ga4gh_info[str(
            test_user.id)]["encoded_passport"] = encoded_passport

        userinfo_response["passport_jwt_v11"] = encoded_passport
        user_id_to_ga4gh_info[str(
            test_user.id)]["userinfo_response"] = userinfo_response

        add_refresh_token(db_session, test_user)

    for j in range(1, n_users_no_visas + 1):
        username = "******".format(j)
        test_user = add_test_ras_user(db_session,
                                      username,
                                      subject_id=username)

    query_visas = db_session.query(GA4GHVisaV1).all()

    assert len(query_visas) == n_users

    def _get_userinfo(*args, **kwargs):
        # b/c of the setup in _get_token_response_for_user we know the
        # access token will be the user.id
        return user_id_to_ga4gh_info.get(str(args[0].get("access_token", {})),
                                         {})["userinfo_response"]

    mock_userinfo.side_effect = _get_userinfo

    # test "fence-create update-visa"
    job = Visa_Token_Update()
    job.pkey_cache = {
        "https://stsstg.nih.gov": {
            kid: rsa_public_key,
        }
    }
    loop = asyncio.get_event_loop()
    loop.run_until_complete(job.update_tokens(db_session))

    query_visas = db_session.query(GA4GHVisaV1).all()

    # this should not disturb previous manually added visas
    # and should add a new visa per user (including users without existing visas)
    assert len(query_visas) == n_users * 2

    for visa in query_visas:
        assert (visa.ga4gh_visa == user_id_to_ga4gh_info[str(
            visa.user.id)]["encoded_visa"])
Ejemplo n.º 6
0
def test_update_visa_token_with_invalid_visa(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    rsa_public_key,
    kid,
    mock_arborist_requests,
    no_app_context_no_public_keys,
):
    """
    Test to check the following case:
    Received visa: [good1, bad2, good3]
    Processed/stored visa: [good1, good3]
    """
    mock_arborist_requests(
        {f"arborist/user/{TEST_RAS_USERNAME}": {
            "PATCH": (None, 204)
        }})

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": TEST_RAS_SUB,
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": TEST_RAS_USERNAME,
        "email": "",
    }

    test_user = add_test_ras_user(db_session)
    existing_encoded_visa, _ = add_visa_manually(db_session, test_user,
                                                 rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    new_visa = {
        "iss": "https://stsstg.nih.gov",
        "sub": TEST_RAS_SUB,
        "iat": int(time.time()),
        "exp": int(time.time()) + 1000,
        "scope": "openid ga4gh_passport_v1 email profile",
        "jti": "jtiajoidasndokmasdl",
        "txn": "sapidjspa.asipidja",
        "name": "",
        "ga4gh_visa_v1": {
            "type": "https://ras.nih.gov/visas/v1",
            "asserted": int(time.time()),
            "value": "https://stsstg.nih.gov/passport/dbgap/v1.1",
            "source": "https://ncbi.nlm.nih.gov/gap",
        },
    }

    headers = {"kid": kid}

    encoded_visa = jwt.encode(new_visa,
                              key=rsa_private_key,
                              headers=headers,
                              algorithm="RS256").decode("utf-8")

    passport_header = {
        "type": "JWT",
        "alg": "RS256",
        "kid": kid,
    }
    new_passport = {
        "iss": "https://stsstg.nih.gov",
        "sub": TEST_RAS_SUB,
        "iat": int(time.time()),
        "scope": "openid ga4gh_passport_v1 email profile",
        "exp": int(time.time()) + 1000,
    }
    new_passport["ga4gh_passport_v1"] = [encoded_visa, [], encoded_visa]

    encoded_passport = jwt.encode(new_passport,
                                  key=rsa_private_key,
                                  headers=passport_header,
                                  algorithm="RS256").decode("utf-8")
    userinfo_response["passport_jwt_v11"] = encoded_passport

    mock_userinfo.return_value = userinfo_response

    pkey_cache = {
        "https://stsstg.nih.gov": {
            kid: rsa_public_key,
        }
    }

    ras_client.update_user_authorization(
        test_user,
        pkey_cache=pkey_cache,
        db_session=db_session,
    )
    # at this point we expect the existing visa to stay around (since it hasn't expired)
    # and 2 new good visas
    query_visas = [
        item.ga4gh_visa
        for item in db_session.query(GA4GHVisaV1).filter_by(user=test_user)
    ]
    assert len(query_visas) == 3
    for query_visa in query_visas:
        assert query_visa == existing_encoded_visa or query_visa == encoded_visa
Ejemplo n.º 7
0
def test_update_visa_empty_visa_returned(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    kid,
    mock_arborist_requests,
):
    """
    Test to check if the db is emptied if the ras userinfo sends back an empty visa
    """
    mock_arborist_requests(
        {f"arborist/user/{TEST_RAS_USERNAME}": {
            "PATCH": (None, 204)
        }})

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": TEST_RAS_SUB,
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": TEST_RAS_USERNAME,
        "email": "",
    }

    passport_header = {
        "type": "JWT",
        "alg": "RS256",
        "kid": kid,
    }
    new_passport = {
        "iss": "https://stsstg.nih.gov",
        "sub": TEST_RAS_SUB,
        "iat": int(time.time()),
        "scope": "openid ga4gh_passport_v1 email profile",
        "exp": int(time.time()) + 1000,
        "ga4gh_passport_v1": [],
    }
    encoded_passport = jwt.encode(new_passport,
                                  key=rsa_private_key,
                                  headers=passport_header,
                                  algorithm="RS256").decode("utf-8")

    userinfo_response["passport_jwt_v11"] = encoded_passport
    mock_userinfo.return_value = userinfo_response

    test_user = add_test_ras_user(db_session)
    existing_encoded_visa, _ = add_visa_manually(db_session, test_user,
                                                 rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    ras_client.update_user_authorization(test_user,
                                         pkey_cache={},
                                         db_session=db_session)

    # at this point we expect the existing visa to stay around (since it hasn't expired)
    # but no new visas
    query_visas = [
        item.ga4gh_visa
        for item in db_session.query(GA4GHVisaV1).filter_by(user=test_user)
    ]
    assert len(query_visas) == 1
    assert existing_encoded_visa in query_visas
Ejemplo n.º 8
0
def test_update_visa_empty_passport_returned(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    rsa_public_key,
    kid,
    mock_arborist_requests,
):
    """
    Test to handle empty passport sent from RAS
    """
    mock_arborist_requests(
        {f"arborist/user/{TEST_RAS_USERNAME}": {
            "PATCH": (None, 204)
        }})

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": TEST_RAS_SUB,
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": TEST_RAS_USERNAME,
        "email": "",
        "passport_jwt_v11": "",
    }
    mock_userinfo.return_value = userinfo_response

    test_user = add_test_ras_user(db_session)
    existing_encoded_visa, _ = add_visa_manually(db_session, test_user,
                                                 rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    pkey_cache = {
        "https://stsstg.nih.gov": {
            kid: rsa_public_key,
        }
    }
    ras_client.update_user_authorization(
        test_user,
        pkey_cache=pkey_cache,
        db_session=db_session,
    )

    # at this point we expect the existing visa to stay around (since it hasn't expired)
    # but no new visas
    query_visas = [
        item.ga4gh_visa
        for item in db_session.query(GA4GHVisaV1).filter_by(user=test_user)
    ]
    assert len(query_visas) == 1
    assert existing_encoded_visa in query_visas
Ejemplo n.º 9
0
def test_update_visa_token(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    kid,
    kid_2,
):
    """
    Test to check visa table is updated when getting new visa
    """

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": "abcd-asdj-sajpiasj12iojd-asnoin",
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": "admin_user",
        "email": "",
    }

    test_user = add_test_user(db_session)
    add_visa_manually(db_session, test_user, rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    new_visa = {
        "iss": "https://stsstg.nih.gov",
        "sub": "abcde12345aspdij",
        "iat": int(time.time()),
        "exp": int(time.time()) + 1000,
        "scope": "openid ga4gh_passport_v1 email profile",
        "jti": "jtiajoidasndokmasdl",
        "txn": "sapidjspa.asipidja",
        "name": "",
        "ga4gh_visa_v1": {
            "type": "https://ras.nih.gov/visas/v1",
            "asserted": int(time.time()),
            "value": "https://nig/passport/dbgap",
            "source": "https://ncbi/gap",
        },
    }

    headers = {"kid": kid_2}

    encoded_visa = jwt.encode(new_visa,
                              key=rsa_private_key,
                              headers=headers,
                              algorithm="RS256").decode("utf-8")

    userinfo_response["ga4gh_passport_v1"] = [encoded_visa]
    mock_userinfo.return_value = userinfo_response

    ras_client.update_user_visas(test_user)

    query_visa = db_session.query(GA4GHVisaV1).first()
    assert query_visa.ga4gh_visa
    assert query_visa.ga4gh_visa == encoded_visa
Ejemplo n.º 10
0
def test_visa_update_cronjob(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    db_session,
    rsa_private_key,
    kid,
    kid_2,
):
    """
    Test to check visa table is updated when updating visas using cronjob
    """

    n_users = 20
    n_users_no_visa = 15

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": "abcd-asdj-sajpiasj12iojd-asnoin",
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": "admin_user",
        "email": "",
    }

    for i in range(n_users):
        username = "******".format(i)
        test_user = add_test_user(db_session, username, i)
        add_visa_manually(db_session, test_user, rsa_private_key, kid)
        add_refresh_token(db_session, test_user)
    for j in range(n_users_no_visa):
        username = "******".format(j)
        test_user = add_test_user(db_session, username, j + n_users)

    query_visas = db_session.query(GA4GHVisaV1).all()

    assert len(query_visas) == n_users

    new_visa = {
        "iss": "https://stsstg.nih.gov",
        "sub": "abcde12345aspdij",
        "iat": int(time.time()),
        "exp": int(time.time()) + 1000,
        "scope": "openid ga4gh_passport_v1 email profile",
        "jti": "jtiajoidasndokmasdl",
        "txn": "sapidjspa.asipidja",
        "name": "",
        "ga4gh_visa_v1": {
            "type": "https://ras.nih.gov/visas/v1",
            "asserted": int(time.time()),
            "value": "https://nig/passport/dbgap",
            "source": "https://ncbi/gap",
        },
    }

    headers = {"kid": kid_2}

    encoded_visa = jwt.encode(new_visa,
                              key=rsa_private_key,
                              headers=headers,
                              algorithm="RS256").decode("utf-8")

    userinfo_response["ga4gh_passport_v1"] = [encoded_visa]
    mock_userinfo.return_value = userinfo_response

    # test "fence-create update-visa"
    job = Visa_Token_Update()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(job.update_tokens(db_session))

    query_visas = db_session.query(GA4GHVisaV1).all()

    assert len(query_visas) == n_users

    for visa in query_visas:
        assert visa.ga4gh_visa == encoded_visa
Ejemplo n.º 11
0
def test_update_visa_token_with_invalid_visa(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    rsa_public_key,
    kid,
):
    """
    Test to check the following case:
    Received visa: [good1, bad2, good3]
    Processed/stored visa: [good1, good3]
    """

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": "abcd-asdj-sajpiasj12iojd-asnoin",
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": "admin_user",
        "email": "",
    }

    test_user = add_test_user(db_session)
    add_visa_manually(db_session, test_user, rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    new_visa = {
        "iss": "https://stsstg.nih.gov",
        "sub": "abcde12345aspdij",
        "iat": int(time.time()),
        "exp": int(time.time()) + 1000,
        "scope": "openid ga4gh_passport_v1 email profile",
        "jti": "jtiajoidasndokmasdl",
        "txn": "sapidjspa.asipidja",
        "name": "",
        "ga4gh_visa_v1": {
            "type": "https://ras.nih.gov/visas/v1",
            "asserted": int(time.time()),
            "value": "https://nig/passport/dbgap",
            "source": "https://ncbi/gap",
        },
    }

    headers = {"kid": kid}

    encoded_visa = jwt.encode(new_visa,
                              key=rsa_private_key,
                              headers=headers,
                              algorithm="RS256").decode("utf-8")

    passport_header = {
        "type": "JWT",
        "alg": "RS256",
        "kid": kid,
    }
    new_passport = {
        "iss": "https://stsstg.nih.gov",
        "sub": "abcde12345aspdij",
        "iat": int(time.time()),
        "scope": "openid ga4gh_passport_v1 email profile",
        "exp": int(time.time()) + 1000,
    }
    new_passport["ga4gh_passport_v1"] = [encoded_visa, [], encoded_visa]

    encoded_passport = jwt.encode(new_passport,
                                  key=rsa_private_key,
                                  headers=passport_header,
                                  algorithm="RS256").decode("utf-8")
    userinfo_response["passport_jwt_v11"] = encoded_passport

    mock_userinfo.return_value = userinfo_response

    pkey_cache = {
        "https://stsstg.nih.gov": {
            kid: rsa_public_key,
        }
    }
    ras_client.update_user_visas(test_user, pkey_cache=pkey_cache)

    query_visas = db_session.query(GA4GHVisaV1).filter_by(user=test_user).all()
    assert len(query_visas) == 2
    for query_visa in query_visas:
        assert query_visa.ga4gh_visa
        assert query_visa.ga4gh_visa == encoded_visa
Ejemplo n.º 12
0
def test_update_visa_empty_visa_returned(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    config,
    db_session,
    rsa_private_key,
    kid,
):
    """
    Test to check if the db is emptied if the ras userinfo sends back an empty visa
    """

    mock_discovery.return_value = "https://ras/token_endpoint"
    new_token = "refresh12345abcdefg"
    token_response = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": new_token,
    }
    mock_get_token.return_value = token_response

    userinfo_response = {
        "sub": "abcd-asdj-sajpiasj12iojd-asnoin",
        "name": "",
        "preferred_username": "******",
        "UID": "",
        "UserID": "admin_user",
        "email": "",
    }

    passport_header = {
        "type": "JWT",
        "alg": "RS256",
        "kid": kid,
    }
    new_passport = {
        "iss": "https://stsstg.nih.gov",
        "sub": "abcde12345aspdij",
        "iat": int(time.time()),
        "scope": "openid ga4gh_passport_v1 email profile",
        "exp": int(time.time()) + 1000,
        "ga4gh_passport_v1": [],
    }
    encoded_passport = jwt.encode(new_passport,
                                  key=rsa_private_key,
                                  headers=passport_header,
                                  algorithm="RS256").decode("utf-8")

    userinfo_response["passport_jwt_v11"] = encoded_passport
    mock_userinfo.return_value = userinfo_response

    test_user = add_test_user(db_session)
    add_visa_manually(db_session, test_user, rsa_private_key, kid)
    add_refresh_token(db_session, test_user)

    visa_query = db_session.query(GA4GHVisaV1).filter_by(
        user=test_user).first()
    initial_visa = visa_query.ga4gh_visa
    assert initial_visa

    oidc = config.get("OPENID_CONNECT", {})
    ras_client = RASClient(
        oidc["ras"],
        HTTP_PROXY=config.get("HTTP_PROXY"),
        logger=logger,
    )

    ras_client.update_user_visas(test_user, pkey_cache={})

    query_visa = db_session.query(GA4GHVisaV1).first()
    assert query_visa == None