Beispiel #1
0
class TestProvider(object):
    @pytest.fixture(autouse=True)
    def create_provider(self):
        kb = KeyBundle(JWKS["keys"])
        kj = KeyJar()
        kj.issuer_keys[''] = [kb]

        _sdb = SessionDB(
            "https://example.com/",
            db={},
            code_factory=DefaultToken('supersecret', 'verybadpassword',
                                      typ='A', lifetime=600),
            token_factory=JWTToken('T', keyjar=kj,
                                   lt_pattern={'code': 3600, 'token': 900},
                                   iss='https://example.com/as',
                                   sign_alg='RS256'),
            refresh_token_factory=JWTToken(
                'R', keyjar=kj, lt_pattern={'': 24 * 3600},
                iss='https://example.com/as')
        )
        #  name, sdb, cdb, authn_broker, authz, client_authn,
        self.provider = Provider("as", _sdb, CDB, AUTHN_BROKER, AUTHZ,
                                 verify_client,
                                 baseurl='https://example.com/as')

    def test_authorization_endpoint_faulty_redirect_uri(self):
        bib = {"state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
               # faulty redirect uri
               "redirect_uri": "http://localhost:8087/cb",
               "response_type": ["code"],
               "client_id": "a1b2c3"}

        arq = AuthorizationRequest(**bib)
        resp = self.provider.authorization_endpoint(request=arq.to_urlencoded())
        assert resp.status == "400 Bad Request"
        msg = json.loads(resp.message)
        assert msg["error"] == "invalid_request"

    def test_authenticated(self):
        client = Client(**CLIENT_CONFIG)
        client.authorization_endpoint = 'https://example.com/as'

        sid = rndstr(8)
        args = {
            'redirect_uri': "http://localhost:8087/authz",
            "state": sid, "response_type": 'code'}

        url, body, ht_args, csi = client.request_info(
            AuthorizationRequest, 'GET', request_args=args)

        resp = self.provider.authorization_endpoint(urlparse(url).query)
        assert resp.status == "303 See Other"
        resp = urlparse(resp.message).query
        aresp = client.parse_authz_response(resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ['state', 'code', 'client_id', 'iss'])
        assert _eq(client.grant[sid].keys(), ['tokens', 'code', 'exp_in',
                                              'seed', 'id_token',
                                              'grant_expiration_time'])

    def test_authenticated_token(self):
        client = Client(**CLIENT_CONFIG)
        client.authorization_endpoint = 'https://example.com/as'

        sid = rndstr(8)
        args = {'redirect_uri': "http://localhost:8087/authz", "state": sid,
                "response_type": 'token'}

        url, body, ht_args, csi = client.request_info(AuthorizationRequest,
                                                      'GET', request_args=args)

        QUERY_STRING = url.split("?")[1]
        resp = self.provider.authorization_endpoint(QUERY_STRING)
        auth_resp = parse_qs(urlparse(resp.message).fragment)

        assert "access_token" in auth_resp
        assert auth_resp["token_type"][0] == "Bearer"

    def test_token_endpoint(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ['access_token', 'token_type'])

    def test_token_endpoint_no_cache(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        assert resp.headers == [('Pragma', 'no-cache'), ('Cache-Control', 'no-store'),
                                ('Content-type', 'application/json')]

    def test_token_endpoint_unauth(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1",
                                       response_type='code')

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client2",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ['error_description', 'error'])

    def test_token_introspection(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        req = TokenIntrospectionRequest(token=atr['access_token'],
                                        client_id="client1",
                                        client_secret="hemlighet",
                                        token_type_hint='access_token')
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, 'json')
        assert ti_resp['active'] is True

    def test_token_revocation_and_introspection(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")

        req = TokenRevocationRequest(token=atr['access_token'],
                                     client_id="client1",
                                     client_secret="hemlighet",
                                     token_type_hint='access_token')
        resp = self.provider.revocation_endpoint(request=req.to_urlencoded())
        assert resp.status == '200 OK'

        req = TokenIntrospectionRequest(token=atr['access_token'],
                                        client_id="client1",
                                        client_secret="hemlighet",
                                        token_type_hint='access_token')
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, 'json')
        assert ti_resp['active'] is False
Beispiel #2
0
class TestProvider(object):
    @pytest.fixture(autouse=True)
    def create_provider(self):
        kb = KeyBundle(JWKS["keys"])
        kj = KeyJar()
        kj.issuer_keys[''] = [kb]

        _sdb = SessionDB(
            "https://example.com/",
            token_factory=JWTToken('T', keyjar=kj,
                                   lt_pattern={'code': 3600, 'token': 900},
                                   iss='https://example.com/as',
                                   sign_alg='RS256'),
            refresh_token_factory=JWTToken(
                'R', keyjar=kj, lt_pattern={'': 24 * 3600},
                iss='https://example.com/as')
        )
        #  name, sdb, cdb, authn_broker, authz, client_authn,
        self.provider = Provider("as", _sdb, CDB, AUTHN_BROKER, AUTHZ,
                                 verify_client,
                                 baseurl='https://example.com/as')

    def test_authorization_endpoint_faulty_redirect_uri(self):
        bib = {"state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
               # faulty redirect uri
               "redirect_uri": "http://localhost:8087/cb",
               "response_type": ["code"],
               "client_id": "a1b2c3"}

        arq = AuthorizationRequest(**bib)
        resp = self.provider.authorization_endpoint(request=arq.to_urlencoded())
        assert resp.status == "400 Bad Request"
        msg = json.loads(resp.message)
        assert msg["error"] == "invalid_request"

    def test_authenticated(self):
        client = Client(**CLIENT_CONFIG)
        client.authorization_endpoint = 'https://example.com/as'

        sid = rndstr(8)
        args = {
            'redirect_uri': "http://localhost:8087/authz",
            "state": sid, "response_type": 'code'}

        url, body, ht_args, csi = client.request_info(
            AuthorizationRequest, 'GET', request_args=args)

        resp = self.provider.authorization_endpoint(urlparse(url).query)
        assert resp.status == "303 See Other"
        resp = urlparse(resp.message).query
        aresp = client.parse_authz_response(resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ['state', 'code', 'client_id', 'iss'])
        assert _eq(client.grant[sid].keys(), ['tokens', 'code', 'exp_in',
                                              'seed', 'id_token',
                                              'grant_expiration_time'])

    def test_authenticated_token(self):
        client = Client(**CLIENT_CONFIG)
        client.authorization_endpoint = 'https://example.com/as'

        sid = rndstr(8)
        args = {'redirect_uri': "http://localhost:8087/authz", "state": sid,
                "response_type": 'token'}

        url, body, ht_args, csi = client.request_info(AuthorizationRequest,
                                                      'GET', request_args=args)

        QUERY_STRING = url.split("?")[1]
        resp = self.provider.authorization_endpoint(QUERY_STRING)
        auth_resp = parse_qs(urlparse(resp.message).fragment)

        assert "access_token" in auth_resp
        assert auth_resp["token_type"][0] == "Bearer"

    def test_token_endpoint(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ['access_token', 'token_type'])

    def test_token_endpoint_unauth(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1",
                                       response_type='code')

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client2",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ['error_description', 'error'])

    def test_token_introspection(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        req = TokenIntrospectionRequest(token=atr['access_token'],
                                        client_id="client1",
                                        client_secret="hemlighet",
                                        token_type_hint='access_token')
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, 'json')
        assert ti_resp['active'] is True

    def test_token_revocation_and_introspection(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")

        req = TokenRevocationRequest(token=atr['access_token'],
                                     client_id="client1",
                                     client_secret="hemlighet",
                                     token_type_hint='access_token')
        resp = self.provider.revocation_endpoint(request=req.to_urlencoded())
        assert resp.status == '200 OK'

        req = TokenIntrospectionRequest(token=atr['access_token'],
                                        client_id="client1",
                                        client_secret="hemlighet",
                                        token_type_hint='access_token')
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, 'json')
        assert ti_resp['active'] is False
Beispiel #3
0
class TestProvider(object):
    @pytest.fixture(autouse=True)
    def create_provider(self):
        kb = KeyBundle(JWKS["keys"])
        kj = KeyJar()
        kj.issuer_keys[""] = [kb]

        _sdb = SessionDB(
            "https://example.com/",
            db={},
            code_factory=DefaultToken(
                "supersecret", "verybadpassword", typ="A", lifetime=600
            ),
            token_factory=JWTToken(
                "T",
                keyjar=kj,
                lt_pattern={"code": 3600, "token": 900},
                iss="https://example.com/as",
                sign_alg="RS256",
            ),
            refresh_token_factory=JWTToken(
                "R",
                keyjar=kj,
                lt_pattern={"": 24 * 3600},
                iss="https://example.com/as",
                token_storage={},
            ),
        )
        #  name, sdb, cdb, authn_broker, authz, client_authn,
        self.provider = Provider(
            "as",
            _sdb,
            CDB,
            AUTHN_BROKER,
            AUTHZ,
            verify_client,
            baseurl="https://example.com/as",
        )

    def test_authorization_endpoint_faulty_redirect_uri(self):
        bib = {
            "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
            # faulty redirect uri
            "redirect_uri": "http://localhost:8087/cb",
            "response_type": ["code"],
            "client_id": "a1b2c3",
        }

        arq = AuthorizationRequest(**bib)
        resp = self.provider.authorization_endpoint(request=arq.to_urlencoded())
        assert resp.status_code == 400
        msg = json.loads(resp.message)
        assert msg["error"] == "invalid_request"

    def test_authenticated(self):
        client = Client(**CLIENT_CONFIG)
        client.authorization_endpoint = "https://example.com/as"

        sid = rndstr(8)
        args = {
            "redirect_uri": "http://localhost:8087/authz",
            "state": sid,
            "response_type": "code",
        }

        url, body, ht_args, csi = client.request_info(
            AuthorizationRequest, "GET", request_args=args
        )

        resp = self.provider.authorization_endpoint(urlparse(url).query)
        assert resp.status_code == 303
        resp = urlparse(resp.message).query
        aresp = client.parse_authz_response(resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ["state", "code", "client_id", "iss"])
        assert _eq(
            client.grant[sid].keys(),
            ["tokens", "code", "exp_in", "seed", "id_token", "grant_expiration_time"],
        )

    def test_authenticated_token(self):
        client = Client(**CLIENT_CONFIG)
        client.authorization_endpoint = "https://example.com/as"

        sid = rndstr(8)
        args = {
            "redirect_uri": "http://localhost:8087/authz",
            "state": sid,
            "response_type": "token",
        }

        url, body, ht_args, csi = client.request_info(
            AuthorizationRequest, "GET", request_args=args
        )

        QUERY_STRING = url.split("?")[1]
        resp = self.provider.authorization_endpoint(QUERY_STRING)
        auth_resp = parse_qs(urlparse(resp.message).fragment)

        assert "access_token" in auth_resp
        assert auth_resp["token_type"][0] == "Bearer"

    def test_token_endpoint(self):
        authreq = AuthorizationRequest(
            state="state", redirect_uri="http://example.com/authz", client_id="client1"
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client1",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ["access_token", "token_type"])

    def test_token_endpoint_no_cache(self):
        authreq = AuthorizationRequest(
            state="state", redirect_uri="http://example.com/authz", client_id="client1"
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client1",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        assert resp.headers == [
            ("Pragma", "no-cache"),
            ("Cache-Control", "no-store"),
            ("Content-type", "application/json"),
        ]

    def test_token_endpoint_unauth(self):
        authreq = AuthorizationRequest(
            state="state",
            redirect_uri="http://example.com/authz",
            client_id="client1",
            response_type="code",
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client2",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ["error_description", "error"])

    def test_token_introspection(self):
        authreq = AuthorizationRequest(
            state="state", redirect_uri="http://example.com/authz", client_id="client1"
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client1",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        req = TokenIntrospectionRequest(
            token=atr["access_token"],
            client_id="client1",
            client_secret="hemlighet",
            token_type_hint="access_token",
        )
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, "json")
        assert ti_resp["active"] is True

    def test_token_introspection_bad_access_token(self):
        req = TokenIntrospectionRequest(
            token="access_token",
            client_id="client1",
            client_secret="hemlighet",
            token_type_hint="access_token",
        )
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, "json")
        assert ti_resp["active"] is False

    def test_token_introspection_bad_token_no_hint(self):
        req = TokenIntrospectionRequest(
            token="access_token", client_id="client1", client_secret="hemlighet"
        )
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, "json")
        assert ti_resp["active"] is False

    def test_token_introspection_missing(self):
        authreq = AuthorizationRequest(
            state="state", redirect_uri="http://example.com/authz", client_id="client2"
        )

        _sdb = self.provider.sdb
        self.provider.cdb["client2"] = {
            "client_secret": "hemlighet",
            "redirect_uris": [("http://localhost:8087/authz", None)],
            "token_endpoint_auth_method": "client_secret_post",
            "response_types": ["code", "token"],
        }
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client2",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client2",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        # Delete the client
        del self.provider.cdb["client2"]
        req = TokenIntrospectionRequest(
            token=atr["access_token"],
            client_id="client2",
            client_secret="hemlighet",
            token_type_hint="access_token",
        )
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, "json")
        assert ti_resp["error"] == "unauthorized_client"

    def test_token_revocation_and_introspection(self):
        authreq = AuthorizationRequest(
            state="state", redirect_uri="http://example.com/authz", client_id="client1"
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client1",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")

        req = TokenRevocationRequest(
            token=atr["access_token"],
            client_id="client1",
            client_secret="hemlighet",
            token_type_hint="access_token",
        )
        resp = self.provider.revocation_endpoint(request=req.to_urlencoded())
        assert resp.status_code == 200

        req2 = TokenIntrospectionRequest(
            token=atr["access_token"],
            client_id="client1",
            client_secret="hemlighet",
            token_type_hint="access_token",
        )
        resp = self.provider.introspection_endpoint(request=req2.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, "json")
        assert ti_resp["active"] is False

    def test_password_grant_type_ok(self):
        # Set a not so dummy Authn method and token policy
        self.provider.authn_broker = AUTHN_BROKER2
        self.provider.set_token_policy("client1", {"grant_type": ["password"]})
        areq = ROPCAccessTokenRequest(
            grant_type="password", username="******", password="******"
        )
        areq[
            "client_id"
        ] = "client1"  # Token endpoint would fill that in based on client_authn
        resp = self.provider.password_grant_type(areq)

        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ["access_token", "token_type", "refresh_token"])

    def test_password_grant_type_no_authn(self):
        # Set a blank AuthnBroker
        self.provider.authn_broker = AuthnBroker()
        self.provider.set_token_policy("client1", {"grant_type": ["password"]})
        areq = ROPCAccessTokenRequest(
            grant_type="password", username="******", password="******"
        )
        areq[
            "client_id"
        ] = "client1"  # Token endpoint would fill that in based on client_authn
        resp = self.provider.password_grant_type(areq)

        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr["error"] == "invalid_grant"

    def test_password_grant_type_bad(self):
        # Set a not so dummy Authn method and token policy
        self.provider.authn_broker = AUTHN_BROKER2
        self.provider.set_token_policy("client1", {"grant_type": ["password"]})
        areq = ROPCAccessTokenRequest(
            grant_type="password", username="******", password="******"
        )
        areq[
            "client_id"
        ] = "client1"  # Token endpoint would fill that in based on client_authn
        resp = self.provider.password_grant_type(areq)

        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr["error"] == "invalid_grant"