Beispiel #1
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
Beispiel #2
0
def test_update_visa_fetch_pkey(
    mock_discovery,
    mock_get_token,
    mock_userinfo,
    mock_httpx_get,
    db_session,
    rsa_private_key,
    kid,
    mock_arborist_requests,
):
    """
    Test that when the RAS client's pkey cache is empty, the client's
    update_user_authorization can fetch and serialize the visa issuer's public keys and
    validate a visa using the correct key.
    """
    # 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"
    mock_get_token.return_value = {
        "access_token": "abcdef12345",
        "id_token": "id12345abcdef",
        "refresh_token": "refresh12345abcdefg",
    }
    # New visa that will be returned by userinfo
    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,
        "ga4gh_passport_v1": [encoded_visa],
    }

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

    mock_userinfo.return_value = {
        "passport_jwt_v11": encoded_passport,
    }

    # Mock the call to the jwks endpoint so it returns the test app's keypairs,
    # one of which is rsa_private_key (and its corresponding public key), which
    # we just used to sign new_visa.
    keys = [
        keypair.public_key_to_jwk() for keypair in flask.current_app.keypairs
    ]
    mock_httpx_get.return_value = httpx.Response(200, json={"keys": keys})

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

    # Pass in an empty pkey cache so that the client will have to hit the jwks endpoint.
    ras_client.update_user_authorization(test_user,
                                         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

    # Check that the new visa passed validation, indicating a successful pkey fetch
    query_visas = [
        item.ga4gh_visa
        for item in db_session.query(GA4GHVisaV1).filter_by(user=test_user)
    ]
    for visa in query_visas:
        assert visa == encoded_visa
Beispiel #3
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
Beispiel #4
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
Beispiel #5
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