Exemplo n.º 1
0
    def test_verify(self):
        _dict = {"req_str": "Fair", "opt_str": "game", "opt_int": 9,
                 "opt_str_list": ["one", "two"],
                 "req_str_list": ["spike", "lee"],
                 "opt_json": '{"ford": "green"}'}

        cls = DummyMessage(**_dict)
        assert cls.verify()
        assert _eq(cls.keys(), ['opt_str', 'req_str', 'opt_json',
                                'req_str_list', 'opt_str_list', 'opt_int'])

        _dict = {"req_str": "Fair", "opt_str": "game", "opt_int": 9,
                 "opt_str_list": ["one", "two"],
                 "req_str_list": ["spike", "lee"],
                 "opt_json": '{"ford": "green"}', "extra": "internal"}

        cls = DummyMessage(**_dict)
        assert cls.verify()
        assert _eq(cls.keys(), ['opt_str', 'req_str', 'extra', 'opt_json',
                                'req_str_list', 'opt_str_list', 'opt_int'])

        _dict = {"req_str": "Fair", "opt_str": "game", "opt_int": 9,
                 "opt_str_list": ["one", "two"],
                 "req_str_list": ["spike", "lee"]}

        cls = DummyMessage(**_dict)
        cls.verify()
        assert _eq(cls.keys(), ['opt_str', 'req_str', 'req_str_list',
                                'opt_str_list', 'opt_int'])
Exemplo n.º 2
0
    def test_to_urlencoded_extended_omit(self):
        atr = AccessTokenResponse(
            access_token="2YotnFZFEjr1zCsicMWpAA",
            token_type="example",
            expires_in=3600,
            refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
            example_parameter="example_value",
            scope=["inner", "outer"],
            extra=["local", "external"],
            level=3)

        uec = atr.to_urlencoded()
        assert query_string_compare(uec,
                                    "scope=inner+outer&level=3&expires_in=3600&token_type=example&extra=local&extra=external&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&access_token=2YotnFZFEjr1zCsicMWpAA&example_parameter=example_value")

        del atr["extra"]
        ouec = atr.to_urlencoded()
        assert query_string_compare(ouec,
                                    "access_token=2YotnFZFEjr1zCsicMWpAA&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&level=3&example_parameter=example_value&token_type=example&expires_in=3600&scope=inner+outer")
        assert len(uec) == (len(ouec) + len("extra=local") +
                            len("extra=external") + 2)

        atr2 = AccessTokenResponse().deserialize(uec, "urlencoded")
        assert _eq(atr2.keys(), ['access_token', 'expires_in', 'token_type',
                                 'scope', 'refresh_token', 'level',
                                 'example_parameter', 'extra'])

        atr3 = AccessTokenResponse().deserialize(ouec, "urlencoded")
        assert _eq(atr3.keys(), ['access_token', 'expires_in', 'token_type',
                                 'scope', 'refresh_token', 'level',
                                 'example_parameter'])
Exemplo n.º 3
0
def test_grant_access_token_1():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example", expires_in=1,
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              xscope=["inner", "outer"])

    token = Token(atr)
    grant.tokens.append(token)

    print grant.keys()
    assert _eq(grant.keys(), ['tokens', 'id_token', 'code', 'exp_in', 'seed',
                              'grant_expiration_time'])
    print token.keys()
    assert _eq(token.keys(), ['token_expiration_time', 'access_token',
                              'expires_in', 'example_parameter', 'token_type',
                              'xscope', 'refresh_token', 'scope',
                              'replaced'])

    assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
    assert token.token_type == "example"
    assert token.refresh_token == "tGzv3JOkF0XG5Qx2TlKWIA"
    assert token.example_parameter == "example_value"
    assert token.xscope == ["inner", "outer"]
    assert token.token_expiration_time != 0

    time.sleep(2)
    assert token.is_valid() is False
Exemplo n.º 4
0
def test_bearer_header_with_http_args():
    client = Client("A")
    client.client_secret = "boarding pass"

    request_args = {"access_token": "Sesame"}

    cis = ResourceRequest()

    bh = BearerHeader(client)
    http_args = bh.construct(cis, request_args, http_args={"foo": "bar"})

    print cis
    print http_args
    assert _eq(http_args.keys(), ["foo", "headers"])
    assert http_args["headers"] == {"Authorization": "Bearer Sesame"}

    # -----------------

    request_args = {"access_token": "Sesame"}

    bh = BearerHeader(client)
    http_args = bh.construct(cis, request_args,
                             http_args={"headers": {"x-foo": "bar"}})

    print cis
    print http_args
    assert _eq(http_args.keys(), ["headers"])
    assert _eq(http_args["headers"].keys(), ["Authorization", "x-foo"])
    assert http_args["headers"]["Authorization"] == "Bearer Sesame"
Exemplo n.º 5
0
    def test_to_urlencoded_extended_omit(self):
        atr = AccessTokenResponse(
            access_token="2YotnFZFEjr1zCsicMWpAA",
            token_type="example",
            expires_in=3600,
            refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
            example_parameter="example_value",
            scope=["inner", "outer"],
            extra=["local", "external"],
            level=3)

        uec = atr.to_urlencoded()
        assert query_string_compare(uec,
                                    "scope=inner+outer&level=3&expires_in=3600&token_type=example&extra=local&extra=external&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&access_token=2YotnFZFEjr1zCsicMWpAA&example_parameter=example_value")

        del atr["extra"]
        ouec = atr.to_urlencoded()
        assert query_string_compare(ouec,
                                    "access_token=2YotnFZFEjr1zCsicMWpAA&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&level=3&example_parameter=example_value&token_type=example&expires_in=3600&scope=inner+outer")
        assert len(uec) == (len(ouec) + len("extra=local") +
                            len("extra=external") + 2)

        atr2 = AccessTokenResponse().deserialize(uec, "urlencoded")
        assert _eq(atr2.keys(), ['access_token', 'expires_in', 'token_type',
                                 'scope', 'refresh_token', 'level',
                                 'example_parameter', 'extra'])

        atr3 = AccessTokenResponse().deserialize(ouec, "urlencoded")
        assert _eq(atr3.keys(), ['access_token', 'expires_in', 'token_type',
                                 'scope', 'refresh_token', 'level',
                                 'example_parameter'])
Exemplo n.º 6
0
def test_server_parse_token_request():
    atr = AccessTokenRequest(grant_type="authorization_code",
                             code="SplxlOBeZQQYbYS6WxSbIA",
                             redirect_uri="https://client.example.com/cb",
                             client_id=CLIENT_ID,
                             extra="foo")

    uenc = atr.to_urlencoded()

    srv = Server()
    srv.keyjar = KEYJ
    tr = srv.parse_token_request(body=uenc)
    print tr.keys()

    assert tr.type() == "AccessTokenRequest"
    assert _eq(tr.keys(),
               ['code', 'redirect_uri', 'grant_type', 'client_id', 'extra'])

    assert tr["grant_type"] == "authorization_code"
    assert tr["code"] == "SplxlOBeZQQYbYS6WxSbIA"

    tr = srv.parse_token_request(body=uenc)
    print tr.keys()

    assert tr.type() == "AccessTokenRequest"
    assert _eq(tr.keys(),
               ['code', 'grant_type', 'client_id', 'redirect_uri', 'extra'])

    assert tr["extra"] == "foo"
Exemplo n.º 7
0
    def test_complete_auth_token(self):
        _state = "state0"
        self.consumer.config["response_type"] = ["code", "token"]

        args = {
            "client_id": self.consumer.client_id,
            "response_type": self.consumer.config["response_type"],
            "scope": ["openid"],
        }

        result = self.consumer.do_authorization_request(state=_state,
                                                        request_args=args)
        self.consumer._backup("state0")

        assert result.status_code == 302
        parsed = urlparse(result.headers["location"])
        baseurl = "{}://{}{}".format(parsed.scheme, parsed.netloc, parsed.path)
        assert baseurl == self.consumer.redirect_uris[0]

        part = self.consumer.parse_authz(query=parsed.query)
        auth = part[0]
        acc = part[1]
        assert part[2] is None

        assert isinstance(auth, AuthorizationResponse)
        assert isinstance(acc, AccessTokenResponse)
        assert _eq(auth.keys(), [
            'code', 'access_token', 'expires_in', 'token_type', 'state',
            'scope', 'refresh_token'
        ])
        assert _eq(acc.keys(), [
            'token_type', 'state', 'access_token', 'scope', 'expires_in',
            'refresh_token'
        ])
Exemplo n.º 8
0
def test_provider_authenticated():
    provider = Provider("pyoicserv", sdb.SessionDB(SERVER_INFO["issuer"]), CDB,
                        AUTHN_BROKER, AUTHZ, verify_client, symkey=rndstr(16))
    _session_db = {}
    cons = Consumer(_session_db, client_config=CLIENT_CONFIG,
                    server_info=SERVER_INFO, **CONSUMER_CONFIG)
    cons.debug = True

    sid, location = cons.begin("http://localhost:8087",
                               "http://localhost:8088/authorization")

    query_string = location.split("?")[1]

    resp = provider.authorization_endpoint(query_string)
    assert resp.status == "302 Found"
    print resp.headers
    print resp.message
    if content_type(resp.headers) == "json":
        resp = resp.message
    else:
        resp = resp.message.split("?")[1]
    aresp = cons.handle_authorization_response(query=resp)

    print aresp.keys()
    assert aresp.type() == "AuthorizationResponse"
    assert _eq(aresp.keys(), ['state', 'code'])

    print cons.grant[sid].keys()
    assert _eq(cons.grant[sid].keys(), ['tokens', 'code', 'exp_in',
                                               'seed', 'id_token',
                                               'grant_expiration_time'])
Exemplo n.º 9
0
def test_server_parse_token_request():
    atr = AccessTokenRequest(grant_type="authorization_code",
                             code="SplxlOBeZQQYbYS6WxSbIA",
                             redirect_uri="https://client.example.com/cb",
                             client_id=CLIENT_ID, extra="foo")

    uenc = atr.to_urlencoded()

    srv = Server()
    srv.keyjar = KEYJ
    tr = srv.parse_token_request(body=uenc)
    print tr.keys()

    assert tr.type() == "AccessTokenRequest"
    assert _eq(tr.keys(), ['code', 'redirect_uri', 'grant_type', 'client_id',
                           'extra'])

    assert tr["grant_type"] == "authorization_code"
    assert tr["code"] == "SplxlOBeZQQYbYS6WxSbIA"

    tr = srv.parse_token_request(body=uenc)
    print tr.keys()

    assert tr.type() == "AccessTokenRequest"
    assert _eq(tr.keys(), ['code', 'grant_type', 'client_id', 'redirect_uri',
                           'extra'])

    assert tr["extra"] == "foo"
Exemplo n.º 10
0
def test_message():
    _dict = {"req_str": "Fair", "opt_str": "game", "opt_int": 9,
             "opt_str_list": ["one", "two"], "req_str_list": ["spike", "lee"],
             "opt_json": '{"ford": "green"}'}

    cls = Dummy_Message(**_dict)
    cls.verify()
    assert _eq(cls.keys(), ['opt_str', 'req_str', 'opt_json',
                            'req_str_list', 'opt_str_list', 'opt_int'])

    _dict = {"req_str": "Fair", "opt_str": "game", "opt_int": 9,
             "opt_str_list": ["one", "two"], "req_str_list": ["spike", "lee"],
             "opt_json": '{"ford": "green"}', "extra": "internal"}

    cls = Dummy_Message(**_dict)
    cls.verify()
    print cls.keys()
    assert _eq(cls.keys(), ['opt_str', 'req_str', 'extra', 'opt_json',
                            'req_str_list', 'opt_str_list', 'opt_int'])

    _dict = {"req_str": "Fair", "opt_str": "game", "opt_int": 9,
             "opt_str_list": ["one", "two"], "req_str_list": ["spike", "lee"]}

    cls = Dummy_Message(**_dict)
    cls.verify()
    assert _eq(cls.keys(), ['opt_str', 'req_str', 'req_str_list',
                            'opt_str_list', 'opt_int'])
Exemplo n.º 11
0
def test_ProviderConfigurationResponse():
    resp = {
        "authorization_endpoint": "https://server.example.com/connect/authorize",
        "issuer": "https://server.example.com",
        "token_endpoint": "https://server.example.com/connect/token",
        "token_endpoint_auth_methods_supported": ["client_secret_basic",
                                                  "private_key_jwt"],
        "userinfo_endpoint": "https://server.example.com/connect/user",
        "check_id_endpoint": "https://server.example.com/connect/check_id",
        "refresh_session_endpoint": "https://server.example.com/connect/refresh_session",
        "end_session_endpoint": "https://server.example.com/connect/end_session",
        "jwk_url": "https://server.example.com/jwk.json",
        "registration_endpoint": "https://server.example.com/connect/register",
        "scopes_supported": ["openid", "profile", "email", "address", "phone"],
        "response_types_supported": ["code", "code id_token", "token id_token"],
        "acrs_supported": ["1", "2", "http://id.incommon.org/assurance/bronze"],
        "user_id_types_supported": ["public", "pairwise"],
        "userinfo_algs_supported": ["HS256", "RS256", "A128CBC", "A128KW",
                                    "RSA1_5"],
        "id_token_algs_supported": ["HS256", "RS256", "A128CBC", "A128KW",
                                    "RSA1_5"],
        "request_object_algs_supported": ["HS256", "RS256", "A128CBC", "A128KW",
                                          "RSA1_5"]
    }

    pcr = ProviderConfigurationResponse().deserialize(json.dumps(resp), "json")

    assert _eq(pcr["user_id_types_supported"], ["public", "pairwise"])
    assert _eq(pcr["acrs_supported"],
               ["1", "2", "http://id.incommon.org/assurance/bronze"])
Exemplo n.º 12
0
def test_ProviderConfigurationResponse():
    resp = {
        "authorization_endpoint": "https://server.example.com/connect/authorize",
        "issuer": "https://server.example.com",
        "token_endpoint": "https://server.example.com/connect/token",
        "token_endpoint_auth_methods_supported": ["client_secret_basic",
                                                  "private_key_jwt"],
        "userinfo_endpoint": "https://server.example.com/connect/user",
        "check_id_endpoint": "https://server.example.com/connect/check_id",
        "refresh_session_endpoint": "https://server.example.com/connect/refresh_session",
        "end_session_endpoint": "https://server.example.com/connect/end_session",
        "jwk_url": "https://server.example.com/jwk.json",
        "registration_endpoint": "https://server.example.com/connect/register",
        "scopes_supported": ["openid", "profile", "email", "address", "phone"],
        "response_types_supported": ["code", "code id_token", "token id_token"],
        "acrs_supported": ["1", "2", "http://id.incommon.org/assurance/bronze"],
        "user_id_types_supported": ["public", "pairwise"],
        "userinfo_algs_supported": ["HS256", "RS256", "A128CBC", "A128KW",
                                    "RSA1_5"],
        "id_token_algs_supported": ["HS256", "RS256", "A128CBC", "A128KW",
                                    "RSA1_5"],
        "request_object_algs_supported": ["HS256", "RS256", "A128CBC", "A128KW",
                                          "RSA1_5"]
    }

    pcr = ProviderConfigurationResponse().deserialize(json.dumps(resp), "json")

    assert _eq(pcr["user_id_types_supported"], ["public", "pairwise"])
    assert _eq(pcr["acrs_supported"],
               ["1", "2", "http://id.incommon.org/assurance/bronze"])
Exemplo n.º 13
0
    def test_complete_auth_token(self):
        _state = "state0"
        self.consumer.config["response_type"] = ["code", "token"]

        args = {
            "client_id": self.consumer.client_id,
            "response_type": self.consumer.config["response_type"],
            "scope": ["openid"],
        }

        result = self.consumer.do_authorization_request(state=_state,
                                                        request_args=args)
        self.consumer._backup("state0")

        assert result.status_code == 302
        parsed = urlparse(result.headers["location"])
        baseurl = "{}://{}{}".format(parsed.scheme, parsed.netloc, parsed.path)
        assert baseurl == self.consumer.redirect_uris[0]

        part = self.consumer.parse_authz(query=parsed.query)
        auth = part[0]
        acc = part[1]
        assert part[2] is None

        assert isinstance(auth, AuthorizationResponse)
        assert isinstance(acc, AccessTokenResponse)
        print(auth.keys())
        assert _eq(auth.keys(), ['code', 'access_token',
                                 'token_type', 'state', 'client_id', 'scope'])
        assert _eq(acc.keys(), ['token_type', 'state', 'access_token', 'scope'])
Exemplo n.º 14
0
    def test_authenticated_hybrid(self):
        _state, location = self.cons.begin(
            scope="openid email claims_in_id_token",
            response_type="code id_token",
            path="http://localhost:8087")

        resp = self.provider.authorization_endpoint(
            request=urlparse(location).query)

        part = self.cons.parse_authz(resp.message)

        aresp = part[0]
        assert part[1] is None
        assert part[2] is not None

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ['scope', 'state', 'code', 'id_token'])

        assert _eq(self.cons.grant[_state].keys(),
                   ['code', 'id_token', 'tokens',
                    'exp_in',
                    'grant_expiration_time', 'seed'])
        id_token = part[2]
        assert isinstance(id_token, IdToken)
        assert _eq(id_token.keys(),
                   ['nonce', 'c_hash', 'sub', 'iss', 'acr', 'exp', 'auth_time',
                    'iat', 'aud'])
Exemplo n.º 15
0
def test_sp_sep_list_deserializer():
    vals = sp_sep_list_deserializer("foo bar zen")
    assert len(vals) == 3
    assert _eq(vals, ["foo", "bar", "zen"])

    vals = sp_sep_list_deserializer(["foo bar zen"])
    assert len(vals) == 3
    assert _eq(vals, ["foo", "bar", "zen"])
Exemplo n.º 16
0
def test_sp_sep_list_deserializer():
    vals = sp_sep_list_deserializer("foo bar zen")
    assert len(vals) == 3
    assert _eq(vals, ["foo", "bar", "zen"])

    vals = sp_sep_list_deserializer(["foo bar zen"])
    assert len(vals) == 3
    assert _eq(vals, ["foo", "bar", "zen"])
Exemplo n.º 17
0
def test_address_deser():
    pre = AddressClaim(street_address="Kasamark 114", locality="Umea",
                       country="Sweden")

    adc = address_deser(pre.to_json(), sformat="json")
    assert _eq(adc.keys(), ['street_address', 'locality', 'country'])

    adc = address_deser(pre.to_dict(), sformat="json")
    assert _eq(adc.keys(), ['street_address', 'locality', 'country'])
Exemplo n.º 18
0
def test_address_deser():
    pre = AddressClaim(street_address="Kasamark 114", locality="Umea",
                       country="Sweden")

    adc = address_deser(pre.to_json(), sformat="json")
    assert _eq(adc.keys(), ['street_address', 'locality', 'country'])

    adc = address_deser(pre.to_dict(), sformat="json")
    assert _eq(adc.keys(), ['street_address', 'locality', 'country'])
Exemplo n.º 19
0
    def test_construct_with_headers(self, client):
        request_args = {"access_token": "Sesame"}

        bh = BearerHeader(client)
        http_args = bh.construct(request_args=request_args,
                                 http_args={"headers": {"x-foo": "bar"}})

        assert _eq(http_args.keys(), ["headers"])
        assert _eq(http_args["headers"].keys(), ["Authorization", "x-foo"])
        assert http_args["headers"]["Authorization"] == "Bearer Sesame"
Exemplo n.º 20
0
    def test_init(self):
        info = user_info(None, USERDB, "diana")

        keys = [SYMKey(key="hemlig")]
        cresp = UserClaimsResponse(jwt=info.to_jwt(key=keys, algorithm="HS256"),
                                   claims_names=list(info.keys()))

        assert _eq(list(cresp.keys()), ["jwt", "claims_names"])
        assert _eq(cresp["claims_names"], ['gender', 'birthdate'])
        assert "jwt" in cresp
Exemplo n.º 21
0
    def test_construct_with_headers(self, client):
        request_args = {"access_token": "Sesame"}

        bh = BearerHeader(client)
        http_args = bh.construct(request_args=request_args,
                                 http_args={"headers": {"x-foo": "bar"}})

        assert _eq(http_args.keys(), ["headers"])
        assert _eq(http_args["headers"].keys(), ["Authorization", "x-foo"])
        assert http_args["headers"]["Authorization"] == "Bearer Sesame"
Exemplo n.º 22
0
def test_parse_userinfo_request():
    srv = Server()
    qdict = srv.parse_user_info_request(data=UIREQ.to_urlencoded())
    assert _eq(qdict.keys(), ['access_token'])
    assert qdict["access_token"] == "access_token"

    url = "https://example.org/userinfo?%s" % UIREQ.to_urlencoded()
    qdict = srv.parse_user_info_request(data=url)
    assert _eq(qdict.keys(), ['access_token'])
    assert qdict["access_token"] == "access_token"
Exemplo n.º 23
0
def test_parse_userinfo_request():
    srv = Server()
    qdict = srv.parse_user_info_request(data=UIREQ.to_urlencoded())
    assert _eq(qdict.keys(), ['access_token'])
    assert qdict["access_token"] == "access_token"

    url = "https://example.org/userinfo?%s" % UIREQ.to_urlencoded()
    qdict = srv.parse_user_info_request(data=url)
    assert _eq(qdict.keys(), ['access_token'])
    assert qdict["access_token"] == "access_token"
Exemplo n.º 24
0
def test_multiple_response_types_urlencoded():
    ar = AuthorizationRequest(response_type=["code", "token"],
                              client_id="foobar")
    ue = ar.to_urlencoded()
    ue_splits = ue.split('&')
    expected_ue_splits = "response_type=code+token&client_id=foobar".split('&')
    assert _eq(ue_splits, expected_ue_splits)

    are = AuthorizationRequest().deserialize(ue, "urlencoded")
    assert _eq(are.keys(), ["response_type", "client_id"])
    assert _eq(are["response_type"], ["code", "token"])
Exemplo n.º 25
0
    def test_init(self):
        info = user_info(None, USERDB, "diana")

        keys = [SYMKey(key="hemlig")]
        cresp = UserClaimsResponse(jwt=info.to_jwt(key=keys,
                                                   algorithm="HS256"),
                                   claims_names=list(info.keys()))

        assert _eq(list(cresp.keys()), ["jwt", "claims_names"])
        assert _eq(cresp["claims_names"], ['gender', 'birthdate'])
        assert "jwt" in cresp
Exemplo n.º 26
0
def test_multiple_response_types_urlencoded():
    ar = AuthorizationRequest(response_type=["code", "token"],
                              client_id="foobar")
    ue = ar.to_urlencoded()
    ue_splits = ue.split('&')
    expected_ue_splits = "response_type=code+token&client_id=foobar".split('&')
    assert _eq(ue_splits, expected_ue_splits)

    are = AuthorizationRequest().deserialize(ue, "urlencoded")
    assert _eq(are.keys(), ["response_type", "client_id"])
    assert _eq(are["response_type"], ["code", "token"])
Exemplo n.º 27
0
    def test_parse_userinfo_requesr(self):
        uireq = UserInfoRequest(access_token="access_token")
        uencq = uireq.to_urlencoded()

        qdict = self.srv.parse_user_info_request(data=uencq)
        assert _eq(qdict.keys(), ['access_token'])
        assert qdict["access_token"] == "access_token"

        url = "https://example.org/userinfo?{}".format(uencq)
        qdict = self.srv.parse_user_info_request(data=url)
        assert _eq(qdict.keys(), ['access_token'])
        assert qdict["access_token"] == "access_token"
Exemplo n.º 28
0
def test_claims_deser_dict():
    pre = Claims(name={"essential": True}, nickname=None,
                 email={"essential": True},
                 email_verified={"essential": True}, picture=None)

    claims = claims_deser(pre.to_json(), sformat="json")
    assert _eq(claims.keys(), ['name', 'nickname', 'email', 'email_verified',
                               'picture'])

    claims = claims_deser(pre.to_dict(), sformat="dict")
    assert _eq(claims.keys(), ['name', 'nickname', 'email', 'email_verified',
                               'picture'])
Exemplo n.º 29
0
def test_parse_refresh_session_request():
    srv = Server()
    request = srv.parse_refresh_session_request(query=RSREQ.to_urlencoded())
    assert request.type() == "RefreshSessionRequest"
    assert _eq(request.keys(), ['id_token', 'state', 'redirect_url'])
    assert request["id_token"] == "id_token"

    url = "https://example.org/userinfo?%s" % RSREQ.to_urlencoded()
    request = srv.parse_refresh_session_request(url=url)
    assert request.type() == "RefreshSessionRequest"
    assert _eq(request.keys(), ['id_token', 'state', 'redirect_url'])
    assert request["id_token"] == "id_token"
Exemplo n.º 30
0
def test_parse_refresh_session_request():
    srv = Server()
    request = srv.parse_refresh_session_request(query=RSREQ.to_urlencoded())
    assert request.type() == "RefreshSessionRequest"
    assert _eq(request.keys(), ['id_token', 'state', 'redirect_url'])
    assert request["id_token"] == "id_token"

    url = "https://example.org/userinfo?%s" % RSREQ.to_urlencoded()
    request = srv.parse_refresh_session_request(url=url)
    assert request.type() == "RefreshSessionRequest"
    assert _eq(request.keys(), ['id_token', 'state', 'redirect_url'])
    assert request["id_token"] == "id_token"
Exemplo n.º 31
0
def test_claims_deser():
    pre = Claims(name={"essential": True}, nickname=None,
                 email={"essential": True},
                 email_verified={"essential": True}, picture=None)

    claims = claims_deser(pre.to_json(), sformat="json")
    assert _eq(claims.keys(), ['name', 'nickname', 'email', 'email_verified',
                               'picture'])

    claims = claims_deser(pre.to_dict(), sformat="dict")
    assert _eq(claims.keys(), ['name', 'nickname', 'email', 'email_verified',
                               'picture'])
Exemplo n.º 32
0
def test_clean_response():
    atr = AccessTokenResponse(access_token="access_token",
                              token_type="bearer", expires_in=600,
                              refresh_token="refresh", steps=39, stalls="yes")

    catr = clean_response(atr)
    atr_keys = atr.keys()
    catr_keys = catr.keys()
    assert _eq(atr_keys, ['token_type', 'access_token', 'expires_in',
                          'refresh_token', 'steps', 'stalls'])
    assert _eq(catr_keys, ['token_type', 'access_token', 'expires_in',
                           'refresh_token'])
Exemplo n.º 33
0
def test_multiple_response_types_json():
    ar = AuthorizationRequest(response_type=["code", "token"],
                              client_id="foobar")
    ue = ar.to_json()
    ue_obj = json.loads(ue)
    expected_ue_obj = {"response_type": "code token", "client_id": "foobar"}
    assert ue_obj == expected_ue_obj

    are = AuthorizationRequest().deserialize(ue, "json")
    print are.keys()
    assert _eq(are.keys(), ["response_type", "client_id"])
    assert _eq(are["response_type"], ["code", "token"])
Exemplo n.º 34
0
    def test_parse_userinfo_requesr(self):
        uireq = UserInfoRequest(access_token="access_token")
        uencq = uireq.to_urlencoded()

        qdict = self.srv.parse_user_info_request(data=uencq)
        assert _eq(qdict.keys(), ['access_token'])
        assert qdict["access_token"] == "access_token"

        url = "https://example.org/userinfo?{}".format(uencq)
        qdict = self.srv.parse_user_info_request(data=url)
        assert _eq(qdict.keys(), ['access_token'])
        assert qdict["access_token"] == "access_token"
Exemplo n.º 35
0
    def test_authenticated(self):
        _session_db = {}
        cons = Consumer(_session_db, client_config=CLIENT_CONFIG, server_info=SERVER_INFO, **CONSUMER_CONFIG)

        sid, location = cons.begin("http://localhost:8087", "http://localhost:8088/authorization")

        resp = self.provider.authorization_endpoint(urlparse(location).query)
        assert resp.status == "302 Found"
        resp = urlparse(resp.message).query
        aresp = cons.handle_authorization_response(query=resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ["state", "code"])
        assert _eq(cons.grant[sid].keys(), ["tokens", "code", "exp_in", "seed", "id_token", "grant_expiration_time"])
Exemplo n.º 36
0
 def real_test_discover(self):
     c = Consumer(None, None)
     principal = "*****@*****.**"
     res = c.discover(principal)
     assert isinstance(res, ProviderConfigurationResponse)
     assert _eq(res.keys(), ['registration_endpoint', 'scopes_supported',
                             'identifiers_supported', 'token_endpoint',
                             'flows_supported', 'version',
                             'userinfo_endpoint',
                             'authorization_endpoint', 'x509_url', 'issuer'])
     assert res.version == "3.0"
     assert _eq(res.flows_supported, ['code', 'token', 'id_token',
                                      'code token', 'code id_token',
                                      'id_token token'])
Exemplo n.º 37
0
    def test_multiple_response_types_json(self):
        ar = AuthorizationRequest(response_type=["code", "token"],
                                  client_id="foobar")
        ue = ar.to_json()
        ue_obj = json.loads(ue)
        expected_ue_obj = {
            "response_type": "code token",
            "client_id": "foobar"
        }
        assert ue_obj == expected_ue_obj

        are = AuthorizationRequest().deserialize(ue, "json")
        assert _eq(are.keys(), ["response_type", "client_id"])
        assert _eq(are["response_type"], ["code", "token"])
Exemplo n.º 38
0
 def real_test_discover(self):
     c = Consumer(None, None)
     principal = "*****@*****.**"
     res = c.discover(principal)
     assert isinstance(res, ProviderConfigurationResponse)
     assert _eq(res.keys(), [
         'registration_endpoint', 'scopes_supported',
         'identifiers_supported', 'token_endpoint', 'flows_supported',
         'version', 'userinfo_endpoint', 'authorization_endpoint',
         'x509_url', 'issuer'
     ])
     assert res.version == "3.0"
     assert _eq(res.flows_supported, [
         'code', 'token', 'id_token', 'code token', 'code id_token',
         'id_token token'
     ])
Exemplo n.º 39
0
    def test_construct_TokenRevocationRequest(self):
        req = self.client.construct_TokenRevocationRequest(state="foo")

        assert req
        print req.keys()
        assert _eq(req.keys(), ['token'])
        assert req["token"] == "access"
Exemplo n.º 40
0
def test_authz_err_resp_1b():
    ter = TokenErrorResponse(error="access_denied", state="xyz")

    assert ter
    print ter.__dict__.items()
    assert ter["error"] == "access_denied"
    assert _eq(ter.keys(), ['state', 'error'])
Exemplo n.º 41
0
    def test_parse_refresh_session_request(self):
        rsreq = RefreshSessionRequest(id_token="id_token",
                                      redirect_url="http://example.com/authz",
                                      state="state0")
        uencq = rsreq.to_urlencoded()

        request = self.srv.parse_refresh_session_request(query=uencq)
        assert isinstance(request, RefreshSessionRequest)
        assert _eq(request.keys(), ['id_token', 'state', 'redirect_url'])
        assert request["id_token"] == "id_token"

        url = "https://example.org/userinfo?{}".format(uencq)
        request = self.srv.parse_refresh_session_request(url=url)
        assert isinstance(request, RefreshSessionRequest)
        assert _eq(request.keys(), ['id_token', 'state', 'redirect_url'])
        assert request["id_token"] == "id_token"
Exemplo n.º 42
0
    def test_token_endpoint_unauth(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.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz"
        }

        # 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'])
Exemplo n.º 43
0
def test_userinfo():
    consumer = Consumer(SessionDB(SERVER_INFO["issuer"]), CONFIG,
                        CLIENT_CONFIG, SERVER_INFO)
    consumer.keyjar = CLIKEYS
    mfos = MyFakeOICServer("http://localhost:8088")
    mfos.keyjar = SRVKEYS
    consumer.http_request = mfos.http_request
    consumer.redirect_uris = ["http://example.com/authz"]
    _state = "state0"
    consumer.nonce = rndstr()
    consumer.secret_type = "basic"
    consumer.set_client_secret("hemligt")
    consumer.keyjar = CLIKEYS

    args = {
        "client_id": consumer.client_id,
        "response_type": "code",
        "scope": ["openid"],
    }

    result = consumer.do_authorization_request(state=_state, request_args=args)
    assert result.status_code == 302
    assert result.headers["location"].startswith(consumer.redirect_uris[0])
    _, query = result.headers["location"].split("?")

    consumer.parse_response(AuthorizationResponse,
                            info=query,
                            sformat="urlencoded")

    consumer.complete(_state)

    result = consumer.get_user_info(_state)
    print result
    assert result.type() == "OpenIDSchema"
    assert _eq(result.keys(), ['name', 'email', 'verified', 'nickname', 'sub'])
Exemplo n.º 44
0
    def test_parse_refresh_session_request(self):
        rsreq = RefreshSessionRequest(id_token="id_token",
                                      redirect_url="http://example.com/authz",
                                      state="state0")
        uencq = rsreq.to_urlencoded()

        request = self.srv.parse_refresh_session_request(query=uencq)
        assert isinstance(request, RefreshSessionRequest)
        assert _eq(request.keys(), ['id_token', 'state', 'redirect_url'])
        assert request["id_token"] == "id_token"

        url = "https://example.org/userinfo?{}".format(uencq)
        request = self.srv.parse_refresh_session_request(url=url)
        assert isinstance(request, RefreshSessionRequest)
        assert _eq(request.keys(), ['id_token', 'state', 'redirect_url'])
        assert request["id_token"] == "id_token"
Exemplo n.º 45
0
def test_authz_err_resp_1b():
    ter = TokenErrorResponse(error="access_denied", state="xyz")

    assert ter
    print ter.__dict__.items()
    assert ter["error"] == "access_denied"
    assert _eq(ter.keys(), ['state', 'error'])
Exemplo n.º 46
0
    def test_provider_config(self):
        c = Consumer(None, None)
        mfos = MyFakeOICServer("http://example.com")
        mfos.keyjar = SRVKEYS
        c.http_request = mfos.http_request

        principal = "*****@*****.**"

        res = c.discover(principal)
        info = c.provider_config(res)
        assert isinstance(info, ProviderConfigurationResponse)
        assert _eq(info.keys(), ['registration_endpoint', 'jwks_uri',
                                 'check_session_endpoint',
                                 'refresh_session_endpoint',
                                 'register_endpoint',
                                 'subject_types_supported',
                                 'token_endpoint_auth_methods_supported',
                                 'id_token_signing_alg_values_supported',
                                 'grant_types_supported', 'user_info_endpoint',
                                 'claims_parameter_supported',
                                 'request_parameter_supported',
                                 'discovery_endpoint', 'issuer',
                                 'authorization_endpoint', 'scopes_supported',
                                 'require_request_uri_registration',
                                 'identifiers_supported', 'token_endpoint',
                                 'request_uri_parameter_supported', 'version',
                                 'response_types_supported',
                                 'end_session_endpoint', 'flows_supported'])

        assert info["end_session_endpoint"] == "http://example.com/end_session"
Exemplo n.º 47
0
def test_jwt_pack_and_unpack():
    srv = JWT(keyjar, iss=issuer)
    _jwt = srv.pack(sub='sub')

    info = srv.unpack(_jwt)

    assert _eq(info.keys(), ['jti', 'iat', 'exp', 'iss', 'sub'])
Exemplo n.º 48
0
    def test_token_endpoint(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id=CLIENT_ID,
                                       response_type="code",
                                       scope=["openid"])

        _sdb = self.provider.sdb
        sid = _sdb.token.key(user="******", areq=authreq)
        access_grant = _sdb.token(sid=sid)
        ae = AuthnEvent("user", "salt")
        _sdb[sid] = {
            "oauth_state": "authz",
            "authn_event": ae,
            "authzreq": authreq.to_json(),
            "client_id": CLIENT_ID,
            "code": access_grant,
            "code_used": False,
            "scope": ["openid"],
            "redirect_uri": "http://example.com/authz",
        }
        _sdb.do_sub(sid, "client_salt")

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

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt)
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(),
                   ['token_type', 'id_token', 'access_token', 'scope',
                    'expires_in', 'refresh_token'])
Exemplo n.º 49
0
    def test_registration_endpoint_openid4us(self):
        req = RegistrationRequest(
            **{'token_endpoint_auth_method': u'client_secret_post',
               'redirect_uris': [
                   u'https://connect.openid4.us:5443/phpRp/index.php/callback',
                   u'https://connect.openid4.us:5443/phpRp/authcheck.php/authcheckcb'],
               'jwks_uri': u'https://connect.openid4.us:5443/phpRp/rp/rp.jwk',
               'userinfo_encrypted_response_alg': u'RSA1_5',
               'contacts': [u'*****@*****.**'],
               'userinfo_encrypted_response_enc': u'A128CBC-HS256',
               'application_type': u'web',
               'client_name': u'ABRP-17',
               'grant_types': [u'authorization_code', u'implicit'],
               'post_logout_redirect_uris': [
                   u'https://connect.openid4.us:5443/phpRp/index.php/logoutcb'],
               'subject_type': u'public',
               'response_types': [u'code', u'token', u'id_token', u'code token',
                                  u'code id_token', u'id_token token',
                                  u'code id_token token'],
               'policy_uri': u'https://connect.openid4.us:5443/phpRp/index.php/policy',
               'logo_uri': u'https://connect.openid4.us:5443/phpRp/media/logo.png'})

        resp = self.provider.registration_endpoint(request=req.to_json())

        regresp = RegistrationResponse().deserialize(resp.message, "json")
        assert _eq(regresp.keys(), list(req.keys()) +
                   ['registration_client_uri',
                    'client_secret_expires_at',
                    'registration_access_token',
                    'client_id', 'client_secret',
                    'client_id_issued_at'])
Exemplo n.º 50
0
    def test_parse_open_id_request(self):
        userinfo_claims = Claims(name={"essential": True}, nickname=None,
                                 email={"essential": True},
                                 email_verified={"essential": True},
                                 picture=None)
        id_token_claims = Claims(auth_time={"essential": True,
                                            "acr": {"values": [
                                                "urn:mace:incommon:iap:silver"]}})
        claims_req = ClaimsRequest(userinfo=userinfo_claims,
                                   id_token=id_token_claims)

        oidreq = OpenIDRequest(response_type=["code", "id_token"],
                               client_id=CLIENT_ID,
                               redirect_uri="https://client.example.com/cb",
                               scope="openid profile", state="n-0S6_WzA2Mj",
                               nonce="af0ifjsldkj", max_age=86400,
                               claims=claims_req)

        request = self.srv.parse_open_id_request(data=oidreq.to_json(),
                                                 sformat="json")
        assert isinstance(request, OpenIDRequest)
        assert _eq(request.keys(), ['nonce', 'claims', 'state', 'redirect_uri',
                                    'response_type', 'client_id', 'scope',
                                    'max_age'])
        assert request["nonce"] == "af0ifjsldkj"
        assert "email" in request["claims"]["userinfo"]
Exemplo n.º 51
0
    def test_parse_open_id_request(self):
        userinfo_claims = Claims(name={"essential": True},
                                 nickname=None,
                                 email={"essential": True},
                                 email_verified={"essential": True},
                                 picture=None)
        id_token_claims = Claims(auth_time={
            "essential": True,
            "acr": {
                "values": ["urn:mace:incommon:iap:silver"]
            }
        })
        claims_req = ClaimsRequest(userinfo=userinfo_claims,
                                   id_token=id_token_claims)

        oidreq = OpenIDRequest(response_type=["code", "id_token"],
                               client_id=CLIENT_ID,
                               redirect_uri="https://client.example.com/cb",
                               scope="openid profile",
                               state="n-0S6_WzA2Mj",
                               nonce="af0ifjsldkj",
                               max_age=86400,
                               claims=claims_req)

        request = self.srv.parse_open_id_request(data=oidreq.to_json(),
                                                 sformat="json")
        assert isinstance(request, OpenIDRequest)
        assert _eq(request.keys(), [
            'nonce', 'claims', 'state', 'redirect_uri', 'response_type',
            'client_id', 'scope', 'max_age'
        ])
        assert request["nonce"] == "af0ifjsldkj"
        assert "email" in request["claims"]["userinfo"]
Exemplo n.º 52
0
    def test_begin_file(self):
        tempdir = tempfile.mkdtemp()
        self.consumer.config["request_method"] = "file"
        self.consumer.config["temp_dir"] = tempdir
        self.consumer.config["temp_path"] = tempdir
        self.consumer.config["authz_page"] = "/authz"
        srv = Server()
        srv.keyjar = SRVKEYS

        sid, location = self.consumer.begin("openid",
                                            "code",
                                            path="http://localhost:8087")
        print location
        # vkeys = {".":srv.keyjar.get_verify_key()}
        authreq = srv.parse_authorization_request(url=location)
        print authreq.keys()
        assert _eq(authreq.keys(), [
            'max_age', 'state', 'redirect_uri', 'response_type', 'client_id',
            'scope', 'claims', 'request_uri'
        ])

        assert authreq["state"] == sid
        assert authreq["scope"] == self.consumer.config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
        assert authreq["redirect_uri"].startswith(
            "http://localhost:8087/authz")
        # Cleanup the file we have created
        shutil.rmtree(tempdir)
Exemplo n.º 53
0
def test_client_registration():
    msg = {
        "application_type":
        "web",
        "redirect_uris": [
            "https://client.example.org/callback",
            "https://client.example.org/callback2"
        ],
        "client_name":
        "My Example",
        "client_name#ja-Jpan-JP":
        "クライアント名",
        "logo_uri":
        "https://client.example.org/logo.png",
        "subject_type":
        "pairwise",
        "sector_identifier_uri":
        "https://other.example.net/file_of_redirect_uris.json",
        "token_endpoint_auth_method":
        "client_secret_basic",
        "jwks_uri":
        "https://client.example.org/my_public_keys.jwks",
        "userinfo_encrypted_response_alg":
        "RSA1_5",
        "userinfo_encrypted_response_enc":
        "A128CBC+HS256",
        "contacts": ["*****@*****.**", "*****@*****.**"],
        "request_uris": [
            "https://client.example.org/rf.txt#qpXaRLh_n93TTR9F252ValdatUQvQiJi5BDub2BeznA"
        ]
    }

    reg = RegistrationRequest().deserialize(json.dumps(msg), "json")

    assert _eq(msg.keys(), reg.keys())
Exemplo n.º 54
0
def test_provider_config():
    c = Consumer(None, None)
    mfos = MyFakeOICServer("http://example.com")
    mfos.keyjar = SRVKEYS
    c.http_request = mfos.http_request

    principal = "*****@*****.**"

    res = c.discover(principal)
    info = c.provider_config(res)
    assert info.type() == "ProviderConfigurationResponse"
    print info.keys()
    assert _eq(info.keys(), [
        'registration_endpoint', 'jwks_uri', 'check_session_endpoint',
        'refresh_session_endpoint', 'register_endpoint',
        'subject_types_supported', 'token_endpoint_auth_methods_supported',
        'id_token_signing_alg_values_supported', 'grant_types_supported',
        'user_info_endpoint', 'claims_parameter_supported',
        'request_parameter_supported', 'discovery_endpoint', 'issuer',
        'authorization_endpoint', 'scopes_supported',
        'require_request_uri_registration', 'identifiers_supported',
        'token_endpoint', 'request_uri_parameter_supported', 'version',
        'response_types_supported', 'end_session_endpoint', 'flows_supported'
    ])

    assert info["end_session_endpoint"] == "http://example.com/end_session"
Exemplo n.º 55
0
def test_claims_deser_0():
    _dic = {
        "userinfo": {
            "given_name": {
                "essential": True
            },
            "nickname": None,
            "email": {
                "essential": True
            },
            "email_verified": {
                "essential": True
            },
            "picture": None,
            "http://example.info/claims/groups": None
        },
        "id_token": {
            "auth_time": {
                "essential": True
            },
            "acr": {
                "values": ["urn:mace:incommon:iap:silver"]
            }
        }
    }

    claims = claims_deser(json.dumps(_dic), sformat="json")
    assert _eq(claims.keys(), ["userinfo", "id_token"])