Ejemplo n.º 1
0
    def test_decode_access_token(self):
        """decode_access_token() does a base64 decode of the JWT auth token data to get profile information"""
        uaac = UAAClient("http://example.com", "foo", False)
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImxlZ2FjeS10b2tlbi1rZXkiLCJ0eXAiOiJKV1QifQ.eyJqdGkiOiI5OWNiZGM4ZGE2MTg0ZmMyODgxYzUwYWNhYzJjZTJjNiIsInN1YiI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiY2xpZW50cy5yZWFkIiwicGFzc3dvcmQud3JpdGUiLCJjbGllbnRzLnNlY3JldCIsImNsaWVudHMud3JpdGUiLCJ1YWEuYWRtaW4iLCJzY2ltLndyaXRlIiwic2NpbS5yZWFkIl0sInNjb3BlIjpbImNsaWVudHMucmVhZCIsInBhc3N3b3JkLndyaXRlIiwiY2xpZW50cy5zZWNyZXQiLCJjbGllbnRzLndyaXRlIiwidWFhLmFkbWluIiwic2NpbS53cml0ZSIsInNjaW0ucmVhZCJdLCJjbGllbnRfaWQiOiJhZG1pbiIsImNpZCI6ImFkbWluIiwiYXpwIjoiYWRtaW4iLCJncmFudF90eXBlIjoiY2xpZW50X2NyZWRlbnRpYWxzIiwicmV2X3NpZyI6ImQ1NjA4NGZkIiwiaWF0IjoxNDc4Mjc5NTM3LCJleHAiOjE0NzgzMjI3MzcsImlzcyI6Imh0dHBzOi8vdWFhLmNsb3VkLmdvdi9vYXV0aC90b2tlbiIsInppZCI6InVhYSIsImF1ZCI6WyJzY2ltIiwicGFzc3dvcmQiLCJjbGllbnRzIiwidWFhIiwiYWRtaW4iXX0.uJABuxWIc3p-p3zJol1i2BHBfDkKXnpIcCFbOvDg8WGdbrufhFZjk78uRiPk8sw9I0reUbjyLeo0-0Eqg-x49pVaNpNeheDYaz2oc_CMO13MPXlCtVHdEGnq4e6NV21wxTMVmrLhP0QscDRctnITUY7c-ywMsUrXgv7VFj-9GPZjfr-PyG01OxStrAfe06kTXKbEHIHFgfidrDYA_pTnPO1LPz5HllVQUkAdlIIEx6VshBW6_4l2Sm0nof3cVOxqMUUB6xLSJARfudPrCmFeUIdnICl85T00-1kOe2YUMm9xRHS4hnBYbM6IU5JDmzvnz3ANEM2Uzmzv9JzkJjboIQ"  # noqa: E501
        profile = uaac.decode_access_token(token)

        assert "scope" in profile
        assert "exp" in profile
Ejemplo n.º 2
0
    def test_decode_access_token(self):
        """decode_access_token() does a base64 decode of the JWT auth token data to get profile information"""
        uaac = UAAClient('http://example.com', 'foo', False)
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImxlZ2FjeS10b2tlbi1rZXkiLCJ0eXAiOiJKV1QifQ.eyJqdGkiOiI5OWNiZGM4ZGE2MTg0ZmMyODgxYzUwYWNhYzJjZTJjNiIsInN1YiI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiY2xpZW50cy5yZWFkIiwicGFzc3dvcmQud3JpdGUiLCJjbGllbnRzLnNlY3JldCIsImNsaWVudHMud3JpdGUiLCJ1YWEuYWRtaW4iLCJzY2ltLndyaXRlIiwic2NpbS5yZWFkIl0sInNjb3BlIjpbImNsaWVudHMucmVhZCIsInBhc3N3b3JkLndyaXRlIiwiY2xpZW50cy5zZWNyZXQiLCJjbGllbnRzLndyaXRlIiwidWFhLmFkbWluIiwic2NpbS53cml0ZSIsInNjaW0ucmVhZCJdLCJjbGllbnRfaWQiOiJhZG1pbiIsImNpZCI6ImFkbWluIiwiYXpwIjoiYWRtaW4iLCJncmFudF90eXBlIjoiY2xpZW50X2NyZWRlbnRpYWxzIiwicmV2X3NpZyI6ImQ1NjA4NGZkIiwiaWF0IjoxNDc4Mjc5NTM3LCJleHAiOjE0NzgzMjI3MzcsImlzcyI6Imh0dHBzOi8vdWFhLmNsb3VkLmdvdi9vYXV0aC90b2tlbiIsInppZCI6InVhYSIsImF1ZCI6WyJzY2ltIiwicGFzc3dvcmQiLCJjbGllbnRzIiwidWFhIiwiYWRtaW4iXX0.uJABuxWIc3p-p3zJol1i2BHBfDkKXnpIcCFbOvDg8WGdbrufhFZjk78uRiPk8sw9I0reUbjyLeo0-0Eqg-x49pVaNpNeheDYaz2oc_CMO13MPXlCtVHdEGnq4e6NV21wxTMVmrLhP0QscDRctnITUY7c-ywMsUrXgv7VFj-9GPZjfr-PyG01OxStrAfe06kTXKbEHIHFgfidrDYA_pTnPO1LPz5HllVQUkAdlIIEx6VshBW6_4l2Sm0nof3cVOxqMUUB6xLSJARfudPrCmFeUIdnICl85T00-1kOe2YUMm9xRHS4hnBYbM6IU5JDmzvnz3ANEM2Uzmzv9JzkJjboIQ"  # noqa: E501
        profile = uaac.decode_access_token(token)

        assert 'scope' in profile
        assert 'exp' in profile
Ejemplo n.º 3
0
    def test_get_user(self):
        """get_user() makes a GET request to /Users/<id>"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.get_user('foo')
        m.assert_called_with(urljoin('/Users', 'foo'), 'GET')
Ejemplo n.º 4
0
    def test_get_user(self):
        """get_user() makes a GET request to /Users/<id>"""

        uaac = UAAClient("http://example.com", "foo", False)
        m = Mock()
        uaac._request = m

        uaac.get_user("foo")
        m.assert_called_with(urljoin("/Users", "foo"), "GET")
Ejemplo n.º 5
0
    def test_get_user(self):
        """get_user() makes a GET request to /Users/<id>"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.get_user('foo')
        m.assert_called_with(urljoin('/Users', 'foo'), 'GET')
Ejemplo n.º 6
0
    def oauth_login():
        """Called at the end of the oauth flow.  We'll receive an auth code from UAA and use it to
        retrieve a bearer token that we can use to actually do stuff
        """
        logging.info(request.referrer)
        is_invitation = (request.referrer
                         and request.referrer.find("invitations/accept") != 1)
        if is_invitation and "code" not in request.args:
            return redirect(url_for("first_login"))

        try:

            # connect a client with no token
            uaac = UAAClient(
                app.config["UAA_BASE_URL"],
                None,
                verify_tls=app.config["UAA_VERIFY_TLS"],
            )

            # auth with our client secret and the code they gave us
            token = uaac.oauth_token(
                request.args["code"],
                app.config["UAA_CLIENT_ID"],
                app.config["UAA_CLIENT_SECRET"],
            )

            # if it's valid, but missing the scope we need, bail
            if "scim.invite" not in token["scope"].split(" "):
                raise RuntimeError(
                    "Valid oauth authentication but missing the scim.invite scope.  Scopes: {0}"
                    .format(token["scope"]))

            # make flask expire our session for us, by expiring it shortly before the token expires
            session.permanent = True
            app.permanent_session_lifetime = timedelta(
                seconds=token["expires_in"] - 30)

            # stash the stuff we care about
            session["UAA_TOKEN"] = token["access_token"]
            session["UAA_TOKEN_SCOPES"] = token["scope"].split(" ")
            if is_invitation:
                return redirect(url_for("first_login"))
            endpoint = session.pop("_endpoint", None)
            if not endpoint:
                endpoint = "index"
            logging.info(endpoint)
            return redirect(url_for(endpoint))
        except UAAError:
            logging.exception(
                "An invalid authorization_code was received from UAA")
            return render_template("error/token_validation.html"), 401
        except RuntimeError:
            logging.exception("Token validated but had wrong scope")
            return render_template("error/missing_scope.html"), 403
Ejemplo n.º 7
0
    def test_change_password(self):
        """change_password() makes a PUT request to /Users/<id>/password"""

        uaac = UAAClient("http://example.com", "foo", False)
        m = Mock()
        uaac._request = m

        uaac.change_password("foo", "bar", "baz")

        m.assert_called_with(
            "/Users/foo/password", "PUT", body={"oldPassword": "******", "password": "******"}
        )
Ejemplo n.º 8
0
    def test_put_user(self):
        """put_user() makes a PUT request to /Users/<id> with appropriate headers"""

        uaac = UAAClient("http://example.com", "foo", False)
        m = Mock()
        uaac._request = m

        user = {"id": "foo", "meta": {"version": "123"}}

        uaac.put_user(user)

        m.assert_called_with(
            urljoin("/Users", "foo"), "PUT", body=user, headers={"If-Match": "123"}
        )
Ejemplo n.º 9
0
    def oauth_login():
        """Called at the end of the oauth flow.  We'll receive an auth code from UAA and use it to
        retrieve a bearer token that we can use to actually do stuff
        """
        logging.info(request.referrer)
        is_invitation = request.referrer and request.referrer.find(
            'invitations/accept') != 1
        if is_invitation and 'code' not in request.args:
            return redirect(url_for('first_login'))

        try:

            # connect a client with no token
            uaac = UAAClient(app.config['UAA_BASE_URL'],
                             None,
                             verify_tls=app.config['UAA_VERIFY_TLS'])

            # auth with our client secret and the code they gave us
            token = uaac.oauth_token(request.args['code'],
                                     app.config['UAA_CLIENT_ID'],
                                     app.config['UAA_CLIENT_SECRET'])

            # if it's valid, but missing the scope we need, bail
            if 'scim.invite' not in token['scope'].split(' '):
                raise RuntimeError(
                    'Valid oauth authentication but missing the scim.invite scope.  Scopes: {0}'
                    .format(token['scope']))

            # make flask expire our session for us, by expiring it shortly before the token expires
            session.permanent = True
            app.permanent_session_lifetime = timedelta(
                seconds=token['expires_in'] - 30)

            # stash the stuff we care about
            session['UAA_TOKEN'] = token['access_token']
            session['UAA_TOKEN_SCOPES'] = token['scope'].split(' ')
            if is_invitation:
                return redirect(url_for('first_login'))
            endpoint = session.pop('_endpoint', None)
            if not endpoint:
                endpoint = 'index'
            logging.info(endpoint)
            return redirect(url_for(endpoint))
        except UAAError:
            logging.exception(
                'An invalid authorization_code was received from UAA')
            return render_template('error/token_validation.html'), 401
        except RuntimeError:
            logging.exception('Token validated but had wrong scope')
            return render_template('error/missing_scope.html'), 403
Ejemplo n.º 10
0
    def test_change_password(self):
        """change_password() makes a PUT request to /Users/<id>/password"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.change_password('foo', 'bar', 'baz')

        m.assert_called_with(
            '/Users/foo/password',
            'PUT',
            body={
                'oldPassword': '******',
                'password': '******'
            }
        )
Ejemplo n.º 11
0
    def test_change_password(self):
        """change_password() makes a PUT request to /Users/<id>/password"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.change_password('foo', 'bar', 'baz')

        m.assert_called_with(
            '/Users/foo/password',
            'PUT',
            body={
                'oldPassword': '******',
                'password': '******'
            }
        )
Ejemplo n.º 12
0
    def test_invite_users(self):
        """invite_users() makes a PUT request to /invite_users<id>"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        email = '*****@*****.**'
        redirect_uri = 'http://www.example.com'

        uaac.invite_users(email, redirect_uri)

        m.assert_called_with(
            '/invite_users',
            'POST',
            body={'emails': [email]},
            params={'redirect_uri': redirect_uri}
        )
Ejemplo n.º 13
0
    def test_users_with_token(self):
        """invite_users() makes a PUT request to /invite_users<id>"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        email = '*****@*****.**'
        redirect_uri = 'http://www.example.com'

        uaac.invite_users(email, redirect_uri, token="foobar")

        m.assert_called_with(
            '/invite_users',
            'POST',
            body={'emails': [email]},
            headers={'Authorization': 'Bearer foobar'},
            params={'redirect_uri': redirect_uri}
        )
Ejemplo n.º 14
0
    def test_users_with_token(self):
        """invite_users() makes a PUT request to /invite_users<id>"""

        uaac = UAAClient("http://example.com", "foo", False)
        m = Mock()
        uaac._request = m

        email = "*****@*****.**"
        redirect_uri = "http://www.example.com"

        uaac.invite_users(email, redirect_uri, token="foobar")

        m.assert_called_with(
            "/invite_users",
            "POST",
            body={"emails": [email]},
            headers={"Authorization": "Bearer foobar"},
            params={"redirect_uri": redirect_uri},
        )
Ejemplo n.º 15
0
    def oauth_login():
        """Called at the end of the oauth flow.  We'll receive an auth code from UAA and use it to
        retrieve a bearer token that we can use to actually do stuff
        """
        logging.info(request.referrer)
        is_invitation = request.referrer and request.referrer.find('invitations/accept') != 1
        if is_invitation and 'code' not in request.args:
            return redirect(url_for('first_login'))

        try:

            # connect a client with no token
            uaac = UAAClient(app.config['UAA_BASE_URL'], None, verify_tls=app.config['UAA_VERIFY_TLS'])

            # auth with our client secret and the code they gave us
            token = uaac.oauth_token(request.args['code'], app.config['UAA_CLIENT_ID'], app.config['UAA_CLIENT_SECRET'])

            # if it's valid, but missing the scope we need, bail
            if 'scim.invite' not in token['scope'].split(' '):
                raise RuntimeError('Valid oauth authentication but missing the scim.invite scope.  Scopes: {0}'.format(
                    token['scope']
                ))

            # make flask expire our session for us, by expiring it shortly before the token expires
            session.permanent = True
            app.permanent_session_lifetime = timedelta(seconds=token['expires_in'] - 30)

            # stash the stuff we care about
            session['UAA_TOKEN'] = token['access_token']
            session['UAA_TOKEN_SCOPES'] = token['scope'].split(' ')
            if is_invitation:
                return redirect(url_for('first_login'))
            endpoint = session.pop('_endpoint', None)
            if not endpoint:
                endpoint = 'index'
            logging.info(endpoint)
            return redirect(url_for(endpoint))
        except UAAError:
            logging.exception('An invalid authorization_code was received from UAA')
            return render_template('error/token_validation.html'), 401
        except RuntimeError:
            logging.exception('Token validated but had wrong scope')
            return render_template('error/missing_scope.html'), 403
Ejemplo n.º 16
0
    def test_request_bad(self, requests):
        """UAAError is reaised when it occurs"""

        r = Mock()
        r.status_code = 500
        r.text = json.dumps({"error_description": "oh no"})
        requests.get.return_value = r

        uaac = UAAClient("http://example.com", "foo", True)

        with self.assertRaises(UAAError):
            uaac._request("/bar", "GET")

        requests.get.assert_called_with(
            "http://example.com/bar",
            headers={"Authorization": "Bearer foo"},
            json=None,
            params=None,
            auth=None,
            verify=True,
        )
Ejemplo n.º 17
0
    def test_get_client_token(self):
        """_get_client_token() makes a POST to /oauth/token with the appropriate headers and query params"""

        uaac = UAAClient("http://example.com", "foo", False)
        m = Mock()
        uaac._request = m

        uaac._get_client_token("bar", "baz")

        args, kwargs = m.call_args

        assert args == ("/oauth/token", "POST")

        assert kwargs["params"] == {
            "grant_type": "client_credentials",
            "response_type": "token",
        }

        assert isinstance(kwargs["auth"], HTTPBasicAuth)
        assert kwargs["auth"].username == "bar"
        assert kwargs["auth"].password == "baz"
Ejemplo n.º 18
0
    def test_request_bad(self, requests):
        """UAAError is reaised when it occurs"""

        r = Mock()
        r.status_code = 500
        r.text = json.dumps({'error_description': 'oh no'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', True)

        with self.assertRaises(UAAError):
            uaac._request('/bar', 'GET')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params=None,
            auth=None,
            verify=True
        )
Ejemplo n.º 19
0
    def test_get_client_token(self):
        """_get_client_token() makes a POST to /oauth/token with the appropriate headers and query params"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac._get_client_token('bar', 'baz')

        args, kwargs = m.call_args

        assert args == ('/oauth/token', 'POST')

        assert kwargs['params'] == {
            'grant_type': 'client_credentials',
            'response_type': 'token'
        }

        assert isinstance(kwargs['auth'], HTTPBasicAuth)
        assert kwargs['auth'].username == 'bar'
        assert kwargs['auth'].password == 'baz'
Ejemplo n.º 20
0
    def test_get_client_token(self):
        """_get_client_token() makes a POST to /oauth/token with the appropriate headers and query params"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac._get_client_token('bar', 'baz')

        args, kwargs = m.call_args

        assert args == ('/oauth/token', 'POST')

        assert kwargs['params'] == {
            'grant_type': 'client_credentials',
            'response_type': 'token'
        }

        assert isinstance(kwargs['auth'], HTTPBasicAuth)
        assert kwargs['auth'].username == 'bar'
        assert kwargs['auth'].password == 'baz'
Ejemplo n.º 21
0
    def test_request_bad(self, requests):
        """UAAError is reaised when it occurs"""

        r = Mock()
        r.status_code = 500
        r.text = json.dumps({'error_description': 'oh no'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', True)

        with self.assertRaises(UAAError):
            uaac._request('/bar', 'GET')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params=None,
            auth=None,
            verify=True
        )
Ejemplo n.º 22
0
    def test_request_get_auth(self, requests):
        """Auth value is passed directly to requests"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({"test": "value"})
        requests.get.return_value = r

        uaac = UAAClient("http://example.com", "foo", False)

        resp = uaac._request("/bar", "GET", auth="this should be basic")

        requests.get.assert_called_with(
            "http://example.com/bar",
            headers={},
            json=None,
            params=None,
            auth="this should be basic",
            verify=False,
        )

        assert resp["test"] == "value"
Ejemplo n.º 23
0
    def test_request_get_params(self, requests):
        """Query string is sent if params are provided"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET', params={'omg': 'lol'})

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params={'omg': 'lol'},
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Ejemplo n.º 24
0
    def test_request_get_auth(self, requests):
        """Auth value is passed directly to requests"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET', auth='this should be basic')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={},
            json=None,
            params=None,
            auth='this should be basic',
            verify=False
        )

        assert resp['test'] == 'value'
Ejemplo n.º 25
0
    def test_request_get_insecure(self, requests):
        """Insecure GET request is made"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params=None,
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Ejemplo n.º 26
0
    def test_request_get_params(self, requests):
        """Query string is sent if params are provided"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({"test": "value"})
        requests.get.return_value = r

        uaac = UAAClient("http://example.com", "foo", False)

        resp = uaac._request("/bar", "GET", params={"omg": "lol"})

        requests.get.assert_called_with(
            "http://example.com/bar",
            headers={"Authorization": "Bearer foo"},
            json=None,
            params={"omg": "lol"},
            auth=None,
            verify=False,
        )

        assert resp["test"] == "value"
Ejemplo n.º 27
0
    def test_request_get_insecure(self, requests):
        """Insecure GET request is made"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({"test": "value"})
        requests.get.return_value = r

        uaac = UAAClient("http://example.com", "foo", False)

        resp = uaac._request("/bar", "GET")

        requests.get.assert_called_with(
            "http://example.com/bar",
            headers={"Authorization": "Bearer foo"},
            json=None,
            params=None,
            auth=None,
            verify=False,
        )

        assert resp["test"] == "value"
Ejemplo n.º 28
0
    def test_request_get_insecure(self, requests):
        """Insecure GET request is made"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params=None,
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Ejemplo n.º 29
0
    def test_request_post_body(self, requests):
        """Body is included in request if provided"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.post.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'POST', body='hi')

        requests.post.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json='hi',
            params=None,
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Ejemplo n.º 30
0
    def test_request_post_body(self, requests):
        """Body is included in request if provided"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({"test": "value"})
        requests.post.return_value = r

        uaac = UAAClient("http://example.com", "foo", False)

        resp = uaac._request("/bar", "POST", body="hi")

        requests.post.assert_called_with(
            "http://example.com/bar",
            headers={"Authorization": "Bearer foo"},
            json="hi",
            params=None,
            auth=None,
            verify=False,
        )

        assert resp["test"] == "value"
Ejemplo n.º 31
0
    def test_request_post_body(self, requests):
        """Body is included in request if provided"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.post.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'POST', body='hi')

        requests.post.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json='hi',
            params=None,
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Ejemplo n.º 32
0
    def test_request_get_auth(self, requests):
        """Auth value is passed directly to requests"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET', auth='this should be basic')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={},
            json=None,
            params=None,
            auth='this should be basic',
            verify=False
        )

        assert resp['test'] == 'value'
Ejemplo n.º 33
0
    def test_put_user(self):
        """put_user() makes a PUT request to /Users/<id> with appropriate headers"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        user = {
            'id': 'foo',
            'meta': {
                'version': '123'
            }
        }

        uaac.put_user(user)

        m.assert_called_with(
            urljoin('/Users', 'foo'),
            'PUT',
            body=user,
            headers={'If-Match': '123'}
        )
Ejemplo n.º 34
0
    def test_put_user(self):
        """put_user() makes a PUT request to /Users/<id> with appropriate headers"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        user = {
            'id': 'foo',
            'meta': {
                'version': '123'
            }
        }

        uaac.put_user(user)

        m.assert_called_with(
            urljoin('/Users', 'foo'),
            'PUT',
            body=user,
            headers={'If-Match': '123'}
        )
Ejemplo n.º 35
0
    def test_request_get_params(self, requests):
        """Query string is sent if params are provided"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET', params={'omg': 'lol'})

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params={'omg': 'lol'},
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Ejemplo n.º 36
0
    def have_uaa_and_csrf_token():
        """Before each request, make sure we have a valid token from UAA.

        If we don't send them to UAA to start the oauth process.

        Technically we should bounce them through the renew token process if we already have one,
        but this app will be used sparingly, so it's fine to push them back through the authorize flow
        each time we need to renew our token.

        """
        # don't authenticate the oauth code receiver, or we'll never get the code back from UAA
        if request.endpoint and request.endpoint in [
                "oauth_login",
                "forgot_password",
                "redeem_invite",
                "reset_password",
                "signup",
                "static",
        ]:
            return

        # check our token, and expirary date
        token = session.get("UAA_TOKEN", None)

        # if all looks good, setup the client
        if token:
            g.uaac = UAAClient(
                app.config["UAA_BASE_URL"],
                session["UAA_TOKEN"],
                verify_tls=app.config["UAA_VERIFY_TLS"],
            )
        else:
            # if not forget the token, it's bad (if we have one)
            session.clear()
            session["_endpoint"] = request.endpoint

            return redirect(
                "{0}/oauth/authorize?client_id={1}&response_type=code".format(
                    app.config["UAA_BASE_URL"], app.config["UAA_CLIENT_ID"]))

        g.totp = TOTPClient(uaadb_engine)
        # if it's a POST request, that's not to oauth_login
        # Then check for a CSRF token, if we don't have one, bail
        if request.method == "POST":
            csrf_token = session.pop("_csrf_token", None)
            if not csrf_token or csrf_token != request.form.get("_csrf_token"):
                logging.error(
                    "Error validating CSRF token.  Got: {0}; Expected: {1}".
                    format(request.form.get("_csrf_token"), csrf_token))

                return render_template("error/csrf.html"), 400
Ejemplo n.º 37
0
    def test_idps(self):
        """idps() makes a GET request to /identity-providers"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.idps(active_only=True)
        m.assert_called_with('/identity-providers', 'GET', params={'active_only': 'true'})

        uaac.idps(active_only=False)
        m.assert_called_with('/identity-providers', 'GET', params={'active_only': 'false'})
Ejemplo n.º 38
0
    def test_idps(self):
        """idps() makes a GET request to /identity-providers"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.idps(active_only=True)
        m.assert_called_with('/identity-providers', 'GET', params={'active_only': 'true'})

        uaac.idps(active_only=False)
        m.assert_called_with('/identity-providers', 'GET', params={'active_only': 'false'})
Ejemplo n.º 39
0
    def test_idps(self):
        """idps() makes a GET request to /identity-providers"""

        uaac = UAAClient("http://example.com", "foo", False)
        m = Mock()
        uaac._request = m

        uaac.idps(active_only=True)
        m.assert_called_with(
            "/identity-providers", "GET", params={"active_only": "true"}
        )

        uaac.idps(active_only=False)
        m.assert_called_with(
            "/identity-providers", "GET", params={"active_only": "false"}
        )
Ejemplo n.º 40
0
    def reset_password():

        # start with giving them the form
        if request.method == 'GET':

            if 'validation' not in request.args:
                flash(
                    'The password validation link is incomplete. Please verify your link is correct and try again.'
                )
                return render_template('reset_password.html',
                                       validation_code=None)

            return render_template('reset_password.html',
                                   validation_code=request.args['validation'])

        # if we've reached here we are POST so we can email user link
        token = request.form.get('_validation_code', '')
        email = request.form.get('email_address', '')
        if not email:
            flash('Email cannot be blank.')
            return render_template('reset_password.html')
        try:
            v = validate_email(email)  # validate and get info
            email = v["email"]  # replace with normalized form
        except EmailNotValidError as exc:
            # email is not valid, exception message is human-readable
            flash(str(exc))
            return render_template('reset_password.html')

        # If we've made it this far, it's a valid email so let's verify the generated
        # token with their email address.
        if r:
            userToken = r.get(email)

            if userToken.decode('utf-8') == token:
                logging.info('Successfully verified token {0} for {1}'.format(
                    userToken, email))
                r.delete(email)
            else:
                flash(
                    'Valid token not found. Please try your forgot password request again.'
                )
                return render_template('reset_password.html')

            temporaryPassword = generate_temporary_password()
            try:
                g.uaac = UAAClient(app.config['UAA_BASE_URL'],
                                   None,
                                   verify_tls=app.config['UAA_VERIFY_TLS'])
                if g.uaac.set_temporary_password(
                        app.config['UAA_CLIENT_ID'],
                        app.config['UAA_CLIENT_SECRET'], email,
                        temporaryPassword):
                    logging.info(
                        'Set temporary password for {0}'.format(email))
                    return render_template('reset_password.html',
                                           password=temporaryPassword)
                else:
                    flash(
                        'Unable to set temporary password. Did you use the right email address?'
                    )
                    return render_template('reset_password.html')
            except Exception:
                logging.exception('Unable to set your temporary password.')

        return render_template('error/internal.html'), 500
Ejemplo n.º 41
0
    def forgot_password():
        identity_token = uuid.uuid4().hex

        # start with giving them the form
        if request.method == 'GET':
            return render_template('forgot_password.html')

        # if we've reached here we are POST so we can email user link
        email = request.form.get('email_address', '')
        if not email:
            flash('Email cannot be blank.')
            return render_template('forgot_password.html')
        try:
            v = validate_email(email)  # validate and get info
            email = v["email"]  # replace with normalized form
        except EmailNotValidError as exc:
            # email is not valid, exception message is human-readable
            flash(str(exc))
            return render_template('forgot_password.html')

        # If we've made it this far, it's a valid email so we'll generate and store a
        # token and send an email.
        logging.info('generating validation token for user')

        branding = {
            'company_name': app.config['BRANDING_COMPANY_NAME']
        }

        reset = {
            'verifyLink': url_for('reset_password', validation=identity_token, _external=True)
        }
        logging.info(reset['verifyLink'])

        password = {'changeLink': changeLink}

        subject = render_template('email/subject-password.txt', reset=reset, branding=branding).strip()
        body = render_template('email/body-password.html', reset=reset, branding=branding, password=password)

        uaac = UAAClient(
            app.config['UAA_BASE_URL'],
            None,
            verify_tls=app.config['UAA_VERIFY_TLS']
        )

        user_exists = uaac.does_origin_user_exist(
            app.config['UAA_CLIENT_ID'],
            app.config['UAA_CLIENT_SECRET'],
            email,
            app.config['IDP_PROVIDER_ORIGIN']
        )

        if user_exists:
            try:
                r.setex(email, FORGOT_PW_TOKEN_EXPIRATION_IN_SECONDS, identity_token)
            except redis.exceptions.RedisError:
                return render_template('error/internal.html'), 500

            send_email(app, email, subject, body)
        else:
            logging.info("{} does not exist. Forgot password email not sent".format(email))

        return render_template('forgot_password.html', email_sent=True, email=email)
Ejemplo n.º 42
0
    def test_users(self):
        """users() makes a GET request to /Users"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.users()
        m.assert_called_with('/Users', 'GET', params={'startIndex': 1}, headers={})

        uaac.users(start=2)
        m.assert_called_with('/Users', 'GET', params={'startIndex': 2}, headers={})

        uaac.users(list_filter='test filter')
        m.assert_called_with('/Users', 'GET',
                             params={'filter': 'test filter', 'startIndex': 1}, headers={})

        uaac.users(token='FOO')
        m.assert_called_with('/Users', 'GET', params={'startIndex': 1},
                             headers={'Authorization': 'Bearer FOO'})

        uaac.users('test filter', 'FOO', 9)
        m.assert_called_with('/Users', 'GET', params={'filter': 'test filter', 'startIndex': 9},
                             headers={'Authorization': 'Bearer FOO'})
Ejemplo n.º 43
0
    def test_users(self):
        """users() makes a GET request to /Users"""

        uaac = UAAClient("http://example.com", "foo", False)
        m = Mock()
        uaac._request = m

        uaac.users()
        m.assert_called_with("/Users", "GET", params={"startIndex": 1}, headers={})

        uaac.users(start=2)
        m.assert_called_with("/Users", "GET", params={"startIndex": 2}, headers={})

        uaac.users(list_filter="test filter")
        m.assert_called_with(
            "/Users",
            "GET",
            params={"filter": "test filter", "startIndex": 1},
            headers={},
        )

        uaac.users(token="FOO")
        m.assert_called_with(
            "/Users",
            "GET",
            params={"startIndex": 1},
            headers={"Authorization": "Bearer FOO"},
        )

        uaac.users("test filter", "FOO", 9)
        m.assert_called_with(
            "/Users",
            "GET",
            params={"filter": "test filter", "startIndex": 9},
            headers={"Authorization": "Bearer FOO"},
        )
Ejemplo n.º 44
0
def uaa(config):
    uaac = UAAClient(config["urls"]["uaa"], None, verify_tls=True)
    token = uaac._get_client_token(config["uaa_client"], config["uaa_secret"])
    uaac.token = token
    return uaac
Ejemplo n.º 45
0
    def test_users(self):
        """users() makes a GET request to /Users"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.users()
        m.assert_called_with('/Users', 'GET', params={'startIndex': 1}, headers={})

        uaac.users(start=2)
        m.assert_called_with('/Users', 'GET', params={'startIndex': 2}, headers={})

        uaac.users(list_filter='test filter')
        m.assert_called_with('/Users', 'GET',
                             params={'filter': 'test filter', 'startIndex': 1}, headers={})

        uaac.users(token='FOO')
        m.assert_called_with('/Users', 'GET', params={'startIndex': 1},
                             headers={'Authorization': 'Bearer FOO'})

        uaac.users('test filter', 'FOO', 9)
        m.assert_called_with('/Users', 'GET', params={'filter': 'test filter', 'startIndex': 9},
                             headers={'Authorization': 'Bearer FOO'})