Ejemplo n.º 1
0
    def test_do_user_info_request(self):
        resp = AuthorizationResponse(code="code", state="state")
        grant = Grant(10)  # expired grant
        grant.add_code(resp)
        resp2 = AccessTokenResponse(
            refresh_token="refresh_with_me", access_token="access", token_type="Bearer"
        )
        token = Token(resp2)
        grant.tokens.append(token)
        self.client.grant["state0"] = grant
        with responses.RequestsMock() as rsps:
            rsps.add(
                responses.POST,
                "https://example.com/userinfo",
                content_type="application/json",
                json={
                    "name": "Melody Gardot",
                    "email": "*****@*****.**",
                    "verified": False,
                    "nickname": "Melody",
                    "sub": "some sub",
                },
            )

            resp3 = self.client.do_user_info_request(state="state0")
        assert isinstance(resp3, OpenIDSchema)
        assert _eq(resp3.keys(), ["name", "email", "verified", "nickname", "sub"])
        assert resp3["name"] == "Melody Gardot"
Ejemplo n.º 2
0
def test_get_access_token_request():
    resp = AuthorizationResponse(code="code", state="state")

    grant = Grant(1)
    grant.add_code(resp)

    client = Client()
    client.grant["openid"] = grant
    time.sleep(2)
    raises(GrantExpired, 'client.construct_AccessTokenRequest(state="openid")')
Ejemplo n.º 3
0
def test_get_access_token_request():
    resp = AuthorizationResponse(code="code", state="state")

    grant = Grant(1)
    grant.add_code(resp)

    client = Client()
    client.grant["openid"] = grant
    time.sleep(2)
    raises(GrantExpired, 'client.construct_AccessTokenRequest(state="openid")')
Ejemplo n.º 4
0
def test_client_get_grant():
    cli = Client()

    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    cli.grant["state"] = grant

    gr1 = cli.grant_from_state("state")

    assert gr1.code == "code"
Ejemplo n.º 5
0
def test_client_get_grant():
    cli = Client()

    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    cli.grant["state"] = grant

    gr1 = cli.grant_from_state("state")

    assert gr1.code == "code"
Ejemplo n.º 6
0
    def test_get_access_token_request_override(self):
        self.client.reset()
        self.client.redirect_uris = ["http://client.example.com/authz"]
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.utc_time_sans_frac() + 30
        self.client.grant = {"xyz": grant}

        atr = self.client.construct_AccessTokenRequest(state="xyz")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == "http://client.example.com/authz"
Ejemplo n.º 7
0
    def test_get_access_token_request_override(self):
        self.client.reset()
        self.client.redirect_uris = ["http://client.example.com/authz"]
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.utc_time_sans_frac() + 30
        self.client.grant = {"xyz": grant}

        atr = self.client.construct_AccessTokenRequest(state="xyz")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == "http://client.example.com/authz"
Ejemplo n.º 8
0
    def test_do_user_info_request(self):
        resp = AuthorizationResponse(code="code", state="state")
        grant = Grant(10)  # expired grant
        grant.add_code(resp)
        resp2 = AccessTokenResponse(
            refresh_token="refresh_with_me", access_token="access", token_type="Bearer"
        )
        token = Token(resp2)
        grant.tokens.append(token)
        self.client.grant["state0"] = grant

        resp3 = self.client.do_user_info_request(state="state0")
        assert isinstance(resp3, OpenIDSchema)
        assert _eq(resp3.keys(), ["name", "email", "verified", "nickname", "sub"])
        assert resp3["name"] == "Melody Gardot"
Ejemplo n.º 9
0
    def test_do_user_info_request(self):
        resp = AuthorizationResponse(code="code", state="state")
        grant = Grant(10)  # expired grant
        grant.add_code(resp)
        resp = AccessTokenResponse(refresh_token="refresh_with_me",
                                   access_token="access")
        token = Token(resp)
        grant.tokens.append(token)
        self.client.grant["state0"] = grant

        resp = self.client.do_user_info_request(state="state0")
        assert isinstance(resp, OpenIDSchema)
        assert _eq(resp.keys(),
                   ['name', 'email', 'verified', 'nickname', 'sub'])
        assert resp["name"] == "Melody Gardot"
Ejemplo n.º 10
0
    def refresh_access_token(self, credential):
        """
        Request new access token
        :param credential: Credential from DB containing an access token and a refresh token
        :return: Updated credential containing new access token
        """
        access_token, refresh_token = credential.proxy.split(':')
        unverified_payload = jwt.decode(access_token, verify=False)
        issuer = unverified_payload['iss']
        client = self.clients[issuer]
        log.debug('refresh_access_token for {}'.format(issuer))

        # Prepare and make request
        refresh_session_state = rndstr(50)
        client.grant[refresh_session_state] = Grant()
        client.grant[
            refresh_session_state].grant_expiration_time = time_util.utc_time_sans_frac(
            ) + 60
        resp = AccessTokenResponse()
        resp["refresh_token"] = refresh_token
        client.grant[refresh_session_state].tokens.append(Token(resp))
        new_credential = client.do_access_token_refresh(
            authn_method="client_secret_basic", state=refresh_session_state)
        # A new refresh token is optional
        refresh_token = new_credential.get('refresh_token', refresh_token)
        access_token = new_credential.get('access_token')
        unverified_payload = jwt.decode(access_token, verify=False)
        expiration_time = unverified_payload['exp']
        credential.proxy = new_credential['access_token'] + ':' + refresh_token
        credential.termination_time = datetime.utcfromtimestamp(
            expiration_time)

        return credential
Ejemplo n.º 11
0
    def test_construct_EndSessionRequest_kwargs_and_reqargs_state(self):
        self.client.grant["foo"] = Grant()
        self.client.grant["foo"].grant_expiration_time = int(time.time()) + 60
        self.client.grant["foo"].code = "access_code"

        # Need a proper ID Token
        self.client.keyjar.add_kb(IDTOKEN["iss"], KC_SYM_S)
        _sig_key = self.client.keyjar.get_signing_key("oct", IDTOKEN["iss"])
        _signed_jwt = IDTOKEN.to_jwt(_sig_key, algorithm="HS256")

        resp = AccessTokenResponse(
            id_token=_signed_jwt,
            access_token="access",
            scope=["openid"],
            token_type="bearer",
        )

        assert resp.verify(keyjar=self.client.keyjar)

        self.client.grant["foo"].tokens.append(Token(resp))

        # state both in request_args and kwargs
        args = {"redirect_url": "http://example.com/end", "state": "req_args_state"}
        esr = self.client.construct_EndSessionRequest(state="foo", request_args=args)
        assert _eq(esr.keys(), ["id_token", "state", "redirect_url"])
        assert esr["state"] == "req_args_state"
Ejemplo n.º 12
0
    def test_token_request(self, request_func, expected_token_request):
        token_endpoint = self.PROVIDER_BASEURL + '/token'
        now = int(time.time())
        id_token_claims = {
            'iss': self.PROVIDER_METADATA['issuer'],
            'sub': 'test_user',
            'aud': [self.CLIENT_METADATA['client_id']],
            'exp': now + 1,
            'iat': now,
            'nonce': 'test_nonce'
        }
        id_token_jwt, id_token_signing_key = signed_id_token(id_token_claims)
        token_response = AccessTokenResponse(access_token='test_access_token',
                                             refresh_token='refresh-token',
                                             token_type='Bearer',
                                             id_token=id_token_jwt,
                                             expires_in=now + 1)

        responses.add(responses.POST,
                      token_endpoint,
                      json=token_response.to_dict())

        provider_metadata = self.PROVIDER_METADATA.copy(
            token_endpoint=token_endpoint)
        facade = PyoidcFacade(
            ProviderConfiguration(provider_metadata=provider_metadata,
                                  client_metadata=self.CLIENT_METADATA),
            REDIRECT_URI)
        grant = Grant(resp=token_response)
        grant.grant_expiration_time = now + grant.exp_in
        facade._client.grant = {'test-state': grant}

        responses.add(responses.GET,
                      self.PROVIDER_METADATA['jwks_uri'],
                      json={'keys': [id_token_signing_key.serialize()]})
        token_response = request_func(facade)

        assert isinstance(token_response, AccessTokenResponse)
        expected_token_response = token_response.to_dict()
        expected_token_response['id_token'] = id_token_claims
        expected_token_response['id_token_jwt'] = id_token_jwt
        assert token_response.to_dict() == expected_token_response

        token_request = dict(parse_qsl(responses.calls[0].request.body))
        assert token_request == expected_token_request
Ejemplo n.º 13
0
 def test_do_user_info_request_http_errors(self):
     resp = AuthorizationResponse(code="code", state="state")
     grant = Grant(10)  # expired grant
     grant.add_code(resp)
     resp2 = AccessTokenResponse(
         refresh_token="refresh_with_me", access_token="access", token_type="Bearer"
     )
     token = Token(resp2)
     grant.tokens.append(token)
     self.client.grant["state0"] = grant
     with responses.RequestsMock() as rsps:
         rsps.add(
             responses.POST,
             "https://example.com/userinfo",
             status=405,
             headers={"Allow": "GET"},
         )
         with pytest.raises(CommunicationError) as excp:
             self.client.do_user_info_request(state="state0")
         assert excp.value.args[0] == "Server responded with HTTP Error Code 405"
         assert excp.value.args[1] == ["GET"]
Ejemplo n.º 14
0
    def test_token_request_handles_error_response(self):
        token_endpoint = self.PROVIDER_BASEURL + '/token'
        token_response = TokenErrorResponse(
            error='invalid_request',
            error_description='test error description')
        responses.add(responses.POST,
                      token_endpoint,
                      json=token_response.to_dict(),
                      status=400)

        provider_metadata = self.PROVIDER_METADATA.copy(
            token_endpoint=token_endpoint)
        facade = PyoidcFacade(
            ProviderConfiguration(provider_metadata=provider_metadata,
                                  client_metadata=self.CLIENT_METADATA),
            REDIRECT_URI)
        state = 'test-state'
        grant = Grant()
        grant.grant_expiration_time = int(time.time()) + grant.exp_in
        facade._client.grant = {state: grant}
        assert facade.exchange_authorization_code('1234',
                                                  state) == token_response
Ejemplo n.º 15
0
    def test_construct_UserInfoRequest_2_with_token(self):
        self.client.grant["foo"] = Grant()
        self.client.grant["foo"].grant_expiration_time = time.time() + 60
        self.client.grant["foo"].code = "access_code"

        resp = AccessTokenResponse(refresh_token="refresh_with_me",
                                   access_token="access", id_token="IDTOKEN",
                                   scope=["openid"])

        self.client.grant["foo"].tokens.append(Token(resp))
        uir = self.client.construct_UserInfoRequest(state="foo",
                                                    scope=["openid"])
        assert uir["access_token"] == "access"
Ejemplo n.º 16
0
    def test_construct_CheckSessionRequest_2(self):
        self.client.grant["foo"] = Grant()
        self.client.grant["foo"].grant_expiration_time = time.time() + 60
        self.client.grant["foo"].code = "access_code"

        resp = AccessTokenResponse(
            id_token="id_id_id_id", access_token="access", scope=["openid"]
        )

        self.client.grant["foo"].tokens.append(Token(resp))

        csr = self.client.construct_CheckSessionRequest(state="foo", scope=["openid"])
        assert csr["id_token"] == "id_id_id_id"
Ejemplo n.º 17
0
    def test_clean_tokens_fresh(self):
        self.client.grant["foo"] = Grant()
        self.client.grant["foo"].grant_expiration_time = time.time() + 60
        self.client.grant["foo"].code = "access_code"

        resp = AccessTokenResponse(refresh_token="refresh_with_me",
                                   access_token="access",
                                   id_token="IDTOKEN",
                                   scope=["openid"])

        self.client.grant["foo"].tokens.append(Token(resp))
        self.client.clean_tokens()
        assert len(self.client.grant["foo"].tokens) == 1
Ejemplo n.º 18
0
    def test_construct_EndSessionRequest(self):
        self.client.grant["foo"] = Grant()
        self.client.grant["foo"].grant_expiration_time = time.time() + 60
        self.client.grant["foo"].code = "access_code"

        resp = AccessTokenResponse(
            id_token="id_id_id_id", access_token="access", scope=["openid"]
        )

        self.client.grant["foo"].tokens.append(Token(resp))

        args = {"redirect_url": "http://example.com/end"}
        esr = self.client.construct_EndSessionRequest(state="foo", request_args=args)
        assert _eq(esr.keys(), ["id_token", "state", "redirect_url"])
Ejemplo n.º 19
0
def test_construct_CheckSessionRequest_2():
    cli = Client()
    cli.userinfo_endpoint = "https://example.org/oauth2/userinfo"
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(id_token="id_id_id_id",
                               access_token="access", scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    uir = cli.construct_CheckSessionRequest(state="foo", scope=["openid"])
    print uir
    assert ("%s" % uir) == "{'id_token': 'id_id_id_id'}"
Ejemplo n.º 20
0
def test_construct_UserInfoRequest_2():
    cli = Client()
    cli.userinfo_endpoint = "https://example.org/oauth2/userinfo"
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(refresh_token="refresh_with_me",
                               access_token="access", id_token="IDTOKEN",
                               scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    uir = cli.construct_UserInfoRequest(state="foo", scope=["openid"])
    print uir
    assert uir.keys() == ["access_token"]
Ejemplo n.º 21
0
def test_construct_EndSessionRequest():
    cli = Client()
    cli.redirect_uris = ["http://example.com/authz"]
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(id_token="id_id_id_id",
                               access_token="access", scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    args = {"redirect_url": "http://example.com/end"}
    esr = cli.construct_EndSessionRequest(state="foo", request_args=args)
    print esr.keys()
    assert _eq(esr.keys(), ['id_token', 'state', "redirect_url"])
Ejemplo n.º 22
0
    def test_get_access_token_refresh_2(self):
        self.client.grant["foo"] = Grant()
        self.client.grant["foo"].grant_expiration_time = \
            utc_time_sans_frac() + 60
        self.client.grant["foo"].code = "access_code"

        print self.client.grant["foo"]
        resp = AccessTokenResponse()
        resp["refresh_token"] = "refresh_with_me"
        resp["access_token"] = "access"
        self.client.grant["foo"].tokens.append(Token(resp))
        # Uses refresh_token from previous response
        atr = self.client.construct_RefreshAccessTokenRequest(state="foo")

        assert atr.type() == "RefreshAccessTokenRequest"
        assert atr["grant_type"] == "refresh_token"
        assert atr["refresh_token"] == "refresh_with_me"
Ejemplo n.º 23
0
def test_do_userinfo_request_with_state():
    client = Client(CLIENT_ID, client_authn_method=CLIENT_AUTHN_METHOD)
    client.grant["foxhound"] = Grant()
    resp = AccessTokenResponse(access_token="access", token_type="Bearer")
    _token = Token(resp)
    client.grant["foxhound"].tokens = [_token]

    method = "GET"
    state = "foxhound"
    scope = "openid"
    request = "openid"
    kwargs = {"request": request, "userinfo_endpoint": "http://example.com/userinfo"}

    path, body, method, h_args = client.user_info_request(
        method, state, scope, **kwargs
    )

    assert path == "http://example.com/userinfo"
    assert h_args == {"headers": {"Authorization": "Bearer access"}}
    assert method == "GET"
    assert body is None
Ejemplo n.º 24
0
    def test_construct_CheckSessionRequest_2(self):
        self.client.grant["foo"] = Grant()
        self.client.grant["foo"].grant_expiration_time = int(time.time() + 60)
        self.client.grant["foo"].code = "access_code"

        # Need a proper ID Token
        self.client.keyjar.add_kb(IDTOKEN["iss"], KC_SYM_S)
        _sig_key = self.client.keyjar.get_signing_key("oct", IDTOKEN["iss"])
        _signed_jwt = IDTOKEN.to_jwt(_sig_key, algorithm="HS256")

        resp = AccessTokenResponse(
            id_token=_signed_jwt,
            access_token="access",
            scope=["openid"],
            token_type="bearer",
        )

        assert resp.verify(keyjar=self.client.keyjar)

        self.client.grant["foo"].tokens.append(Token(resp))

        csr = self.client.construct_CheckSessionRequest(state="foo", scope=["openid"])
        assert csr["id_token"] == _signed_jwt
Ejemplo n.º 25
0
def test_do_userinfo_request_with_state():
    """ Mirrors the first lines in do_userinfo_request"""
    client = Client(CLIENT_ID, client_authn_method=CLIENT_AUTHN_METHOD)
    client.grant['foxhound'] = Grant()
    resp = AccessTokenResponse(access_token="access", token_type="Bearer")
    _token = Token(resp)
    client.grant["foxhound"].tokens = [_token]

    method = "GET"
    state = "foxhound"
    scope = "openid"
    request = "openid"
    kwargs = {
        "request": request,
        "userinfo_endpoint": 'http://example.com/userinfo'
    }

    path, body, method, h_args = client.user_info_request(
        method, state, scope, **kwargs)

    assert path == 'http://example.com/userinfo'
    assert h_args == {'headers': {'Authorization': 'Bearer access'}}
    assert method == 'GET'
    assert body is None