Exemplo n.º 1
0
    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')
Exemplo n.º 2
0
    def test_pkce_verify_256(self, session_db_factory):
        _cli = Client(
            config={"code_challenge": {
                "method": "S256",
                "length": 64
            }})
        args, cv = _cli.add_code_challenge()

        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
        _prov = Provider(
            "as",
            session_db_factory("https://connect-op.heroku.com"),
            {},
            authn_broker,
            Implicit(),
            verify_client,
        )

        assert _prov.verify_code_challenge(cv, args["code_challenge"]) is True
        assert _prov.verify_code_challenge(cv, args["code_challenge"],
                                           "S256") is True
        resp = _prov.verify_code_challenge("XXX", args["code_challenge"])
        assert isinstance(resp, Response)
        assert resp.info()["status_code"] == 401
Exemplo n.º 3
0
    def __init__(self, name, sdb, cdb, authn_broker, authz,
                 client_authn, symkey, urlmap=None, keyjar=None,
                 hostname="", configuration=None, base_url="",
                 client_authn_methods=None, authn_at_registration="",
                 client_info_url="", secret_lifetime=86400,
                 default_acr=""):

        OAUTH2Provider.__init__(self, name, sdb, cdb, authn_broker, authz,
                                client_authn, symkey=symkey, urlmap=urlmap,
                                client_authn_methods=client_authn_methods,
                                authn_at_registration=authn_at_registration,
                                client_info_url=client_info_url,
                                secret_lifetime=secret_lifetime)
        UmaAS.__init__(self, configuration, baseurl=base_url)

        if keyjar:
            self.keyjar = keyjar
        else:
            self.keyjar = KeyJar()

        self.hostname = hostname or socket.gethostname
        self.jwks_uri = []
        self.endp = UmaAS.endp[:]
        self.endp.extend(OAUTH2Provider.endp)
        self.default_acr = default_acr
Exemplo n.º 4
0
def test_pkce_verify_512():
    _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider("as",
                     sdb.SessionDB(SERVER_INFO["issuer"]), CDB,
                     authn_broker, Implicit(), verify_client)

    assert _prov.verify_code_challenge(cv, args['code_challenge'],'S512') is True
Exemplo n.º 5
0
def test_pkce_verify_512():
    _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider("as", sdb.SessionDB(SERVER_INFO["issuer"]), CDB,
                     authn_broker, Implicit(), verify_client)

    assert _prov.verify_code_challenge(cv, args['code_challenge'],
                                       'S512') is True
Exemplo n.º 6
0
    def test_pkce_verify_512(self, session_db_factory):
        _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}})
        args, cv = _cli.add_code_challenge()

        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
        _prov = Provider("as",
                         session_db_factory('https://connect-op.heroku.com'), {},
                         authn_broker, Implicit(), verify_client)

        assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S512') is True
        resp = _prov.verify_code_challenge('XXX', args['code_challenge'])
        assert isinstance(resp, Response)
        assert resp.info()['status_code'] == 401
Exemplo n.º 7
0
    def test_pkce_verify_512(self, session_db_factory):
        _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}})
        args, cv = _cli.add_code_challenge()

        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
        _prov = Provider("as",
                         session_db_factory('https://connect-op.heroku.com'), {},
                         authn_broker, Implicit(), verify_client)

        assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S512') is True
        resp = _prov.verify_code_challenge('XXX', args['code_challenge'])
        assert isinstance(resp, Response)
        assert resp.info()['status_code'] == 401
Exemplo n.º 8
0
def test_pkce_verify_256(session_db_factory):
    _cli = Client(config={'code_challenge': {'method': 'S256', 'length': 64}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider("as",
                     session_db_factory(SERVER_INFO["issuer"]), CDB,
                     authn_broker, Implicit(), verify_client)

    assert _prov.verify_code_challenge(cv, args['code_challenge']) is True
    assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S256') is True
    resp = _prov.verify_code_challenge('XXX', args['code_challenge'])
    assert isinstance(resp, Response)
    assert resp.info()['status_code'] == 401
Exemplo n.º 9
0
def test_pkce_verify_256(session_db_factory):
    _cli = Client(config={'code_challenge': {'method': 'S256', 'length': 64}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider("as", session_db_factory(SERVER_INFO["issuer"]), CDB,
                     authn_broker, Implicit(), verify_client)

    assert _prov.verify_code_challenge(cv, args['code_challenge']) is True
    assert _prov.verify_code_challenge(cv, args['code_challenge'],
                                       'S256') is True
    resp = _prov.verify_code_challenge('XXX', args['code_challenge'])
    assert isinstance(resp, Response)
    assert resp.info()['status_code'] == 401
Exemplo n.º 10
0
    def create_provider(self, session_db_factory):
        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))

        self.provider = Provider("pyoicserv",
                                 session_db_factory(
                                     TestProvider.SERVER_INFO["issuer"]),
                                 TestProvider.CDB,
                                 authn_broker,
                                 Implicit(),
                                 verify_client,
                                 client_info_url="https://example.com/as",
                                 client_authn_methods={
                                     "client_secret_post": ClientSecretPost,
                                     "client_secret_basic": ClientSecretBasic,
                                     "bearer_header": BearerHeader
                                 })
Exemplo n.º 11
0
    def __init__(self,
                 name,
                 sdb,
                 cdb,
                 authn_broker,
                 authz,
                 client_authn,
                 symkey,
                 urlmap=None,
                 keyjar=None,
                 hostname="",
                 configuration=None,
                 base_url="",
                 client_authn_methods=None,
                 authn_at_registration="",
                 client_info_url="",
                 secret_lifetime=86400,
                 default_acr=""):

        OAUTH2Provider.__init__(self,
                                name,
                                sdb,
                                cdb,
                                authn_broker,
                                authz,
                                client_authn,
                                symkey=symkey,
                                urlmap=urlmap,
                                client_authn_methods=client_authn_methods,
                                authn_at_registration=authn_at_registration,
                                client_info_url=client_info_url,
                                secret_lifetime=secret_lifetime)
        UmaAS.__init__(self, configuration, baseurl=base_url)

        if keyjar:
            self.keyjar = keyjar
        else:
            self.keyjar = KeyJar()

        self.hostname = hostname or socket.gethostname
        self.jwks_uri = []
        self.endp = UmaAS.endp[:]
        self.endp.extend(OAUTH2Provider.endp)
        self.default_acr = default_acr
Exemplo n.º 12
0
def test_pkce_verify_512(session_db_factory):
    _cli = Client(config={"code_challenge": {"method": "S512", "length": 96}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider(
        "as",
        session_db_factory(SERVER_INFO["issuer"]),
        CDB,
        authn_broker,
        Implicit(),
        verify_client,
    )

    assert _prov.verify_code_challenge(cv, args["code_challenge"],
                                       "S512") is True
    resp = _prov.verify_code_challenge("XXX", args["code_challenge"])
    assert isinstance(resp, Response)
    assert resp.info()["status_code"] == 401
Exemplo n.º 13
0
    def create_provider(self):
        kb = KeyBundle(JWKS["keys"])
        kj = KeyJar()
        kj.issuer_keys[""] = [kb]

        _sdb = SessionDB(
            "https://example.com/",
            db=DictSessionBackend(),
            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",
        )
Exemplo n.º 14
0
    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, lifetime={"code": 3600, "token": 900}, iss="https://example.com/as", sign_alg="RS256"
            ),
            refresh_token_factory=JWTToken("R", keyjar=kj, lifetime={"": 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")
Exemplo n.º 15
0
    def create_provider(self):
        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))

        self.provider = Provider("pyoicserv",
                                 sdb.SessionDB(
                                     TestProvider.SERVER_INFO["issuer"]),
                                 TestProvider.CDB,
                                 authn_broker, Implicit(),
                                 verify_client,
                                 client_info_url="https://example.com/as",
                                 client_authn_methods={
                                     "client_secret_post": ClientSecretPost,
                                     "client_secret_basic": ClientSecretBasic,
                                     "bearer_header": BearerHeader})
Exemplo n.º 16
0
    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')
Exemplo n.º 17
0
class TestProvider(object):
    SERVER_INFO = {
        "version": "3.0",
        "issuer": "https://connect-op.heroku.com",
        "authorization_endpoint": "http://localhost:8088/authorization",
        "token_endpoint": "http://localhost:8088/token",
        "flows_supported": ["code", "token", "code token"],
    }

    CDB = {
        "a1b2c3": {
            "password": "******",
            "client_secret": "drickyoughurt"
        },
        "client1": {
            "client_secret": "hemlighet",
            "redirect_uris": [("http://localhost:8087/authz", None)]
        }
    }

    @pytest.fixture(autouse=True)
    def create_provider(self, session_db_factory):
        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))

        self.provider = Provider("pyoicserv",
                                 session_db_factory(
                                     TestProvider.SERVER_INFO["issuer"]),
                                 TestProvider.CDB,
                                 authn_broker,
                                 Implicit(),
                                 verify_client,
                                 client_info_url="https://example.com/as",
                                 client_authn_methods={
                                     "client_secret_post": ClientSecretPost,
                                     "client_secret_basic": ClientSecretBasic,
                                     "bearer_header": BearerHeader
                                 })

    def test_registration_endpoint(self):
        request = RegistrationRequest(
            client_name="myself",
            redirect_uris=["https://example.com/rp"],
            grant_type=['authorization_code', 'implicit'])
        resp = self.provider.registration_endpoint(request=request.to_json())
        assert isinstance(resp, Response)
        data = json.loads(resp.message)
        assert data["client_name"] == "myself"
        assert _eq(data["redirect_uris"], ["https://example.com/rp"])

        _resp = ClientInfoResponse().from_json(resp.message)
        assert "client_id" in _resp

    def test_registration_uri_error(self):
        args = {
            "redirect_uris": [
                "https://client.example.org/callback",
                "https://client.example.org/callback2"
            ],
            "client_name":
            "My Example Client",
            "client_name#ja-Jpan-JP":
            "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method":
            "client_secret_basic",
            "scope":
            "read write dolphin",
            # invalid logo_uri
            "logo_uri":
            "https://client.example.org/logo.png",
            "jwks_uri":
            "https://client.example.org/my_public_keys.jwks"
        }

        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json())
        _resp = ClientRegistrationError().from_json(resp.message)

        assert "error" in _resp
        assert _resp["error"] == "invalid_client_metadata"

    def test_client_registration_utf_8_client_name(self):
        args = {
            "redirect_uris": [
                "https://client.example.org/callback",
                "https://client.example.org/callback2"
            ],
            "client_name":
            "My Example Client",
            "client_name#ja-Jpan-JP":
            "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method":
            "client_secret_basic",
            "scope":
            "read write dolphin",
        }

        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json())
        _resp = ClientInfoResponse().from_json(resp.message)

        assert _resp[
            "client_name#ja-Jpan-JP"] == "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D"
        assert _resp["client_name"] == "My Example Client"

    def test_client_user_info_get(self):
        args = {
            "redirect_uris": [
                "https://client.example.org/callback",
                "https://client.example.org/callback2"
            ],
            "client_name":
            "My Example Client",
            "client_name#ja-Jpan-JP":
            "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method":
            "client_secret_basic",
            "scope":
            "read write dolphin",
        }
        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json())
        _resp = ClientInfoResponse().from_json(resp.message)

        resp = self.provider.client_info_endpoint(
            "GET",
            environ={
                "HTTP_AUTHORIZATION":
                "Bearer %s" % (_resp["registration_access_token"], )
            },
            query="client_id=%s" % _resp["client_id"],
            request=request.to_json())

        _resp_cir = ClientInfoResponse().from_json(resp.message)
        assert _resp == _resp_cir

    def test_client_registration_update(self):
        args = {
            "redirect_uris": [
                "https://client.example.org/callback",
                "https://client.example.org/callback2"
            ],
            "client_name":
            "My Example Client",
            "client_name#ja-Jpan-JP":
            "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method":
            "client_secret_basic",
            "scope":
            "read write dolphin",
        }
        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json(),
                                                   environ={})
        _resp = ClientInfoResponse().from_json(resp.message)

        update = {
            "client_id":
            _resp["client_id"],
            "client_secret":
            _resp["client_secret"],
            "redirect_uris": [
                "https://client.example.org/callback",
                "https://client.example.org/alt"
            ],
            "scope":
            "read write dolphin",
            "grant_types": ["authorization_code", "refresh_token"],
            "token_endpoint_auth_method":
            "client_secret_basic",
            "jwks_uri":
            "https://client.example.org/my_public_keys.jwks",
            "client_name":
            "My New Example",
            "client_name#fr":
            "Mon Nouvel Exemple",
        }
        update_req = RegistrationRequest(**update)
        resp = self.provider.client_info_endpoint(
            request=update_req.to_json(),
            environ={
                "HTTP_AUTHORIZATION":
                "Bearer %s" % (_resp["registration_access_token"], )
            },
            method="PUT",
            query="client_id=%s" % _resp["client_id"])

        _resp_up = ClientInfoResponse().from_json(resp.message)
        assert _resp_up["client_id"] == update["client_id"]
        assert _resp_up["client_secret"] == update["client_secret"]
        assert _resp_up["redirect_uris"] == update["redirect_uris"]
        assert _resp_up["scope"] == update["scope"].split()
        assert _resp_up["grant_types"] == update["grant_types"]
        assert _resp_up["token_endpoint_auth_method"] == update[
            "token_endpoint_auth_method"]
        assert _resp_up["jwks_uri"] == update["jwks_uri"]
        assert _resp_up["client_name"] == update["client_name"]
        assert _resp_up["client_name#fr"] == update["client_name#fr"]

    #
    def test_client_registration_delete(self):
        args = {
            "redirect_uris": [
                "https://client.example.org/callback",
                "https://client.example.org/callback2"
            ],
            "client_name":
            "My Example Client",
            "client_name#ja-Jpan-JP":
            "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method":
            "client_secret_basic",
            "scope":
            "read write dolphin",
        }
        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json(),
                                                   environ={})
        _resp = ClientInfoResponse().from_json(resp.message)
        resp = self.provider.client_info_endpoint(
            request=request.to_json(),
            environ={
                "HTTP_AUTHORIZATION":
                "Bearer %s" % (_resp["registration_access_token"], )
            },
            method="DELETE",
            query="client_id=%s" % _resp["client_id"])

        assert isinstance(resp, NoContent)

        # A read should fail
        resp = self.provider.client_info_endpoint(
            "",
            environ={
                "HTTP_AUTHORIZATION":
                "Bearer %s" % (_resp["registration_access_token"], )
            },
            query="client_id=%s" % _resp["client_id"])

        assert isinstance(resp, Unauthorized)

    def test_client_registration_with_software_statement(self):
        jwks, keyjar, kidd = build_keyjar(KEYS)
        fed_operator = 'https://fedop.example.org'

        self.provider.keyjar[fed_operator] = keyjar['']
        ss = make_software_statement(keyjar, fed_operator, client_id='foxtrot')

        args = {
            "redirect_uris": [
                "https://client.example.org/callback",
                "https://client.example.org/callback2"
            ],
            "client_name":
            "XYZ Service B",
            "token_endpoint_auth_method":
            "client_secret_basic",
            "scope":
            "read write dolphin",
            'software_statement':
            ss
        }
        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json(),
                                                   environ={})
        cli_resp = ClientInfoResponse().from_json(resp.message)
        assert cli_resp
Exemplo n.º 18
0
    authz = Implicit()

    try:
        capabilities = config.CAPABILITIES
    except AttributeError:
        capabilities = None

    if args.insecure:
        kwargs = {'verify_ssl': False}
    else:
        kwargs = {}

    # Initiate the Provider
    oas = Provider(config.issuer, None, cdb, broker, authz,
                   baseurl=config.issuer, client_authn=verify_client,
                   symkey=config.SYM_KEY, hostname=config.HOST,
                   capabilities=capabilities,
                   behavior=config.BEHAVIOR, **kwargs)

    try:
        jwks = keyjar_init(oas, config.keys, kid_template="op%d")
    except Exception as err:
        LOGGER.error("Key setup failed: {}".format(err))
        print("Key setup failed: {}".format(err))
        exit()
        # oas.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        jwks_file_name = JWKS_FILE_NAME
        f = open(jwks_file_name, "w")

        for key in jwks["keys"]:
Exemplo n.º 19
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"
    # chooses which authentication method that is to be used.

    broker = authn_setup(config)

    # dealing with authorization, this is just everything goes.
    authz = Implicit()

    try:
        capabilities = config.CAPABILITIES
    except AttributeError:
        capabilities = None

    # Initiate the Provider
    OAS = Provider(config.issuer, None, cdb, broker, authz,
                   baseurl=config.issuer, client_authn=verify_client,
                   symkey=config.SYM_KEY, hostname=config.HOST,
                   capabilities=capabilities,
                   behavior=config.BEHAVIOR)

    try:
        jwks = keyjar_init(OAS, config.keys, kid_template="op%d")
    except Exception as err:
        LOGGER.error("Key setup failed: {}".format(err))
        print("Key setup failed: {}".format(err))
        exit()
        #OAS.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        jwks_file_name = JWKS_FILE_NAME
        f = open(jwks_file_name, "w")

        for key in jwks["keys"]:
Exemplo n.º 21
0
class TestProvider(object):
    SERVER_INFO = {
        "version": "3.0",
        "issuer": "https://connect-op.heroku.com",
        "authorization_endpoint": "http://localhost:8088/authorization",
        "token_endpoint": "http://localhost:8088/token",
        "flows_supported": ["code", "token", "code token"],
    }

    CDB = {
        "a1b2c3": {"password": "******", "client_secret": "drickyoughurt"},
        "client1": {"client_secret": "hemlighet", "redirect_uris": [("http://localhost:8087/authz", None)]},
    }

    @pytest.fixture(autouse=True)
    def create_provider(self):
        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))

        self.provider = Provider(
            "pyoicserv",
            sdb.SessionDB(TestProvider.SERVER_INFO["issuer"]),
            TestProvider.CDB,
            authn_broker,
            Implicit(),
            verify_client,
            client_info_url="https://example.com/as",
            client_authn_methods={
                "client_secret_post": ClientSecretPost,
                "client_secret_basic": ClientSecretBasic,
                "bearer_header": BearerHeader,
            },
        )

    def test_registration_endpoint(self):
        request = RegistrationRequest(client_name="myself", redirect_uris=["https://example.com/rp"])
        resp = self.provider.registration_endpoint(request=request.to_json())
        assert isinstance(resp, Response)
        data = json.loads(resp.message)
        assert data["client_name"] == "myself"
        assert _eq(data["redirect_uris"], ["https://example.com/rp"])

        _resp = ClientInfoResponse().from_json(resp.message)
        assert "client_id" in _resp

    def test_registration_uri_error(self):
        args = {
            "redirect_uris": ["https://client.example.org/callback", "https://client.example.org/callback2"],
            "client_name": "My Example Client",
            "client_name#ja-Jpan-JP": "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method": "client_secret_basic",
            "scope": "read write dolphin",
            # invalid logo_uri
            "logo_uri": "https://client.example.org/logo.png",
            "jwks_uri": "https://client.example.org/my_public_keys.jwks",
        }

        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json())
        _resp = ClientRegistrationError().from_json(resp.message)

        assert "error" in _resp
        assert _resp["error"] == "invalid_client_metadata"

    def test_client_registration_utf_8_client_name(self):
        args = {
            "redirect_uris": ["https://client.example.org/callback", "https://client.example.org/callback2"],
            "client_name": "My Example Client",
            "client_name#ja-Jpan-JP": "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method": "client_secret_basic",
            "scope": "read write dolphin",
        }

        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json())
        _resp = ClientInfoResponse().from_json(resp.message)

        assert _resp["client_name#ja-Jpan-JP"] == "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D"
        assert _resp["client_name"] == "My Example Client"

    def test_client_user_info_get(self):
        args = {
            "redirect_uris": ["https://client.example.org/callback", "https://client.example.org/callback2"],
            "client_name": "My Example Client",
            "client_name#ja-Jpan-JP": "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method": "client_secret_basic",
            "scope": "read write dolphin",
        }
        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json())
        _resp = ClientInfoResponse().from_json(resp.message)

        resp = self.provider.client_info_endpoint(
            "GET",
            environ={"HTTP_AUTHORIZATION": "Bearer %s" % (_resp["registration_access_token"],)},
            query="client_id=%s" % _resp["client_id"],
            request=request.to_json(),
        )

        _resp_cir = ClientInfoResponse().from_json(resp.message)
        assert _resp == _resp_cir

    def test_client_registration_update(self):
        args = {
            "redirect_uris": ["https://client.example.org/callback", "https://client.example.org/callback2"],
            "client_name": "My Example Client",
            "client_name#ja-Jpan-JP": "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method": "client_secret_basic",
            "scope": "read write dolphin",
        }
        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json(), environ={})
        _resp = ClientInfoResponse().from_json(resp.message)

        update = {
            "client_id": _resp["client_id"],
            "client_secret": _resp["client_secret"],
            "redirect_uris": ["https://client.example.org/callback", "https://client.example.org/alt"],
            "scope": "read write dolphin",
            "grant_types": ["authorization_code", "refresh_token"],
            "token_endpoint_auth_method": "client_secret_basic",
            "jwks_uri": "https://client.example.org/my_public_keys.jwks",
            "client_name": "My New Example",
            "client_name#fr": "Mon Nouvel Exemple",
        }
        update_req = RegistrationRequest(**update)
        resp = self.provider.client_info_endpoint(
            request=update_req.to_json(),
            environ={"HTTP_AUTHORIZATION": "Bearer %s" % (_resp["registration_access_token"],)},
            method="PUT",
            query="client_id=%s" % _resp["client_id"],
        )

        _resp_up = ClientInfoResponse().from_json(resp.message)
        assert _resp_up["client_id"] == update["client_id"]
        assert _resp_up["client_secret"] == update["client_secret"]
        assert _resp_up["redirect_uris"] == update["redirect_uris"]
        assert _resp_up["scope"] == update["scope"].split()
        assert _resp_up["grant_types"] == update["grant_types"]
        assert _resp_up["token_endpoint_auth_method"] == update["token_endpoint_auth_method"]
        assert _resp_up["jwks_uri"] == update["jwks_uri"]
        assert _resp_up["client_name"] == update["client_name"]
        assert _resp_up["client_name#fr"] == update["client_name#fr"]

    #
    def test_client_registration_delete(self):
        args = {
            "redirect_uris": ["https://client.example.org/callback", "https://client.example.org/callback2"],
            "client_name": "My Example Client",
            "client_name#ja-Jpan-JP": "\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u540D",
            "token_endpoint_auth_method": "client_secret_basic",
            "scope": "read write dolphin",
        }
        request = RegistrationRequest(**args)
        resp = self.provider.registration_endpoint(request=request.to_json(), environ={})
        _resp = ClientInfoResponse().from_json(resp.message)
        resp = self.provider.client_info_endpoint(
            request=request.to_json(),
            environ={"HTTP_AUTHORIZATION": "Bearer %s" % (_resp["registration_access_token"],)},
            method="DELETE",
            query="client_id=%s" % _resp["client_id"],
        )

        assert isinstance(resp, NoContent)

        # A read should fail
        resp = self.provider.client_info_endpoint(
            "",
            environ={"HTTP_AUTHORIZATION": "Bearer %s" % (_resp["registration_access_token"],)},
            query="client_id=%s" % _resp["client_id"],
        )

        assert isinstance(resp, Unauthorized)
Exemplo n.º 22
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
Exemplo n.º 23
0
    # chooses which authentication method that is to be used.

    broker = authn_setup(config)

    # dealing with authorization, this is just everything goes.
    authz = Implicit()

    try:
        capabilities = config.CAPABILITIES
    except AttributeError:
        capabilities = None

    # Initiate the Provider
    OAS = Provider(config.issuer, None, cdb, broker, authz,
                   baseurl=config.issuer, client_authn=verify_client,
                   symkey=config.SYM_KEY, hostname=config.HOST,
                   capabilities=capabilities,
                   behavior=config.BEHAVIOR)

    try:
        jwks = keyjar_init(OAS, config.keys, kid_template="op%d")
    except Exception as err:
        LOGGER.error("Key setup failed: {}".format(err))
        print("Key setup failed: {}".format(err))
        exit()
        #OAS.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        jwks_file_name = JWKS_FILE_NAME
        f = open(jwks_file_name, "w")

        for key in jwks["keys"]:
Exemplo n.º 24
0
        capabilities = config.CAPABILITIES
    except AttributeError:
        capabilities = None

    if args.insecure:
        kwargs = {'verify_ssl': False}
    else:
        kwargs = {}

    # Initiate the Provider
    oas = Provider(config.issuer,
                   None,
                   cdb,
                   broker,
                   authz,
                   baseurl=config.issuer,
                   client_authn=verify_client,
                   symkey=config.SYM_KEY,
                   hostname=config.HOST,
                   capabilities=capabilities,
                   behavior=config.BEHAVIOR,
                   **kwargs)

    try:
        jwks = keyjar_init(oas, config.keys, kid_template="op%d")
    except Exception as err:
        LOGGER.error("Key setup failed: {}".format(err))
        print("Key setup failed: {}".format(err))
        exit()
        # oas.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        jwks_file_name = JWKS_FILE_NAME
Exemplo n.º 25
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