Beispiel #1
0
    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'])
Beispiel #2
0
    def test_json_serialize_deserialize(self):
        ar = AuthorizationRequest(response_type=["code"],
                                  client_id="foobar")
        jtxt = ar.serialize(method="json")
        ar2 = AuthorizationRequest().deserialize(jtxt, "json")

        assert ar == ar2
Beispiel #3
0
    def test_deserialize_urlencoded(self):
        ar = AuthorizationRequest(response_type=["code"],
                                  client_id="foobar")
        urlencoded = ar.to_urlencoded()
        ar2 = AuthorizationRequest().deserialize(urlencoded, "urlencoded")

        assert ar == ar2
Beispiel #4
0
    def test_parse_jwt_request(self):
        ar = AuthorizationRequest(
            response_type=["code"], client_id="foobar", redirect_uri="http://foobar.example.com/oaclient", state="cold"
        )

        self.srv.keyjar["foobar"] = KeyBundle(
            [
                {"kty": "oct", "key": "A1B2C3D4".encode("utf-8"), "use": "ver"},
                {"kty": "oct", "key": "A1B2C3D4".encode("utf-8"), "use": "sig"},
            ]
        )
        self.srv.keyjar[""] = KeyBundle(
            [
                {"kty": "oct", "key": "A1B2C3D4".encode("utf-8"), "use": "ver"},
                {"kty": "oct", "key": "A1B2C3D4".encode("utf-8"), "use": "sig"},
            ]
        )

        keys = self.srv.keyjar.get_signing_key(owner="foobar")
        _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"] == "foobar"
        assert req["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert req["state"] == "cold"
Beispiel #5
0
    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')]
Beispiel #6
0
    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
Beispiel #7
0
    def test_urlencoded_with_scope(self):
        ar = AuthorizationRequest(response_type=["code"], client_id="foobar",
                                  redirect_uri="http://foobar.example.com/oaclient",
                                  scope=["foo", "bar"], state="cold")

        ue = ar.to_urlencoded()
        assert query_string_compare(ue,
                                    "scope=foo+bar&state=cold&redirect_uri=http%3A%2F%2Ffoobar.example.com%2Foaclient&response_type=code&client_id=foobar")
Beispiel #8
0
    def test_urlencoded_resp_type_token(self):
        ar = AuthorizationRequest(response_type=["token"],
                                  client_id="s6BhdRkqt3",
                                  redirect_uri="https://client.example.com/cb",
                                  state="xyz")

        ue = ar.to_urlencoded()
        assert query_string_compare(ue,
                                    "state=xyz&redirect_uri=https%3A%2F%2Fclient.example.com%2Fcb&response_type=token&client_id=s6BhdRkqt3")
Beispiel #9
0
    def test_deserialize_urlencoded_multiple_params(self):
        ar = AuthorizationRequest(response_type=["code"],
                                  client_id="foobar",
                                  redirect_uri="http://foobar.example.com/oaclient",
                                  scope=["foo", "bar"], state="cold")
        urlencoded = ar.to_urlencoded()
        ar2 = AuthorizationRequest().deserialize(urlencoded, "urlencoded")

        assert ar == ar2
Beispiel #10
0
    def test_req_json_serialize(self):
        ar = AuthorizationRequest(response_type=["code"],
                                  client_id="foobar")

        js_obj = json.loads(ar.serialize(method="json"))
        expected_js_obj = {
            "response_type": "code",
            "client_id": "foobar"
        }
        assert js_obj == expected_js_obj
Beispiel #11
0
    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_authorization_endpoint_faulty_redirect_uri_nwalker(self):
        bib = {"scope": ["openid"],
               "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
               "redirect_uri": " https://example.com.evil.com",
               # faulty redirect uri
               "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"
Beispiel #13
0
    def test_multiple_response_types_urlencoded(self):
        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"])
Beispiel #14
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"])
Beispiel #15
0
    def test_json_resp_type_token(self):
        ar = AuthorizationRequest(response_type=["token"],
                                  client_id="s6BhdRkqt3",
                                  redirect_uri="https://client.example.com/cb",
                                  state="xyz")

        ue_obj = json.loads(ar.serialize(method="json"))
        expected_ue_obj = {
            "state": "xyz",
            "redirect_uri": "https://client.example.com/cb",
            "response_type": "token",
            "client_id": "s6BhdRkqt3"
        }
        assert ue_obj == expected_ue_obj
Beispiel #16
0
    def test_json_multiple_params(self):
        ar = AuthorizationRequest(response_type=["code"],
                                  client_id="foobar",
                                  redirect_uri="http://foobar.example.com/oaclient",
                                  state="cold")

        ue_obj = json.loads(ar.serialize(method="json"))
        expected_ue_obj = {
            "response_type": "code",
            "state": "cold",
            "redirect_uri": "http://foobar.example.com/oaclient",
            "client_id": "foobar"
        }
        assert ue_obj == expected_ue_obj
    def test_urlencoded_with_scope(self):
        ar = AuthorizationRequest(
            response_type=["code"],
            client_id="foobar",
            redirect_uri="http://foobar.example.com/oaclient",
            scope=["foo", "bar"],
            state="cold",
        )

        ue = ar.to_urlencoded()
        assert query_string_compare(
            ue,
            "scope=foo+bar&state=cold&redirect_uri=http%3A%2F%2Ffoobar.example.com%2Foaclient&"
            "response_type=code&client_id=foobar",
        )
Beispiel #18
0
    def test_json_multiple_params(self):
        ar = AuthorizationRequest(
            response_type=["code"],
            client_id="foobar",
            redirect_uri="http://foobar.example.com/oaclient",
            state="cold")

        ue_obj = json.loads(ar.serialize(method="json"))
        expected_ue_obj = {
            "response_type": "code",
            "state": "cold",
            "redirect_uri": "http://foobar.example.com/oaclient",
            "client_id": "foobar"
        }
        assert ue_obj == expected_ue_obj
Beispiel #19
0
    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"
Beispiel #20
0
    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_authorization_endpoint_wronge_response_mode(self):
        bib = {
            "scope": ["openid"],
            "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
            "redirect_uri": "http://example.com",
            "response_type": ["code"],
            "response_mode": "fragment",
            "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"
Beispiel #22
0
    def duplicate(self, sinfo):
        _dic = copy.copy(sinfo)
        areq = AuthorizationRequest().from_json(_dic["authzreq"])
        sid = self.token_factory["code"].key(user=_dic["sub"], areq=areq)

        _dic["code"] = self.token_factory["code"](sid=sid, sinfo=sinfo)
        _dic["code_used"] = False

        for key in [
                "access_token",
                "access_token_scope",
                "oauth_state",
                "token_type",
                "token_expires_at",
                "expires_in",
                "client_id_issued_at",
                "id_token",
                "oidreq",
                "refresh_token",
        ]:
            try:
                del _dic[key]
            except KeyError:
                pass

        self._db[sid] = _dic
        self._db.update(sid, "sub", _dic["sub"])

        return sid
Beispiel #23
0
    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.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="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')]
Beispiel #24
0
    def test_json_resp_type_token(self):
        ar = AuthorizationRequest(
            response_type=["token"],
            client_id="s6BhdRkqt3",
            redirect_uri="https://client.example.com/cb",
            state="xyz",
        )

        ue_obj = json.loads(ar.serialize(method="json"))
        expected_ue_obj = {
            "state": "xyz",
            "redirect_uri": "https://client.example.com/cb",
            "response_type": "token",
            "client_id": "s6BhdRkqt3",
        }
        assert ue_obj == expected_ue_obj
Beispiel #25
0
    def test_json_serizalize_deserialize_multiple_params(self):
        argv = {"scope": ["openid"],
                "state": "id-b0be8bb64118c3ec5f70093a1174b039",
                "redirect_uri": "http://localhost:8087authz",
                "response_type": ["code"],
                "client_id": "a1b2c3"}

        arq = AuthorizationRequest(**argv)
        jstr = arq.serialize(method="json")
        jarq = AuthorizationRequest().deserialize(jstr, "json")

        assert jarq["scope"] == ["openid"]
        assert jarq["response_type"] == ["code"]
        assert jarq["redirect_uri"] == "http://localhost:8087authz"
        assert jarq["state"] == "id-b0be8bb64118c3ec5f70093a1174b039"
        assert jarq["client_id"] == "a1b2c3"
Beispiel #26
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='<REDACTED>',
                                  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'])
Beispiel #27
0
    def test_authorization_endpoint_faulty_redirect_uri_nwalker(self):
        bib = {
            "scope": ["openid"],
            "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
            "redirect_uri": " https://example.com.evil.com",
            # faulty redirect uri
            "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"
Beispiel #28
0
    def test_token_endpoint_password(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",
            "token_endpoint_auth_method": "client_secret_basic",
        }
        areq = ROPCAccessTokenRequest(grant_type="password",
                                      username="******",
                                      password="******")
        authn = "Basic Y2xpZW50Mjp2ZXJ5c2VjcmV0="
        resp = self.provider.token_endpoint(request=areq.to_urlencoded(),
                                            authn=authn)
        parsed = TokenErrorResponse().from_json(resp.message)
        assert parsed["error"] == "unsupported_grant_type"
    def test_urlencoded_invalid_scope(self):
        args = {"response_type": [10], "client_id": "foobar",
                "redirect_uri": "http://foobar.example.com/oaclient",
                "scope": ["foo", "bar"], "state": "cold"}

        with pytest.raises(DecodeError):
            AuthorizationRequest(**args)
Beispiel #30
0
    def test_urlencoded_deserialize_state(self):
        txt = "scope=foo+bar&state=-11&redirect_uri=http%3A%2F%2Ffoobar" \
              ".example.com%2Foaclient&response_type=code&" \
              "client_id=foobar"

        ar = AuthorizationRequest().deserialize(txt, "urlencoded")
        assert ar["state"] == "-11"
    def test_json_serizalize_deserialize_multiple_params(self):
        argv = {"scope": ["openid"],
                "state": "id-b0be8bb64118c3ec5f70093a1174b039",
                "redirect_uri": "http://localhost:8087authz",
                "response_type": ["code"],
                "client_id": "a1b2c3"}

        arq = AuthorizationRequest(**argv)
        jstr = arq.serialize(method="json")
        jarq = AuthorizationRequest().deserialize(jstr, "json")

        assert jarq["scope"] == ["openid"]
        assert jarq["response_type"] == ["code"]
        assert jarq["redirect_uri"] == "http://localhost:8087authz"
        assert jarq["state"] == "id-b0be8bb64118c3ec5f70093a1174b039"
        assert jarq["client_id"] == "a1b2c3"
Beispiel #32
0
    def test_urlencoded_deserialize_response_type(self):
        txt = "scope=openid&state=id-6a3fc96caa7fd5cb1c7d00ed66937134&" \
              "redirect_uri=http%3A%2F%2Flocalhost%3A8087authz&response_type=code&client_id=a1b2c3"

        ar = AuthorizationRequest().deserialize(txt, "urlencoded")
        assert ar["scope"] == ["openid"]
        assert ar["response_type"] == ["code"]
Beispiel #33
0
    def test_code_grant_type_used(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id='client1',
                                       response_type="code",
                                       scope=["openid"])

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

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

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt)
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr['error'] == "invalid_grant"
Beispiel #34
0
    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.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="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')
        with LogCapture(level=logging.DEBUG) as logcap:
            resp = self.provider.token_endpoint(request=areq.to_urlencoded())

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

        expected = (
            'token_request: code=<REDACTED>&client_secret=<REDACTED>&grant_type=authorization_code'
            '&client_id=client1&redirect_uri=http%3A%2F%2Fexample.com%2Fauthz')
        assert _eq(parse_qs(logcap.records[1].msg[15:]), parse_qs(expected[15:]))
        expected = {u'code': '<REDACTED>', u'client_secret': '<REDACTED>',
                    u'redirect_uri': u'http://example.com/authz',
                    u'client_id': 'client1',
                    u'grant_type': 'authorization_code'}
        # Don't try this at home, kids!
        # We have to eval() to a dict here because otherwise the arbitrary
        # ordering of the string causes the test to fail intermittently.
        assert _eq(eval(logcap.records[2].msg[4:]), expected)
        assert _eq(logcap.records[3].msg, 'Verified Client ID: client1')
        expected = {'redirect_uri': u'http://example.com/authz',
                    'client_secret': '<REDACTED>',
                    'code': u'<REDACTED>', 'client_id': 'client1',
                    'grant_type': 'authorization_code'}
        assert eval(logcap.records[4].msg[20:]) == expected
        expected = {'code': '<REDACTED>', 'authzreq': '', 'sub': 'sub',
                    'access_token': '<REDACTED>',
                    'token_type': 'Bearer',
                    'redirect_uri': 'http://example.com/authz',
                    'code_used': True, 'client_id': 'client1',
                    'oauth_state': 'token',
                    'refresh_token': '<REDACTED>', 'access_token_scope': '?'}
        assert _eq(eval(logcap.records[5].msg[7:]), expected)
        expected = {'access_token': u'<REDACTED>', 'token_type': 'Bearer',
                    'refresh_token': '<REDACTED>'}
        assert _eq(eval(logcap.records[6].msg[21:]), expected)
Beispiel #35
0
    def test_response_types(self, response_types):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1",
                                       response_type='id_token token')

        self.provider.cdb = {
            "client1": {
                "client_secret": "hemlighet",
                "redirect_uris": [("http://example.com/authz", None)],
                'token_endpoint_auth_method': 'client_secret_post',
                'response_types': response_types
            }
        }

        res = self.provider.auth_init(authreq.to_urlencoded())
        assert isinstance(res, dict) and "areq" in res
Beispiel #36
0
    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

        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
def test_provider_authorization_endpoint():
    provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ,
                        verify_client)

    bib = {"scope": ["openid"],
           "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
           "redirect_uri": "http://localhost:8087authz",
           "response_type": ["code"],
           "client_id": "a1b2c3"}

    arq = AuthorizationRequest(**bib)

    QUERY_STRING = arq.to_urlencoded()

    resp = provider.authorization_endpoint(request=QUERY_STRING)

    assert isinstance(resp, Response)
    def test_response_types(self, response_types):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1",
                                       response_type='id_token token')

        self.provider.cdb = {
            "client1": {
                "client_secret": "hemlighet",
                "redirect_uris": [("http://example.com/authz", None)],
                'token_endpoint_auth_method': 'client_secret_post',
                'response_types': response_types
            }
        }

        res = self.provider.auth_init(authreq.to_urlencoded())
        assert isinstance(res, dict) and "areq" in res
Beispiel #39
0
def test_provider_authorization_endpoint():
    provider = Provider("pyoicserv", sdb.SessionDB(), CDB, FUNCTIONS)

    bib = {"scope": ["openid"],
           "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
           "redirect_uri": "http://localhost:8087authz",
           "response_type": ["code"],
           "client_id": "a1b2c3"}

    arq = AuthorizationRequest(**bib)

    environ = BASE_ENVIRON.copy()
    environ["QUERY_STRING"] = arq.to_urlencoded()

    resp = provider.authorization_endpoint(environ, start_response)

    print resp
    assert resp[0].startswith("FORM with")
Beispiel #40
0
    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"
Beispiel #41
0
    def test_parse_jwt_request(self):
        ar = AuthorizationRequest(
            response_type=["code"],
            client_id="foobar",
            redirect_uri="http://foobar.example.com/oaclient",
            state="cold",
        )

        self.srv.keyjar["foobar"] = KeyBundle([
            {
                "kty": "oct",
                "key": "A1B2C3D4".encode("utf-8"),
                "use": "ver"
            },
            {
                "kty": "oct",
                "key": "A1B2C3D4".encode("utf-8"),
                "use": "sig"
            },
        ])
        self.srv.keyjar[""] = KeyBundle([
            {
                "kty": "oct",
                "key": "A1B2C3D4".encode("utf-8"),
                "use": "ver"
            },
            {
                "kty": "oct",
                "key": "A1B2C3D4".encode("utf-8"),
                "use": "sig"
            },
        ])

        keys = self.srv.keyjar.get_signing_key(owner="foobar")
        _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"] == "foobar"
        assert req["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert req["state"] == "cold"
Beispiel #42
0
    def begin(self, environ, server_env, start_response, session):

        state = rndstr()
        #server_env["CACHE"].alternate_sid(sid, state)
        callback = server_env["base_url"] + self.opKey

        # redirect the user to facebook for the authentication
        ar = AuthorizationRequest().from_dict({"client_id": self.client_id,
                                               "redirect_uri": callback,
                                               "state": state,
                                               "response_type": ["code"],
                                               "scope": self._scope})
        url = ar.request(self.extra["authorization_endpoint"])
        logger.info("[OAuth2] callback url: %s" % url)
        #if cookie:
        #    resp = Redirect(url, headers=[cookie])
        #else:
        resp = Redirect(url)
        return resp(environ, start_response)
Beispiel #43
0
def test_provider_authorization_endpoint():
    provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ,
                        verify_client)

    bib = {
        "scope": ["openid"],
        "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
        "redirect_uri": "http://localhost:8087authz",
        "response_type": ["code"],
        "client_id": "a1b2c3"
    }

    arq = AuthorizationRequest(**bib)

    QUERY_STRING = arq.to_urlencoded()

    resp = provider.authorization_endpoint(request=QUERY_STRING)

    assert isinstance(resp, Response)
Beispiel #44
0
    def test_response_types_fail(self, response_types):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1",
                                       response_type='code')

        self.provider.cdb = {
            "client1": {
                "client_secret": "hemlighet",
                "redirect_uris": [("http://example.com/authz", None)],
                'token_endpoint_auth_method': 'client_secret_post',
                'response_types': response_types
            }
        }

        res = self.provider.auth_init(authreq.to_urlencoded())
        assert isinstance(res, Response)

        _res = json.loads(res.message)
        assert _res['error'] == 'invalid_request'
    def test_response_types_fail(self, response_types):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1",
                                       response_type='code')

        self.provider.cdb = {
            "client1": {
                "client_secret": "hemlighet",
                "redirect_uris": [("http://example.com/authz", None)],
                'token_endpoint_auth_method': 'client_secret_post',
                'response_types': response_types
            }
        }

        res = self.provider.auth_init(authreq.to_urlencoded())
        assert isinstance(res, Response)

        _res = json.loads(res.message)
        assert _res['error'] == 'invalid_request'
Beispiel #46
0
    def begin(self, environ, server_env, start_response, cookie,
              sid, info):

        state = rndstr()
        server_env["CACHE"].alternate_sid(sid, state)
        callback = server_env["base_url"] + self.social_endpoint

        # redirect the user to facebook for the authentication
        ar = AuthorizationRequest().from_dict({"client_id": self.client_id,
                                               "redirect_uri": callback,
                                               "state": state,
                                               "response_type": ["code"],
                                               "scope": self._scope})
        url = ar.request(self.extra["authorization_endpoint"])
        logger.info("[OAuth2] callback url: %s" % url)
        if cookie:
            resp = Redirect(url, headers=[cookie])
        else:
            resp = Redirect(url)
        return resp(environ, start_response)
    def test_load_dict(self):
        bib = {"scope": ["openid"],
               "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
               "redirect_uri": "http://localhost:8087authz",
               "response_type": ["code"],
               "client_id": "a1b2c3"}

        arq = AuthorizationRequest(**bib)

        assert arq["scope"] == bib["scope"]
        assert arq["response_type"] == bib["response_type"]
        assert arq["redirect_uri"] == bib["redirect_uri"]
        assert arq["state"] == bib["state"]
        assert arq["client_id"] == bib["client_id"]
Beispiel #48
0
    def test_parse_authz_req(self):
        ar = AuthorizationRequest(
            response_type=["code"], client_id="foobar", redirect_uri="http://foobar.example.com/oaclient", state="cold"
        )

        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"

        urluenc = "%s?%s" % ("https://example.com/authz", 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_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"])
    def test_multiple_response_types_urlencoded(self):
        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"])
Beispiel #51
0
def test_token_endpoint():
    provider = Provider("pyoicserv",
                        sdb.SessionDB(),
                        CDB,
                        AUTHN_BROKER,
                        AUTHZ,
                        verify_client,
                        symkey=rndstr(16))

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

    _sdb = provider.sdb
    sid = _sdb.token.key(user="******", areq=authreq)
    access_grant = _sdb.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="client1",
        client_secret="hemlighet",
    )

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

    print atr.keys()
    assert _eq(atr.keys(),
               ['access_token', 'expires_in', 'token_type', 'refresh_token'])
Beispiel #52
0
    def test_token_endpoint_ok_state(self):
        authreq = AuthorizationRequest(
            state="state",
            redirect_uri="http://example.com/authz",
            client_id="client1",
            response_type="code",
            scope=["openid"],
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        ae = AuthnEvent("user", "salt")
        _sdb[sid] = {
            "oauth_state": "authz",
            "authn_event": ae.to_json(),
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "state": "state",
            "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="client1",
            redirect_uri="http://example.com/authz",
            client_secret="hemlighet",
            grant_type="authorization_code",
            state="state",
        )

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt)
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert atr["token_type"] == "Bearer"
Beispiel #53
0
    def test_token_endpoint_other(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",
            'token_endpoint_auth_method': 'client_secret_basic',
        }
        areq = Message(grant_type='some_other')
        authn = 'Basic Y2xpZW50Mjp2ZXJ5c2VjcmV0='
        with pytest.raises(UnSupported):
            self.provider.token_endpoint(request=areq.to_urlencoded(), authn=authn)
Beispiel #54
0
    def test_token_endpoint_bad_redirect_uri(self):
        authreq = AuthorizationRequest(
            state="state",
            redirect_uri="http://example.com/authz",
            client_id="client1",
            response_type="code",
            scope=["openid"],
        )

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

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

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt)
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr["error"] == "unauthorized_client"
Beispiel #55
0
 def test_urlencoded_missing_required(self):
     ar = AuthorizationRequest(response_type=["code"])
     with pytest.raises(MissingRequiredAttribute):
         ar.verify()
Beispiel #56
0
 def test_verify(self):
     query = 'redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fauthz&response_type=code&client_id=0123456789'
     ar = AuthorizationRequest().deserialize(query, "urlencoded")
     assert ar.verify()
Beispiel #57
0
    def authorization_endpoint(self, request="", cookie="", authn="", **kwargs):
        """ The AuthorizationRequest endpoint

        :param request: The client request
        """

        logger.debug("Request: '%s'" % request)
        # Same serialization used for GET and POST
        try:
            areq = self.server.parse_authorization_request(query=request)
        except MissingRequiredAttribute, err:
            logger.debug("%s" % err)
            return self._error("invalid_request", "%s" % err)
        except KeyError:
            areq = AuthorizationRequest().deserialize(request, "urlencoded")
            # verify the redirect_uri
            try:
                self.get_redirect_uri(areq)
            except (RedirectURIError, ParameterError), err:
                return self._error("invalid_request", "%s" % err)
        except Exception, err:
            message = traceback.format_exception(*sys.exc_info())
            logger.error(message)
            logger.debug("Bad request: %s (%s)" % (err, err.__class__.__name__))
            return BadRequest("%s" % err)

        if not areq:
            logger.debug("No AuthzRequest")
            return self._error("invalid_request", "No parsable AuthzRequest")
Beispiel #58
0
 def test_authz_req_urlencoded(self):
     ar = AuthorizationRequest(response_type=["code"], client_id="foobar")
     ue = ar.to_urlencoded()
     assert query_string_compare(ue, "response_type=code&client_id=foobar")