def get_middleware_app(self):
        if not self._auth_method:
            return None

        if not self._auth_needed:
            return None

        # keystone middleware is needed for fetching objects

        app = AuthPostKeystone(self._server_mgr.api_bottle, {'auth_svc': self})

        auth_middleware = auth_token.AuthProtocol(app, self._conf_info)
        self._auth_middleware = auth_middleware
        while True:
            try:
                self._auth_token = auth_middleware._identity_server._adapter.get_token(
                )
                break
            except auth_token.ServiceError as e:
                msg = "Error in getting admin token: " + str(e)
                time.sleep(2)

        self._server_mgr.config_log("Auth token fetched from keystone.",
                                    level=SandeshLevel.SYS_NOTICE)

        # open access for troubleshooting
        admin_port = self._conf_info['admin_port']
        self._local_auth_app = LocalAuth(self._server_mgr.api_bottle,
                                         self._conf_info)
        vnc_greenlets.VncGreenlet("VNC Auth Keystone",
                                  self._local_auth_app.start_http_server)

        app = AuthPreKeystone(auth_middleware, None, self._server_mgr)
        return app
示例#2
0
def setup_app(pecan_config=None, extra_hooks=None):

    app_hooks = [hooks.ConfigHook(),
                 hooks.DBHook(),
                 hooks.ContextHook(),
                 hooks.RPCHook(),
                 ]
    # TODO(sbauza): Add stevedore extensions for loading hooks
    if extra_hooks:
        app_hooks.extend(extra_hooks)

    app = pecan.make_app(
        pecan_config.app.root,
        debug=CONF.debug,
        hooks=app_hooks,
        wrap_app=middleware.ParsableErrorMiddleware,
        guess_content_type_from_ext=False
    )

    # WSGI middleware for debugging
    if CONF.log_exchange:
        app = debug.Debug.factory(pecan_config)(app)

    # WSGI middleware for Keystone auth
    # NOTE(sbauza): ACLs are always active unless for unittesting where
    #               enable_acl could be set to False
    if pecan_config.app.enable_acl:
        CONF.register_opts(auth_token.opts, group=OPT_GROUP_NAME)
        keystone_config = dict(CONF.get(OPT_GROUP_NAME))
        app = auth_token.AuthProtocol(app, conf=keystone_config)

    return app
    def setUp(self, expected_env=None):
        expected_env = expected_env or {}

        conf = {
            'admin_token': 'admin_token1',
            'auth_host': 'keystone.example.com',
            'auth_port': 1234,
            'auth_admin_prefix': '/testadmin',
            'signing_dir': CERTDIR,
        }

        self.middleware = auth_token.AuthProtocol(FakeApp(expected_env), conf)
        self.middleware.http_client_class = FakeHTTPConnection
        self.middleware._iso8601 = iso8601

        self.response_status = None
        self.response_headers = None
        self.middleware.revoked_file_name = tempfile.mkstemp()[1]
        cache_timeout = datetime.timedelta(days=1)
        self.middleware.token_revocation_list_cache_timeout = cache_timeout
        self.middleware.token_revocation_list = jsonutils.dumps(
            {"revoked": [], "extra": "success"})

        signed_list = 'SIGNED_REVOCATION_LIST'
        valid_signed_list = 'VALID_SIGNED_REVOCATION_LIST'
        globals()[signed_list] = globals()[valid_signed_list]

        super(BaseAuthTokenMiddlewareTest, self).setUp()
示例#4
0
    def get_middleware_app(self):
        if not self._auth_method:
            return None

        if not self._multi_tenancy:
            return None

        # keystone middleware is needed for fetching objects

        app = AuthPostKeystone(self._server_mgr.api_bottle, {'auth_svc': self})

        auth_middleware = auth_token.AuthProtocol(app, self._conf_info)
        self._auth_middleware = auth_middleware

        # open access for troubleshooting
        admin_port = self._conf_info['admin_port']
        self._local_auth_app = LocalAuth(self._server_mgr.api_bottle,
                                         self._conf_info)
        vnc_greenlets.VncGreenlet("VNC Auth Keystone",
                                  self._local_auth_app.start_http_server)

        app = auth_middleware

        # allow multi tenancy to be updated dynamically
        app = AuthPreKeystone(auth_middleware, None, self._multi_tenancy,
                              self._server_mgr)

        return app
    def get_auth_headers_from_token(self, request, token):
        if not self._hdr_from_token_auth_middleware:
            conf_info = self._conf_info.copy()
            conf_info['delay_auth_decision'] = True

            def token_to_headers(env, start_response):
                start_response('200 OK', [('Content-type', 'text/plain')])
                status = env.get('HTTP_X_IDENTITY_STATUS')
                if status and status.lower() == 'invalid':
                    return {}
                ret_headers_dict = {}
                for hdr_name in [
                        'HTTP_X_DOMAIN_ID', 'HTTP_X_PROJECT_ID',
                        'HTTP_X_PROJECT_NAME', 'HTTP_X_USER', 'HTTP_X_ROLE',
                        'HTTP_X_API_ROLE'
                ]:
                    hdr_val = env.get(hdr_name)
                    if hdr_val:
                        ret_headers_dict[hdr_name] = hdr_val
                return ret_headers_dict

            self._hdr_from_token_auth_middleware = auth_token.AuthProtocol(
                token_to_headers, conf_info)
        return self._hdr_from_token_auth_middleware(request.headers.environ,
                                                    self.start_response)
    def get_middleware_app(self):
        if not self._auth_method:
            return None

        if not self._multi_tenancy:
            return None

        # keystone middleware is needed for fetching objects

        # app = bottle.app()
        app = AuthPostKeystone(bottle.app(), {'auth_svc': self})

        auth_middleware = auth_token.AuthProtocol(app, self._conf_info)
        self._auth_middleware = auth_middleware
        while True:
            try:
                self._auth_token = auth_middleware.get_admin_token()
                break
            except auth_token.ServiceError as e:
                self._server_mgr.config_log_error(
                    "Error in getting admin token: " + str(e))
                time.sleep(2)

        # open access for troubleshooting
        self._open_app = AuthOpen('127.0.0.1', '8095', bottle.app())
        gevent.spawn(self._open_app.start_http_server)

        app = auth_middleware

        # allow multi tenancy to be updated dynamically
        app = AuthPreKeystone(auth_middleware,
                              {'admin_token': self._auth_token},
                              self._multi_tenancy)

        return app
示例#7
0
    def validate_user_token(self, request):
        # following config forces keystone middleware to always return the result
        # back in HTTP_X_IDENTITY_STATUS env variable
        conf_info = self._conf_info.copy()
        conf_info['delay_auth_decision'] = True

        auth_middleware = auth_token.AuthProtocol(self.token_valid, conf_info)
        return auth_middleware(request.headers.environ, self.start_response)
    def test_nomemcache(self):
        conf = {
            'admin_token': 'admin_token1',
            'auth_host': 'keystone.example.com',
            'auth_port': 1234,
            'memcached_servers': 'localhost:11211',
        }

        auth_token.AuthProtocol(FakeApp(), conf)
示例#9
0
文件: acl.py 项目: mydaisy2/ironic
def install(app, conf):
    """Install ACL check on application.

    :param app: A WSGI applicatin.
    :param conf: Settings. Must include OPT_GROUP_NAME section.
    :return: The same WSGI application with ACL installed.
    """
    keystone_config = dict(conf.get(OPT_GROUP_NAME))
    return auth_token.AuthProtocol(app, conf=keystone_config)
 def test_config_revocation_cache_timeout(self):
     conf = {
         'auth_host': 'keystone.example.com',
         'auth_port': 1234,
         'auth_admin_prefix': '/testadmin',
         'revocation_cache_time': 24
     }
     middleware = auth_token.AuthProtocol(self.fake_app, conf)
     self.assertEquals(middleware.token_revocation_list_cache_timeout,
                       datetime.timedelta(seconds=24))
示例#11
0
 def test_keystone_middleware_conf(self):
     self.CONF.set_override("auth_protocol",
                            "file",
                            group=acl.OPT_GROUP_NAME)
     self.CONF.set_override("auth_version",
                            "v2.0",
                            group=acl.OPT_GROUP_NAME)
     self.CONF.set_override("auth_uri", None, group=acl.OPT_GROUP_NAME)
     api_app = app.make_app(self.CONF, attach_storage=False)
     conf = dict(self.CONF.get(acl.OPT_GROUP_NAME))
     api_app = auth_token.AuthProtocol(api_app, conf=conf)
     self.assertTrue(api_app.auth_uri.startswith('file'))
示例#12
0
 def test_keystone_middleware_parse_conffile(self):
     content = "[{0}]\nauth_protocol = file"\
               "\nauth_version = v2.0".format(acl.OPT_GROUP_NAME)
     tmpfile = fileutils.write_to_tempfile(content=content,
                                           prefix='ceilometer',
                                           suffix='.conf')
     service.prepare_service(
         ['ceilometer-api', '--config-file=%s' % tmpfile])
     api_app = app.make_app(self.CONF, attach_storage=False)
     conf = dict(self.CONF.get(acl.OPT_GROUP_NAME))
     api_app = auth_token.AuthProtocol(api_app, conf=conf)
     self.assertTrue(api_app.auth_uri.startswith('file'))
     os.unlink(tmpfile)
    def set_middleware(self, fake_app=None, fake_http=None,
                       expected_env=None, conf=None):
        """Configure the class ready to call the auth_token middleware.

        Set up the various fake items needed to run the middleware.
        Individual tests that need to further refine these can call this
        function to override the class defaults.

        """
        conf = conf or self.conf
        if fake_http:
            conf['http_handler'] = fake_http
        fake_app = fake_app or self.fake_app
        self.middleware = auth_token.AuthProtocol(fake_app(expected_env), conf)
        self.middleware._iso8601 = iso8601
        self.middleware.revoked_file_name = tempfile.mkstemp()[1]
        self.middleware.token_revocation_list = jsonutils.dumps(
            {"revoked": [], "extra": "success"})
    def get_middleware_app(self):
        if not self._auth_method:
            return None

        if not self._auth_needed:
            return None

        # keystone middleware is needed for fetching objects

        app = AuthPostKeystone(self._server_mgr, self)

        auth_middleware = auth_token.AuthProtocol(app, self._conf_info)
        self._auth_middleware = auth_middleware

        # open access for troubleshooting
        self._local_auth_app = LocalAuth(self._server_mgr.api_bottle,
                                         self._conf_info)
        vnc_greenlets.VncGreenlet("VNC Auth Keystone",
                                  self._local_auth_app.start_http_server)

        app = AuthPreKeystone(auth_middleware, None, self._server_mgr)
        return app
示例#15
0
    def get_middleware_app(self):
        if not self._auth_method:
            return None

        if not self._multi_tenancy:
            return None

        # keystone middleware is needed for fetching objects

        # app = bottle.app()
        app = AuthPostKeystone(bottle.app(), {'auth_svc': self})

        auth_middleware = auth_token.AuthProtocol(app, self._conf_info)
        self._auth_middleware = auth_middleware
        while True:
            try:
                self._auth_token = auth_middleware.get_admin_token()
                break
            except auth_token.ServiceError as e:
                msg = "Error in getting admin token: " + str(e)
                time.sleep(2)

        self._server_mgr.config_log("Auth token fetched from keystone.",
            level=SandeshLevel.SYS_NOTICE)

        # open access for troubleshooting
        admin_port = self._conf_info['admin_port']
        self._local_auth_app = LocalAuth(bottle.app(), self._conf_info)
        gevent.spawn(self._local_auth_app.start_http_server)

        app = auth_middleware

        # allow multi tenancy to be updated dynamically
        app = AuthPreKeystone(
            auth_middleware,
            {'admin_token': self._auth_token},
            self._multi_tenancy)

        return app
    def validate_user_token(self):
        if not self._user_auth_middleware:
            # following config forces keystone middleware to always return the
            # result back in HTTP_X_IDENTITY_STATUS env variable
            conf_info = self._conf_info.copy()
            conf_info['delay_auth_decision'] = True
            self._user_auth_middleware = auth_token.AuthProtocol(
                self.token_valid, conf_info)

        if not self._user_auth_middleware:
            return False, (403, six.ensure_str(" Permission denied"))

        request_attrs = {
            'REQUEST_METHOD': get_request().route.method,
            'bottle.app': get_request().environ['bottle.app'],
        }
        if 'HTTP_X_AUTH_TOKEN' in get_request().environ:
            request_attrs['HTTP_X_AUTH_TOKEN'] =\
                get_request().environ['HTTP_X_AUTH_TOKEN'].encode("ascii")
        elif 'HTTP_X_USER_TOKEN' in get_request().environ:
            request_attrs['HTTP_X_USER_TOKEN'] =\
                get_request().environ['HTTP_X_USER_TOKEN'].encode("ascii")
        else:
            return False, (400,
                           six.ensure_str("User token needed for validation"))
        b_req = bottle.BaseRequest(request_attrs)
        # get permissions in internal context
        orig_context = get_context()
        i_req = ApiInternalRequest(b_req.url, b_req.urlparts, b_req.environ,
                                   b_req.headers, None, None)
        set_context(ApiContext(internal_req=i_req))
        try:
            token_info = self._user_auth_middleware(
                get_request().headers.environ, self.start_response)
        finally:
            set_context(orig_context)

        return True, token_info
示例#17
0
def install(app, conf):
    """Install ACL check on application."""
    register_opts(cfg.CONF)
    return auth_token.AuthProtocol(app, conf=dict(conf.get(OPT_GROUP_NAME)))
示例#18
0
def setup(app):
    if cfg.CONF.pecan.auth_enable:
        return auth_token.AuthProtocol(app, conf=dict(cfg.CONF.keystone))
    else:
        return app
示例#19
0
def install(app, conf):
    """Installs ACL check on application."""
    app.wsgi_app = auth_token.AuthProtocol(app.wsgi_app,
                                           conf=dict(conf.get(OPT_GROUP_NAME)))
    app.before_request(check)
示例#20
0
 def install(cls, app, conf):
     """Install Auth check on application."""
     LOG.debug(u'Installing Keystone\'s auth protocol')
     cls._register_opts(conf)
     conf = dict(conf.get(cls.OPT_GROUP_NAME))
     return auth_token.AuthProtocol(app, conf=conf)