Example #1
0
def test_server_parse_parse_authorization_request():
    srv = Server()
    srv.keyjar = KEYJ
    ar = AuthorizationRequest(response_type=["code"], client_id="foobar",
                              redirect_uri="http://foobar.example.com/oaclient",
                              state="cold", nonce="NONCE", scope=["openid"])

    uencq = ar.to_urlencoded()

    areq = srv.parse_authorization_request(query=uencq)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"

    urluenc = "%s?%s" % ("https://example.com/authz", uencq)

    areq = srv.parse_authorization_request(url=urluenc)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"
Example #2
0
def test_server_parse_parse_authorization_request():
    srv = Server()
    srv.keyjar = KEYJ
    ar = AuthorizationRequest(
        response_type=["code"],
        client_id="foobar",
        redirect_uri="http://foobar.example.com/oaclient",
        state="cold",
        nonce="NONCE",
        scope=["openid"])

    uencq = ar.to_urlencoded()

    areq = srv.parse_authorization_request(query=uencq)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"

    urluenc = "%s?%s" % ("https://example.com/authz", uencq)

    areq = srv.parse_authorization_request(url=urluenc)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"
    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)
Example #4
0
def test_request_attr_mis_match():
    redirect_uri = "http://example.com/redirect"
    client = Client(CLIENT_ID, client_authn_method=CLIENT_AUTHN_METHOD)
    client.redirect_uris = [redirect_uri]
    client.authorization_endpoint = "http://example.com/authorization"
    client.client_secret = "abcdefghijklmnop"
    client.keyjar[""] = KC_RSA
    client.behaviour = {
        "request_object_signing_alg": DEF_SIGN_ALG["openid_request_object"]}

    srv = Server()
    srv.keyjar = KEYJ

    areq = client.construct_AuthorizationRequest(
        request_args={
            "scope": "openid",
            "response_type": ["code"],
            "max_age": 86400,
            'state': 'foobar'
        },
        request_param="request")

    for attr in ['state', 'max_age', 'client_id']:
        del areq[attr]

    areq.lax = True
    req = srv.parse_authorization_request(query=areq.to_urlencoded())

    assert req.verify()
Example #5
0
    def test_begin_file(self, tmpdir):
        path = tmpdir.strpath
        external_path = "/exported"
        self.consumer.consumer_config["request_method"] = "file"
        self.consumer.consumer_config["temp_dir"] = path
        self.consumer.consumer_config["temp_path"] = external_path
        self.consumer.consumer_config["authz_page"] = "/authz"
        srv = Server()
        srv.keyjar = SRVKEYS

        sid, location = self.consumer.begin("openid", "code",
                                            path="http://localhost:8087")

        with responses.RequestsMock() as rsps:
            p = urlparse(self.consumer.request_uri)
            assert p.netloc == "localhost:8087"
            # Map the URL path to the local path
            relative_path = os.path.relpath(p.path, external_path)
            file_path = os.path.join(path, relative_path)

            with open(file_path) as f:
                rsps.add(rsps.GET, self.consumer.request_uri,
                         body=f.read(), status=200,
                         content_type='application/urlencoded')

            authreq = srv.parse_authorization_request(url=location)
            assert _eq(list(authreq.keys()),
                       ['max_age', 'state', 'redirect_uri', 'response_type',
                        'client_id', 'scope', 'claims'])

            assert authreq["state"] == sid
            assert authreq["scope"] == self.consumer.consumer_config["scope"]
            assert authreq["client_id"] == self.consumer.client_id
            assert authreq["redirect_uri"].startswith(
                "http://localhost:8087/authz")
Example #6
0
    def test_begin_file(self, tmpdir):
        path = tmpdir.strpath
        self.consumer.consumer_config["request_method"] = "file"
        self.consumer.consumer_config["temp_dir"] = path
        self.consumer.consumer_config["temp_path"] = path
        self.consumer.consumer_config["authz_page"] = "/authz"
        srv = Server()
        srv.keyjar = SRVKEYS

        sid, location = self.consumer.begin("openid",
                                            "code",
                                            path="http://localhost:8087")

        with responses.RequestsMock() as rsps:
            p = urlparse(self.consumer.request_uri)
            rsps.add(rsps.GET,
                     self.consumer.request_uri,
                     body=open(p.path).read(),
                     status=200,
                     content_type='application/urlencoded')

            authreq = srv.parse_authorization_request(url=location)
            assert _eq(list(authreq.keys()), [
                'max_age', 'state', 'redirect_uri', 'response_type',
                'client_id', 'scope', 'claims'
            ])

            assert authreq["state"] == sid
            assert authreq["scope"] == self.consumer.consumer_config["scope"]
            assert authreq["client_id"] == self.consumer.client_id
            assert authreq["redirect_uri"].startswith(
                "http://localhost:8087/authz")
Example #7
0
def test_parse_authorization_request():
    srv = Server()
    qdict = srv.parse_authorization_request(query=AREQ.to_urlencoded())
    assert _eq(qdict.keys(), [
        'nonce', 'state', 'redirect_uri', 'response_type', 'client_id', 'scope'
    ])
    assert qdict["state"] == "state0"
Example #8
0
def test_request_attr_mis_match():
    redirect_uri = "http://example.com/redirect"
    client = Client(CLIENT_ID, client_authn_method=CLIENT_AUTHN_METHOD)
    client.redirect_uris = [redirect_uri]
    client.authorization_endpoint = "http://example.com/authorization"
    client.client_secret = "abcdefghijklmnop"
    client.keyjar[""] = KC_RSA
    client.behaviour = {
        "request_object_signing_alg": DEF_SIGN_ALG["openid_request_object"]
    }

    srv = Server()
    srv.keyjar = KEYJ

    areq = client.construct_AuthorizationRequest(
        request_args={
            "scope": "openid",
            "response_type": ["code"],
            "max_age": 86400,
            "state": "foobar",
        },
        request_param="request",
    )

    for attr in ["state", "max_age", "client_id"]:
        del areq[attr]

    areq.lax = True
    req = srv.parse_authorization_request(query=areq.to_urlencoded())

    assert req.verify()
Example #9
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)
Example #10
0
def test_request_1():
    srv = Server()
    srv.keyjar = KEYJ

    areq = 'redirect_uri=https%3A%2F%2Fnode-openid-client.dev%2Fcb&request' \
           '=eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0' \
           '.eyJzdGF0ZSI6ImZvb2JhciIsImlzcyI6Inp2bWk4UGdJbURiOSIsImF1ZCI6Imh0dHBzOi8vcnAuY2VydGlmaWNhdGlvbi5vcGVuaWQubmV0OjgwODAvbm9kZS1vcGVuaWQtY2xpZW50L3JwLXJlcXVlc3RfdXJpLXVuc2lnbmVkIiwiY2xpZW50X2lkIjoienZtaThQZ0ltRGI5In0.&client_id=zvmi8PgImDb9&scope=openid&response_type=code'

    req = srv.parse_authorization_request(query=areq)

    assert req
Example #11
0
    def test_begin(self):
        srv = Server()
        srv.keyjar = SRVKEYS
        sid, location = self.consumer.begin("openid", "code")
        authreq = srv.parse_authorization_request(url=location)
        assert _eq(list(authreq.keys()),
                   ['state', 'max_age', 'claims', 'response_type', 'client_id',
                    'scope', 'redirect_uri'])

        assert authreq["state"] == sid
        assert authreq["scope"] == self.consumer.consumer_config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
Example #12
0
    def test_begin(self):
        srv = Server()
        srv.keyjar = SRVKEYS
        sid, location = self.consumer.begin("openid", "code")
        authreq = srv.parse_authorization_request(url=location)
        assert _eq(authreq.keys(), ['request', 'state', 'max_age', 'claims',
                                    'response_type', 'client_id', 'scope',
                                    'redirect_uri'])

        assert authreq["state"] == sid
        assert authreq["scope"] == self.consumer.consumer_config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
Example #13
0
    def test_begin_file(self, tmpdir):
        path = tmpdir.strpath
        external_path = "/exported"
        self.consumer.consumer_config["request_method"] = "file"
        self.consumer.consumer_config["temp_dir"] = path
        self.consumer.consumer_config["temp_path"] = external_path
        self.consumer.consumer_config["authz_page"] = "/authz"
        srv = Server()
        srv.keyjar = SRVKEYS

        sid, location = self.consumer.begin("openid",
                                            "code",
                                            path="http://localhost:8087")

        with responses.RequestsMock() as rsps:
            p = urlparse(self.consumer.request_uri)
            assert p.netloc == "localhost:8087"
            # Map the URL path to the local path
            relative_path = os.path.relpath(p.path, external_path)
            file_path = os.path.join(path, relative_path)

            with open(file_path) as f:
                rsps.add(
                    rsps.GET,
                    self.consumer.request_uri,
                    body=f.read(),
                    status=200,
                    content_type="application/urlencoded",
                )

            authreq = srv.parse_authorization_request(url=location)
            assert _eq(
                list(authreq.keys()),
                [
                    "max_age",
                    "state",
                    "redirect_uri",
                    "response_type",
                    "client_id",
                    "scope",
                    "claims",
                ],
            )

            assert authreq["state"] == sid
            assert authreq["scope"] == self.consumer.consumer_config["scope"]
            assert authreq["client_id"] == self.consumer.client_id
            assert authreq["redirect_uri"].startswith(
                "http://localhost:8087/authz")
Example #14
0
def test_request_duplicate_state():
    srv = Server()
    srv.keyjar = KEYJ

    areq = (
        "redirect_uri=https%3A%2F%2Fnode-openid-client.dev%2Fcb&state=barf"
        "&request"
        "=eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0"
        ".eyJzdGF0ZSI6ImZvb2JhciIsImlzcyI6Inp2bWk4UGdJbURiOSIsImF1ZCI6Imh0dHBzOi8v"
        "cnAuY2VydGlmaWNhdGlvbi5vcGVuaWQubmV0OjgwODAvbm9kZS1vcGVuaWQtY2xpZW50L3JwL"
        "XJlcXVlc3RfdXJpLXVuc2lnbmVkIiwiY2xpZW50X2lkIjoienZtaThQZ0ltRGI5In0.&"
        "client_id=zvmi8PgImDb9&scope=openid&response_type=code")

    req = srv.parse_authorization_request(query=areq)

    assert req["state"] == "foobar"
    assert req["redirect_uri"] == "https://node-openid-client.dev/cb"
Example #15
0
    def test_begin_file(self):
        self.consumer.config["request_method"] = "file"
        self.consumer.config["temp_dir"] = "./file"
        self.consumer.config["temp_path"] = "/tmp/"
        srv = Server(SRVKEYS)
        location = self.consumer.begin(BASE_ENVIRON, start_response)
        print location
        vkeys = {".":srv.keystore.get_verify_key()}
        authreq = srv.parse_authorization_request(url=location, keys=vkeys)
        print authreq.keys()
        assert _eq(authreq.keys(), ['state', 'redirect_uri',
                                    'response_type', 'client_id', 'scope',
                                    'request_uri'])

        assert authreq["state"] == self.consumer.state
        assert authreq["scope"] == self.consumer.config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
        assert authreq["redirect_uri"].startswith("http://localhost:8087/authz")
Example #16
0
    def test_begin_file(self, tmpdir):
        path = tmpdir.strpath
        self.consumer.consumer_config["request_method"] = "file"
        self.consumer.consumer_config["temp_dir"] = path
        self.consumer.consumer_config["temp_path"] = path
        self.consumer.consumer_config["authz_page"] = "/authz"
        srv = Server()
        srv.keyjar = SRVKEYS

        sid, location = self.consumer.begin("openid", "code",
                                            path="http://localhost:8087")
        authreq = srv.parse_authorization_request(url=location)
        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.consumer_config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
        assert authreq["redirect_uri"].startswith("http://localhost:8087/authz")
Example #17
0
    def test_begin(self):
        self.consumer.authorization_endpoint = "http://example.com/authorization"
        self.consumer.keystore.set_sign_key(rsapub, "rsa")
        self.consumer.keystore.set_verify_key(rsapub, "rsa")

        srv = Server(SRVKEYS)
        print "redirect_uris",self.consumer.redirect_uris
        print "config", self.consumer.config
        location = self.consumer.begin(BASE_ENVIRON, start_response)
        print location
        vkeys = {".":srv.keystore.get_verify_key()}
        authreq = srv.parse_authorization_request(url=location, keys=vkeys)
        print authreq.keys()
        assert _eq(authreq.keys(), ['request', 'state',
                                    'redirect_uri', 'response_type',
                                    'client_id', 'scope'])
        
        assert authreq["state"] == self.consumer.state
        assert authreq["scope"] == self.consumer.config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
Example #18
0
    def test_begin(self):
        self.consumer.authorization_endpoint = AUTHZ_URL
        self.consumer.keyjar[""].append(KC_RSA)
        #self.consumer.keyjar.set_sign_key(rsapub, "rsa")
        #self.consumer.keyjar.set_verify_key(rsapub, "rsa")

        srv = Server()
        srv.keyjar = SRVKEYS
        print "redirect_uris", self.consumer.redirect_uris
        print "config", self.consumer.config
        location = self.consumer.begin("openid", "code")
        print location
        authreq = srv.parse_authorization_request(url=location)
        print authreq.keys()
        assert _eq(authreq.keys(), ['request', 'state', 'max_age', 'claims',
                                    'response_type', 'client_id', 'scope',
                                    'redirect_uri'])

        assert authreq["state"] == self.consumer.state
        assert authreq["scope"] == self.consumer.config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
Example #19
0
    def test_begin(self):
        self.consumer.authorization_endpoint = AUTHZ_URL
        self.consumer.keyjar[""].append(KC_RSA)
        #self.consumer.keyjar.set_sign_key(rsapub, "rsa")
        #self.consumer.keyjar.set_verify_key(rsapub, "rsa")

        srv = Server()
        srv.keyjar = SRVKEYS
        print "redirect_uris", self.consumer.redirect_uris
        print "config", self.consumer.config
        location = self.consumer.begin("openid", "code")
        print location
        authreq = srv.parse_authorization_request(url=location)
        print authreq.keys()
        assert _eq(authreq.keys(), ['request', 'state', 'max_age', 'claims',
                                    'response_type', 'client_id', 'scope',
                                    'redirect_uri'])

        assert authreq["state"] == self.consumer.state
        assert authreq["scope"] == self.consumer.config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
Example #20
0
    def test_begin_file(self, tmpdir):
        path = tmpdir.strpath
        self.consumer.consumer_config["request_method"] = "file"
        self.consumer.consumer_config["temp_dir"] = path
        self.consumer.consumer_config["temp_path"] = path
        self.consumer.consumer_config["authz_page"] = "/authz"
        srv = Server()
        srv.keyjar = SRVKEYS

        sid, location = self.consumer.begin("openid",
                                            "code",
                                            path="http://localhost:8087")
        authreq = srv.parse_authorization_request(url=location)
        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.consumer_config["scope"]
        assert authreq["client_id"] == self.consumer.client_id
        assert authreq["redirect_uri"].startswith(
            "http://localhost:8087/authz")
class TestServer(object):
    @pytest.fixture(autouse=True)
    def create_server(self):
        self.srv = Server()
        self.srv.keyjar = KEYJ

    def test_parse_authz_req(self):
        ar = AuthorizationRequest(response_type=["code"], client_id="foobar",
                                  redirect_uri="http://foobar.example.com/oaclient",
                                  state="cold", nonce="NONCE", scope=["openid"])

        # query string
        uencq = ar.to_urlencoded()
        areq = self.srv.parse_authorization_request(query=uencq)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"

        # urlencoded
        urluenc = "https://example.com/authz?{}".format(uencq)
        areq = self.srv.parse_authorization_request(url=urluenc)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"

    def test_parse_authz_req_jwt(self):
        ar = AuthorizationRequest(response_type=["code"], client_id=CLIENT_ID,
                                  redirect_uri="http://foobar.example.com/oaclient",
                                  state="cold", nonce="NONCE", scope=["openid"])

        _keys = self.srv.keyjar.get_verify_key(owner=CLIENT_ID)
        _jwt = ar.to_jwt(key=_keys, algorithm="HS256")

        req = self.srv.parse_jwt_request(txt=_jwt)

        assert isinstance(req, AuthorizationRequest)
        assert req["response_type"] == ["code"]
        assert req["client_id"] == CLIENT_ID
        assert req["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert req["state"] == "cold"

    def test_server_parse_token_request(self):
        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()

        tr = self.srv.parse_token_request(body=uenc)

        assert isinstance(tr, AccessTokenRequest)
        assert _eq(tr.keys(),
                   ['code', 'redirect_uri', 'grant_type', 'client_id',
                    'extra'])
        assert tr["grant_type"] == "authorization_code"
        assert tr["code"] == "SplxlOBeZQQYbYS6WxSbIA"
        assert tr["extra"] == "foo"

    def test_server_parse_refresh_token_request(self):
        ratr = RefreshAccessTokenRequest(refresh_token="ababababab",
                                         client_id="Client_id")
        uenc = ratr.to_urlencoded()
        tr = self.srv.parse_refresh_token_request(body=uenc)

        assert isinstance(tr, RefreshAccessTokenRequest)
        assert tr["refresh_token"] == "ababababab"
        assert tr["client_id"] == "Client_id"

    def test_parse_urlencoded(self):
        loc = "http://example.com/userinfo?access_token=access_token"
        qdict = self.srv._parse_urlencoded(loc)
        assert qdict["access_token"] == ["access_token"]

    def test_parse_authorization_request(self):
        areq = AuthorizationRequest(response_type="code", client_id="client_id",
                                    redirect_uri="http://example.com/authz",
                                    scope=["openid"], state="state0",
                                    nonce="N0nce")
        qdict = self.srv.parse_authorization_request(query=areq.to_urlencoded())
        assert _eq(qdict.keys(), ['nonce', 'state', 'redirect_uri',
                                  'response_type', 'client_id', 'scope'])
        assert qdict["state"] == "state0"

    def test_parse_token_request(self):
        treq = AccessTokenRequest(code="code",
                                  redirect_uri="http://example.com/authz",
                                  client_id=CLIENT_ID,
                                  grant_type='authorization_code')
        qdict = self.srv.parse_token_request(body=treq.to_urlencoded())
        assert isinstance(qdict, AccessTokenRequest)
        assert _eq(qdict.keys(), ['code', 'redirect_uri', 'client_id',
                                  'grant_type'])
        assert qdict["client_id"] == CLIENT_ID
        assert qdict["code"] == "code"

    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"

    def test_parse_registration_request(self):
        regreq = RegistrationRequest(contacts=["*****@*****.**"],
                                     redirect_uris=[
                                         "http://example.org/jqauthz"],
                                     application_name="pacubar",
                                     client_id=CLIENT_ID,
                                     operation="register",
                                     application_type="web")

        request = self.srv.parse_registration_request(
                data=regreq.to_urlencoded())
        assert isinstance(request, RegistrationRequest)
        assert _eq(request.keys(), ['redirect_uris', 'contacts', 'client_id',
                                    'application_name', 'operation',
                                    'application_type', 'response_types'])
        assert request["application_name"] == "pacubar"
        assert request["operation"] == "register"

    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"

    def test_parse_check_session_request(self):
        csreq = CheckSessionRequest(
                id_token=IDTOKEN.to_jwt(key=KC_SYM_S.get(alg2keytype("HS256")),
                                        algorithm="HS256"))
        request = self.srv.parse_check_session_request(
                query=csreq.to_urlencoded())
        assert isinstance(request, IdToken)
        assert _eq(request.keys(), ['nonce', 'sub', 'aud', 'iss', 'exp', 'iat'])
        assert request["aud"] == ["client_1"]

    def test_parse_end_session_request(self):
        esreq = EndSessionRequest(
                id_token=IDTOKEN.to_jwt(key=KC_SYM_S.get(alg2keytype("HS256")),
                                        algorithm="HS256"),
                redirect_url="http://example.org/jqauthz",
                state="state0")

        request = self.srv.parse_end_session_request(
                query=esreq.to_urlencoded())
        assert isinstance(request, EndSessionRequest)
        assert _eq(request.keys(), ['id_token', 'redirect_url', 'state'])
        assert request["state"] == "state0"

        assert request["id_token"]["aud"] == ["client_1"]

    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"]

    def test_make_id_token(self):
        self.srv.keyjar["http://oic.example/rp"] = KC_RSA

        session = {"sub": "user0",
                   "client_id": "http://oic.example/rp"}
        issuer = "http://oic.example/idp"
        code = "abcdefghijklmnop"
        _idt = self.srv.make_id_token(session, loa="2", issuer=issuer,
                                      code=code, access_token="access_token")

        algo = "RS256"
        ckey = self.srv.keyjar.get_signing_key(alg2keytype(algo),
                                               session["client_id"])
        _signed_jwt = _idt.to_jwt(key=ckey, algorithm="RS256")

        idt = IdToken().from_jwt(_signed_jwt, keyjar=self.srv.keyjar)
        _jwt = JWT().unpack(_signed_jwt)

        lha = left_hash(code.encode("utf-8"),
                        func="HS" + _jwt.headers["alg"][-3:])
        assert lha == idt["c_hash"]

        atr = AccessTokenResponse(id_token=_signed_jwt,
                                  access_token="access_token",
                                  token_type="Bearer")
        atr["code"] = code
        assert atr.verify(keyjar=self.srv.keyjar)
Example #22
0
class TestServer(object):
    @pytest.fixture(autouse=True)
    def create_server(self):
        self.srv = Server()
        self.srv.keyjar = KEYJ

    def test_parse_authz_req(self):
        ar = AuthorizationRequest(
            response_type=["code"],
            client_id="foobar",
            redirect_uri="http://foobar.example.com/oaclient",
            state="cold",
            nonce="NONCE",
            scope=["openid"],
        )

        # query string
        uencq = ar.to_urlencoded()
        areq = self.srv.parse_authorization_request(query=uencq)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"

        # urlencoded
        urluenc = "https://example.com/authz?{}".format(uencq)
        areq = self.srv.parse_authorization_request(url=urluenc)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"

    def test_parse_authz_req_jwt(self):
        ar = AuthorizationRequest(
            response_type=["code"],
            client_id=CLIENT_ID,
            redirect_uri="http://foobar.example.com/oaclient",
            state="cold",
            nonce="NONCE",
            scope=["openid"],
        )

        _keys = self.srv.keyjar.get_verify_key(owner=CLIENT_ID)
        _jwt = ar.to_jwt(key=_keys, algorithm="HS256")

        req = self.srv.parse_jwt_request(txt=_jwt)

        assert isinstance(req, AuthorizationRequest)
        assert req["response_type"] == ["code"]
        assert req["client_id"] == CLIENT_ID
        assert req["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert req["state"] == "cold"

    def test_server_parse_token_request(self):
        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()

        tr = self.srv.parse_token_request(body=uenc)

        assert isinstance(tr, AccessTokenRequest)
        assert _eq(
            tr.keys(),
            ["code", "redirect_uri", "grant_type", "client_id", "extra"])
        assert tr["grant_type"] == "authorization_code"
        assert tr["code"] == "SplxlOBeZQQYbYS6WxSbIA"
        assert tr["extra"] == "foo"

    def test_server_parse_refresh_token_request(self):
        ratr = RefreshAccessTokenRequest(refresh_token="ababababab",
                                         client_id="Client_id")
        uenc = ratr.to_urlencoded()
        tr = self.srv.parse_refresh_token_request(body=uenc)

        assert isinstance(tr, RefreshAccessTokenRequest)
        assert tr["refresh_token"] == "ababababab"
        assert tr["client_id"] == "Client_id"

    def test_parse_urlencoded(self):
        loc = "http://example.com/userinfo?access_token=access_token"
        qdict = self.srv._parse_urlencoded(loc)
        assert qdict["access_token"] == ["access_token"]

    def test_parse_authorization_request(self):
        areq = AuthorizationRequest(
            response_type="code",
            client_id="client_id",
            redirect_uri="http://example.com/authz",
            scope=["openid"],
            state="state0",
            nonce="N0nce",
        )
        qdict = self.srv.parse_authorization_request(
            query=areq.to_urlencoded())
        assert _eq(
            qdict.keys(),
            [
                "nonce", "state", "redirect_uri", "response_type", "client_id",
                "scope"
            ],
        )
        assert qdict["state"] == "state0"

    def test_parse_token_request(self):
        treq = AccessTokenRequest(
            code="code",
            redirect_uri="http://example.com/authz",
            client_id=CLIENT_ID,
            grant_type="authorization_code",
        )
        qdict = self.srv.parse_token_request(body=treq.to_urlencoded())
        assert isinstance(qdict, AccessTokenRequest)
        assert _eq(qdict.keys(),
                   ["code", "redirect_uri", "client_id", "grant_type"])
        assert qdict["client_id"] == CLIENT_ID
        assert qdict["code"] == "code"

    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"

    def test_parse_registration_request(self):
        regreq = RegistrationRequest(
            contacts=["*****@*****.**"],
            redirect_uris=["http://example.org/jqauthz"],
            application_name="pacubar",
            client_id=CLIENT_ID,
            operation="register",
            application_type="web",
        )

        request = self.srv.parse_registration_request(
            data=regreq.to_urlencoded())
        assert isinstance(request, RegistrationRequest)
        assert _eq(
            request.keys(),
            [
                "redirect_uris",
                "contacts",
                "client_id",
                "application_name",
                "operation",
                "application_type",
                "response_types",
            ],
        )
        assert request["application_name"] == "pacubar"
        assert request["operation"] == "register"

    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"

    def test_parse_check_session_request(self):
        csreq = CheckSessionRequest(id_token=IDTOKEN.to_jwt(
            key=KC_SYM_S.get(alg2keytype("HS256")), algorithm="HS256"))
        request = self.srv.parse_check_session_request(
            query=csreq.to_urlencoded())
        assert isinstance(request, IdToken)
        assert _eq(request.keys(),
                   ["nonce", "sub", "aud", "iss", "exp", "iat"])
        assert request["aud"] == ["client_1"]

    def test_parse_end_session_request(self):
        esreq = EndSessionRequest(
            id_token=IDTOKEN.to_jwt(key=KC_SYM_S.get(alg2keytype("HS256")),
                                    algorithm="HS256"),
            redirect_url="http://example.org/jqauthz",
            state="state0",
        )

        request = self.srv.parse_end_session_request(
            query=esreq.to_urlencoded())
        assert isinstance(request, EndSessionRequest)
        assert _eq(request.keys(), ["id_token", "redirect_url", "state"])
        assert request["state"] == "state0"

        assert request["id_token"]["aud"] == ["client_1"]

    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"]

    def test_make_id_token(self):
        self.srv.keyjar["http://oic.example/idp"] = KC_RSA

        session = {"sub": "user0", "client_id": "http://oic.example/rp"}
        issuer = "http://oic.example/idp"
        code = "abcdefghijklmnop"
        _idt = self.srv.make_id_token(session,
                                      loa="2",
                                      issuer=issuer,
                                      code=code,
                                      access_token="access_token")

        algo = "RS256"
        ckey = self.srv.keyjar.get_signing_key(alg2keytype(algo), issuer)
        _signed_jwt = _idt.to_jwt(key=ckey, algorithm="RS256")

        idt = IdToken().from_jwt(_signed_jwt, keyjar=self.srv.keyjar)
        _jwt = JWT().unpack(_signed_jwt)

        lha = left_hash(code.encode("utf-8"),
                        func="HS" + _jwt.headers["alg"][-3:])
        assert lha == idt["c_hash"]

        atr = AccessTokenResponse(id_token=_signed_jwt,
                                  access_token="access_token",
                                  token_type="Bearer")
        atr["code"] = code
        assert atr.verify(keyjar=self.srv.keyjar)
Example #23
0
def test_parse_authorization_request():
    srv = Server()
    qdict = srv.parse_authorization_request(query=AREQ.to_urlencoded())
    assert _eq(qdict.keys(), ["nonce", "state", "redirect_uri", "response_type", "client_id", "scope"])
    assert qdict["state"] == "state0"
Example #24
0
def test_parse_authorization_request():
    srv = Server()
    qdict = srv.parse_authorization_request(query=AREQ.to_urlencoded())
    assert _eq(qdict.keys(), ['nonce', 'state', 'redirect_uri',
                              'response_type', 'client_id', 'scope'])
    assert qdict["state"] == "state0"