Beispiel #1
0
    def testExtAttrsCollection(self):
        with temp.AutoTempDirPath(remove_non_empty=True) as temp_dirpath:
            foo_filepath = temp.TempFilePath(dir=temp_dirpath)
            filesystem_test_lib.SetExtAttr(foo_filepath,
                                           name="user.quux",
                                           value="foo")

            bar_filepath = temp.TempFilePath(dir=temp_dirpath)
            filesystem_test_lib.SetExtAttr(bar_filepath,
                                           name="user.quux",
                                           value="bar")

            baz_filepath = temp.TempFilePath(dir=temp_dirpath)
            filesystem_test_lib.SetExtAttr(baz_filepath,
                                           name="user.quux",
                                           value="baz")

            request = rdf_client_fs.FindSpec(pathspec=rdf_paths.PathSpec(
                path=temp_dirpath, pathtype=rdf_paths.PathSpec.PathType.OS),
                                             path_glob="*",
                                             collect_ext_attrs=True)

            hits = self.RunAction(searching.Find, request)

            self.assertLen(hits, 3)

            values = []
            for hit in hits:
                self.assertLen(hit.ext_attrs, 1)
                values.append(hit.ext_attrs[0].value)

            self.assertCountEqual(values, [b"foo", b"bar", b"baz"])
Beispiel #2
0
def SetUpTestFiles():
    with temp.AutoTempDirPath(remove_non_empty=True) as temp_dirpath:
        file_bar_path = temp.TempFilePath(dir=temp_dirpath, prefix="bar")
        with open(file_bar_path, "w") as fd:
            fd.write("bar")

        file_baz_path = temp.TempFilePath(dir=temp_dirpath, prefix="baz")
        with open(file_baz_path, "w") as fd:
            fd.write("baz")

        file_foo_path = temp.TempFilePath(dir=temp_dirpath, prefix="foo")
        with open(file_foo_path, "w") as fd:
            fd.write("foo")

        yield {
            "bar":
            TestFile(path=file_bar_path,
                     sha1="62cdb7020ff920e5aa642c3d4066950dd1f01f4d"),
            "baz":
            TestFile(path=file_baz_path,
                     sha1="bbe960a25ea311d21d40669e93df2003ba9b90a2"),
            "foo":
            TestFile(path=file_foo_path,
                     sha1="0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33")
        }
Beispiel #3
0
    def setUpClass(cls):
        super(ApiSslServerTestBase, cls).setUpClass()

        if ApiSslServerTestBase._api_set_up_done:
            return

        key = rdf_crypto.RSAPrivateKey.GenerateKey()
        key_path = temp.TempFilePath("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())

        ApiSslServerTestBase.ssl_cert_path = temp.TempFilePath(
            "certificate.pem")
        with open(ApiSslServerTestBase.ssl_cert_path, "wb") as f:
            f.write(cert.public_bytes(serialization.Encoding.PEM))

        ApiSslServerTestBase.ssl_port = portpicker.pick_unused_port()
        with test_lib.ConfigOverrider({
                "AdminUI.enable_ssl":
                True,
                "AdminUI.ssl_key_file":
                key_path,
                "AdminUI.ssl_cert_file":
                ApiSslServerTestBase.ssl_cert_path,
        }):
            ApiSslServerTestBase._ssl_trd = wsgiapp_testlib.ServerThread(
                ApiSslServerTestBase.ssl_port, name="ApiSslServerTest")
            ApiSslServerTestBase._ssl_trd.StartAndWaitUntilServing()

        ApiSslServerTestBase.ssl_endpoint = ("https://localhost:%s" %
                                             ApiSslServerTestBase.ssl_port)

        ApiSslServerTestBase._api_set_up_done = True
Beispiel #4
0
  def testSuffix(self):
    filepath = temp.TempFilePath(suffix="foo")

    self.assertTrue(os.path.exists(filepath))
    self.assertEndsWith(os.path.basename(filepath), "foo")

    os.remove(filepath)
Beispiel #5
0
  def testPrefix(self):
    filepath = temp.TempFilePath(prefix="foo")

    self.assertTrue(os.path.exists(filepath))
    self.assertStartsWith(os.path.basename(filepath), "foo")

    os.remove(filepath)
Beispiel #6
0
def TestInit():
  """Only used in tests and will rerun all the hooks to create a clean state."""
  global INIT_RAN

  stats_collector = prometheus_stats_collector.PrometheusStatsCollector()
  stats_collector_instance.Set(stats_collector)

  # Tests use both the server template grr_server.yaml as a primary config file
  # (this file does not contain all required options, e.g. private keys), and
  # additional configuration in test_data/grr_test.yaml which contains typical
  # values for a complete installation.
  flags.FLAGS.config = package.ResourcePath("grr-response-core",
                                            "install_data/etc/grr-server.yaml")

  flags.FLAGS.secondary_configs.append(
      package.ResourcePath("grr-response-test",
                           "grr_response_test/test_data/grr_test.yaml"))

  # This config contains non-public settings that should be applied during
  # tests.
  extra_test_config = config.CONFIG["Test.additional_test_config"]
  if os.path.exists(extra_test_config):
    flags.FLAGS.secondary_configs.append(extra_test_config)

  # Prevent using the default writeback location since it may clash with local
  # setup.
  writeback_filepath = temp.TempFilePath(prefix="grr_writeback", suffix=".yaml")
  config.CONFIG.global_override["Config.writeback"] = writeback_filepath

  # Tests additionally add a test configuration file.
  config_lib.SetPlatformArchContext()
  config_lib.ParseConfigCommandLine()

  # We are running a test so let the config system know that.
  config.CONFIG.AddContext(contexts.TEST_CONTEXT,
                           "Context applied when we run tests.")

  if not INIT_RAN:
    server_logging.ServerLoggingStartupInit()
    server_logging.SetTestVerbosity()

  blob_store_test_lib.UseTestBlobStore()

  data_store.InitializeDataStore()

  artifact.LoadArtifactsOnce()
  checks.LoadChecksFromFilesystemOnce()
  client_approval_auth.InitializeClientApprovalAuthorizationManagerOnce()
  email_alerts.InitializeEmailAlerterOnce()
  http_api.InitializeHttpRequestHandlerOnce()
  ip_resolver.IPResolverInitOnce()
  stats_server.InitializeStatsServerOnce()
  webauth.InitializeWebAuthOnce()

  if not utils.TimeBasedCache.house_keeper_thread:
    utils.TimeBasedCache()
  utils.TimeBasedCache.house_keeper_thread.exit = True
  utils.TimeBasedCache.house_keeper_thread.join()

  INIT_RAN = True
Beispiel #7
0
  def testDir(self):
    with temp.AutoTempDirPath() as dirpath:
      filepath = temp.TempFilePath(dir=dirpath)

      self.assertTrue(os.path.exists(filepath))
      self.assertStartsWith(filepath, dirpath)

      os.remove(filepath)
Beispiel #8
0
  def testEmptyFileCreation(self):
    filepath = temp.TempFilePath()

    self.assertTrue(os.path.exists(filepath))
    with io.open(filepath, "rb") as filedesc:
      self.assertEmpty(filedesc.read())

    os.remove(filepath)
Beispiel #9
0
    def testGetAllFiles(self):
        with temp.AutoTempDirPath(remove_non_empty=True) as tmpdir_path:
            foo_path = temp.TempFilePath(suffix="foo.yaml")
            bar_path = temp.TempFilePath(suffix="bar.json")
            baz_path = temp.TempFilePath(suffix="baz.yaml")
            quux_path = temp.TempFilePath(dir=tmpdir_path, suffix="quux.yaml")
            norf_path = temp.TempFilePath(dir=tmpdir_path, suffix="norf.json")
            thud_path = temp.TempFilePath(dir=tmpdir_path, suffix="thud.xml")

            self.sources.AddFile(foo_path)
            self.sources.AddFile(bar_path)
            self.sources.AddDir(tmpdir_path)

            files = list(self.sources.GetAllFiles())
            self.assertIn(foo_path, files)
            self.assertIn(bar_path, files)
            self.assertIn(quux_path, files)
            self.assertIn(norf_path, files)
            self.assertNotIn(baz_path, files)
            self.assertNotIn(thud_path, files)
Beispiel #10
0
 def setUp(self):
     super().setUp()
     self.temp_filepath = temp.TempFilePath()
     self.addCleanup(lambda: os.remove(self.temp_filepath))
Beispiel #11
0
 def setUp(self):
   super(ConditionTestMixin, self).setUp()
   self.temp_filepath = temp.TempFilePath()
   self.addCleanup(lambda: os.remove(self.temp_filepath))
Beispiel #12
0
 def setUp(self):
     super(ConditionTestMixin, self).setUp()
     self.temp_filepath = temp.TempFilePath()
Beispiel #13
0
 def setUp(self):
   super(FileReaderTest, self).setUp()
   self.temp_filepath = temp.TempFilePath()
Beispiel #14
0
 def setUp(self):
   super(StreamFilePathTest, self).setUp()
   self.temp_filepath = temp.TempFilePath()