def setUp(self): super(ApiSslServerTestBase, self).setUp() key = rdf_crypto.RSAPrivateKey.GenerateKey() key_path = os.path.join(self.temp_dir, "key.pem") with open(key_path, "wb") as f: f.write(key.AsPEM()) subject = issuer = x509.Name([ x509.NameAttribute(oid.NameOID.COMMON_NAME, u"localhost"), ]) cert = x509.CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key( key.GetPublicKey().GetRawPublicKey()).serial_number( x509.random_serial_number()).not_valid_before( datetime.datetime.utcnow()).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=1)).add_extension( x509.SubjectAlternativeName( [x509.DNSName(u"localhost")]), critical=False, ).sign(key.GetRawPrivateKey(), hashes.SHA256(), backends.default_backend()) self.cert_path = os.path.join(self.temp_dir, "certificate.pem") with open(self.cert_path, "wb") as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) config_overrider = test_lib.ConfigOverrider({ "AdminUI.enable_ssl": True, "AdminUI.ssl_key_file": key_path, "AdminUI.ssl_cert_file": self.cert_path, }) config_overrider.Start() self.addCleanup(config_overrider.Stop) self.port = portpicker.pick_unused_port() thread = wsgiapp_testlib.ServerThread(self.port, name="ApiSslServerTest") thread.StartAndWaitUntilServing() self.addCleanup(thread.Stop) api_auth_manager.InitializeApiAuthManager() self.token.username = "******" webauth.WEBAUTH_MANAGER.SetUserName(self.token.username) self.endpoint = "https://localhost:%s" % self.port
def InstallACLChecks(self): """Installs AccessControlManager and stubs out SendEmail.""" acrwac = api_call_router_with_approval_checks # Clear the cache of the approvals-based router. acrwac.ApiCallRouterWithApprovalChecks.ClearCache() name = compatibility.GetName(acrwac.ApiCallRouterWithApprovalChecks) config_overrider = test_lib.ConfigOverrider( {"API.DefaultRouter": name}) config_overrider.Start() self.addCleanup(config_overrider.Stop) # Make sure ApiAuthManager is initialized with this configuration setting. api_auth_manager.InitializeApiAuthManager()
def setUp(self): super(ApiClientLibApprovalsTest, self).setUp() cls = api_call_router_with_approval_checks.ApiCallRouterWithApprovalChecks cls.ClearCache() config_overrider = test_lib.ConfigOverrider( {"API.DefaultRouter": compatibility.GetName(cls)}) config_overrider.Start() self.addCleanup(config_overrider.Stop) # Force creation of new APIAuthorizationManager, so that configuration # changes are picked up. api_auth_manager.InitializeApiAuthManager()
def setUp(self): # pylint: disable=invalid-name """Set up test method.""" super().setUp() if not self.__class__.api_method: raise ValueError("%s.api_method has to be set." % self.__class__.__name__) if not self.__class__.handler: raise ValueError("%s.handler has to be set." % self.__class__.__name__) self.checks = [] p = psutil.Process(os.getpid()) syscalls_stubber = utils.MultiStubber( (socket, "gethostname", lambda: "test.host"), (os, "getpid", lambda: 42), (psutil, "Process", lambda _=None: p)) syscalls_stubber.Start() self.addCleanup(syscalls_stubber.Stop) self.test_username = "******" webauth.WEBAUTH_MANAGER.SetUserName(self.test_username) # Force creation of new APIAuthorizationManager. api_auth_manager.InitializeApiAuthManager() config_overrider = test_lib.ConfigOverrider({ # For regression tests we want to use a fixed version number instead of # current one. Otherwise regression data would have to be re-generated # each time GRR version is increased. "Source.version_major": 1, "Source.version_minor": 2, "Source.version_revision": 3, "Source.version_release": 4, "Source.version_string": "1.2.3.4", "Source.version_numeric": 1234, }) config_overrider.Start() self.addCleanup(config_overrider.Stop)
def setUp(self): super(ApiIntegrationTest, self).setUp() api_auth_manager.InitializeApiAuthManager() self.token.username = "******" webauth.WEBAUTH_MANAGER.SetUserName(self.token.username) self.CreateUser(self.token.username) self.port = ApiIntegrationTest.server_port self.endpoint = "http://localhost:%s" % self.port self.api = grr_api.InitHttp(api_endpoint=self.endpoint) poll_stubber = utils.MultiStubber( (grr_api_utils, "DEFAULT_POLL_INTERVAL", 0.1), (grr_api_utils, "DEFAULT_POLL_TIMEOUT", 10)) poll_stubber.Start() self.addCleanup(poll_stubber.Stop)
def GetConnector(api_version): if api_version not in [1, 2]: raise ValueError("api_version may be 1 or 2 only") with _HTTP_ENDPOINTS_LOCK: if api_version not in _HTTP_ENDPOINTS: port = portpicker.pick_unused_port() logging.info("Picked free AdminUI port %d.", port) # Force creation of new APIAuthorizationManager. api_auth_manager.InitializeApiAuthManager() trd = wsgiapp_testlib.ServerThread( port, name="ApiRegressionHttpConnectorV%d" % api_version) trd.StartAndWaitUntilServing() _HTTP_ENDPOINTS[api_version] = "http://localhost:%d" % port return connectors.HttpConnector(api_endpoint=_HTTP_ENDPOINTS[api_version])
def setUp(self): super(ApiIntegrationTest, self).setUp() api_auth_manager.InitializeApiAuthManager() self.context = api_call_context.ApiCallContext("api_test_robot_user") self.token.username = self.context.username try: webauth.WEBAUTH_MANAGER.SetUserName(self.context.username) except AttributeError: # Only the NullWebAuthManager supports SetUserName pass self.CreateUser(self.context.username) self.port = ApiIntegrationTest.server_port self.endpoint = "http://localhost:%s" % self.port self.api = grr_api.InitHttp(api_endpoint=self.endpoint) poll_stubber = utils.MultiStubber( (grr_api_utils, "DEFAULT_POLL_INTERVAL", 0.1), (grr_api_utils, "DEFAULT_POLL_TIMEOUT", 10)) poll_stubber.Start() self.addCleanup(poll_stubber.Stop)
def setUp(self): super().setUp() default_router = RootApiBinaryManagementTestRouter root_api_config_overrider = test_lib.ConfigOverrider( {"API.DefaultRouter": compatibility.GetName(default_router)}) root_api_config_overrider.Start() self.addCleanup(root_api_config_overrider.Stop) patcher = mock.patch.object(api_call_router_registry, "_API_CALL_ROUTER_REGISTRY", {}) patcher.start() self.addCleanup(patcher.stop) api_call_router_registry.RegisterApiCallRouter( "RootApiBinaryManagementTestRouter", RootApiBinaryManagementTestRouter) self.addCleanup( lambda: api_call_router_registry.UnregisterApiCallRouter( # pylint:disable=g-long-lambda "RootApiBinaryManagementTestRouter")) # Force creation of new APIAuthorizationManager, so that configuration # changes are picked up. api_auth_manager.InitializeApiAuthManager()
def setUp(self): super().setUp() config_overrider = test_lib.ConfigOverrider({ "API.DefaultRouter": compatibility.GetName(TestHttpApiRouter), }) config_overrider.Start() self.addCleanup(config_overrider.Stop) patcher = mock.patch.object(api_call_router_registry, "_API_CALL_ROUTER_REGISTRY", {}) patcher.start() self.addCleanup(patcher.stop) api_call_router_registry.RegisterApiCallRouter("TestHttpApiRouter", TestHttpApiRouter) # pylint: disable=g-long-lambda self.addCleanup(lambda: api_call_router_registry.UnregisterApiCallRouter( "TestHttpApiRouter")) api_call_router_registry.RegisterApiCallRouter("TestHttpApiRouter", TestHttpApiRouter) # Make sure ApiAuthManager is initialized with this configuration setting. api_auth_manager.InitializeApiAuthManager() self.router_matcher = http_api.RouterMatcher()
def ClearCache(self): api_router.ApiCallRouterWithApprovalChecks.ClearCache() api_auth_manager.InitializeApiAuthManager()
def InstallACLChecks(self): # This class purposefully does not install ACL checks. api_auth_manager.InitializeApiAuthManager()
def Init(): """Run all required startup routines and initialization hooks.""" # Set up a temporary syslog handler so we have somewhere to log problems # with ConfigInit() which needs to happen before we can start our create our # proper logging setup. syslog_logger = logging.getLogger("TempLogger") if os.path.exists("/dev/log"): handler = logging.handlers.SysLogHandler(address="/dev/log") else: handler = logging.handlers.SysLogHandler() syslog_logger.addHandler(handler) try: config_lib.SetPlatformArchContext() config_lib.ParseConfigCommandLine() except config_lib.Error: syslog_logger.exception("Died during config initialization") raise metric_metadata = server_metrics.GetMetadata() metric_metadata.extend(communicator.GetMetricMetadata()) stats_collector = prometheus_stats_collector.PrometheusStatsCollector( metric_metadata, registry=prometheus_client.REGISTRY) stats_collector_instance.Set(stats_collector) server_logging.ServerLoggingStartupInit() bs_registry_init.RegisterBlobStores() all_decoders.Register() all_parsers.Register() data_store.InitializeDataStore() if data_store.AFF4Enabled(): aff4.AFF4Init() # Requires data_store.InitializeDataStore. aff4_grr.GRRAFF4Init() # Requires aff4.AFF4Init. filestore.FileStoreInit() # Requires aff4_grr.GRRAFF4Init. results.ResultQueueInit() # Requires aff4.AFF4Init. sequential_collection.StartUpdaterOnce() if contexts.ADMIN_UI_CONTEXT in config.CONFIG.context: api_auth_manager.InitializeApiAuthManager() artifact.LoadArtifactsOnce() # Requires aff4.AFF4Init. checks.LoadChecksFromFilesystemOnce() client_approval_auth.InitializeClientApprovalAuthorizationManagerOnce() cronjobs.InitializeCronWorkerOnce() # Requires aff4.AFF4Init. email_alerts.InitializeEmailAlerterOnce() http_api.InitializeHttpRequestHandlerOnce() ip_resolver.IPResolverInitOnce() stats_server.InitializeStatsServerOnce() webauth.InitializeWebAuthOnce() # Exempt config updater from this check because it is the one responsible for # setting the variable. if not config.CONFIG.ContextApplied("ConfigUpdater Context"): if not config.CONFIG.Get("Server.initialized"): raise RuntimeError( "Config not initialized, run \"grr_config_updater" " initialize\". If the server is already configured," " add \"Server.initialized: True\" to your config.")