text:
namespace {

// Extension ID of chrome/test/data/extensions/good.crx
const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";

// Explicit expectations from the caller of GetTrackedPrefHistogramCount(). This
// enables detailed reporting of the culprit on failure.
enum AllowedBuckets {
  // Allow no samples in any buckets.
  ALLOW_NONE = -1,
  // Any integer between BEGIN_ALLOW_SINGLE_BUCKET and END_ALLOW_SINGLE_BUCKET
  // indicates that only this specific bucket is allowed to have a sample.
  BEGIN_ALLOW_SINGLE_BUCKET = 0,
  END_ALLOW_SINGLE_BUCKET = 100,
  // Allow any buckets (no extra verifications performed).
  ALLOW_ANY
};

#if defined(OS_WIN)
base::string16 GetRegistryPathForTestProfile() {
  base::FilePath profile_dir;
  EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &profile_dir));
  return L"SOFTWARE\\Chromium\\PrefHashBrowserTest\\" +
         profile_dir.BaseName().value();
}
#endif

// Returns the number of times |histogram_name| was reported so far; adding the
// results of the first 100 buckets (there are only ~19 reporting IDs as of this
// writing; varies depending on the platform). |allowed_buckets| hints at extra
// requirements verified in this method (see AllowedBuckets for details).
int GetTrackedPrefHistogramCount(const char* histogram_name,
                                 const char* histogram_suffix,
                                 int allowed_buckets) {
  std::string full_histogram_name(histogram_name);
  if (*histogram_suffix)
    full_histogram_name.append(".").append(histogram_suffix);
  const base::HistogramBase* histogram =
      base::StatisticsRecorder::FindHistogram(full_histogram_name);
  if (!histogram)
    return 0;

  std::unique_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples());
  int sum = 0;
  for (int i = 0; i < 100; ++i) {
    int count_for_id = samples->GetCount(i);
    EXPECT_GE(count_for_id, 0);
    sum += count_for_id;

    if (allowed_buckets == ALLOW_NONE ||
        (allowed_buckets != ALLOW_ANY && i != allowed_buckets)) {
      EXPECT_EQ(0, count_for_id) << "Unexpected reporting_id: " << i;
    }
  }
  return sum;
}

// Helper function to call GetTrackedPrefHistogramCount with no external
// validation suffix.
int GetTrackedPrefHistogramCount(const char* histogram_name,
                                 int allowed_buckets) {
  return GetTrackedPrefHistogramCount(histogram_name, "", allowed_buckets);
}

std::unique_ptr<base::DictionaryValue> ReadPrefsDictionary(
    const base::FilePath& pref_file) {
  JSONFileValueDeserializer deserializer(pref_file);
  int error_code = JSONFileValueDeserializer::JSON_NO_ERROR;
  std::string error_str;
  std::unique_ptr<base::Value> prefs =
      deserializer.Deserialize(&error_code, &error_str);
  if (!prefs || error_code != JSONFileValueDeserializer::JSON_NO_ERROR) {
    ADD_FAILURE() << "Error #" << error_code << ": " << error_str;
    return std::unique_ptr<base::DictionaryValue>();
  }
  if (!prefs->IsType(base::Value::Type::DICTIONARY)) {
    ADD_FAILURE();
    return std::unique_ptr<base::DictionaryValue>();
  }
  return std::unique_ptr<base::DictionaryValue>(
      static_cast<base::DictionaryValue*>(prefs.release()));
}

// Returns whether external validation is supported on the platform through
// storing MACs in the registry.
bool SupportsRegistryValidation() {
#if defined(OS_WIN)
  return true;
#else
  return false;
#endif
}

#define PREF_HASH_BROWSER_TEST(fixture, test_name)                          \
  IN_PROC_BROWSER_TEST_P(fixture, PRE_##test_name) {                        \
    SetupPreferences();                                                     \
  }                                                                         \
  IN_PROC_BROWSER_TEST_P(fixture, test_name) {                              \
    VerifyReactionToPrefAttack();                                           \
  }                                                                         \
  INSTANTIATE_TEST_CASE_P(                                                  \
      fixture##Instance,                                                    \
      fixture,                                                              \
      testing::Values(                                                      \
          chrome_prefs::internals::kSettingsEnforcementGroupNoEnforcement,  \
          chrome_prefs::internals::kSettingsEnforcementGroupEnforceAlways,  \
          chrome_prefs::internals::                                         \
              kSettingsEnforcementGroupEnforceAlwaysWithDSE,                \
          chrome_prefs::internals::                                         \
              kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE));

// A base fixture designed such that implementations do two things:
//  1) Override all three pure-virtual methods below to setup, attack, and
//     verify preferenes throughout the tests provided by this fixture.
//  2) Instantiate their test via the PREF_HASH_BROWSER_TEST macro above.
// Based on top of ExtensionBrowserTest to allow easy interaction with the
// ExtensionService.
class PrefHashBrowserTestBase
    : public ExtensionBrowserTest,
      public testing::WithParamInterface<std::string> {
 public:
  // List of potential protection levels for this test in strict increasing
  // order of protection levels.
  enum SettingsProtectionLevel {
    PROTECTION_DISABLED_ON_PLATFORM,
    PROTECTION_DISABLED_FOR_GROUP,
    PROTECTION_ENABLED_BASIC,
    PROTECTION_ENABLED_DSE,
    PROTECTION_ENABLED_EXTENSIONS,
    // Represents the strongest level (i.e. always equivalent to the last one in
    // terms of protection), leave this one last when adding new levels.
    PROTECTION_ENABLED_ALL
  };

  PrefHashBrowserTestBase()
      : protection_level_(GetProtectionLevelFromTrialGroup(GetParam())) {
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    EXPECT_FALSE(command_line->HasSwitch(switches::kForceFieldTrials));
    command_line->AppendSwitchASCII(
        switches::kForceFieldTrials,
        std::string(chrome_prefs::internals::kSettingsEnforcementTrialName) +
            "/" + GetParam() + "/");
#if defined(OS_CHROMEOS)
    command_line->AppendSwitch(
        chromeos::switches::kIgnoreUserProfileMappingForTests);
#endif
  }

  bool SetUpUserDataDirectory() override {
    // Do the normal setup in the PRE test and attack preferences in the main
    // test.
    if (IsPRETest())
      return ExtensionBrowserTest::SetUpUserDataDirectory();

#if defined(OS_CHROMEOS)
    // For some reason, the Preferences file does not exist in the location
    // below on Chrome OS. Since protection is disabled on Chrome OS, it's okay
    // to simply not attack preferences at all (and still assert that no
    // hardening related histogram kicked in in VerifyReactionToPrefAttack()).
    // TODO(gab): Figure out why there is no Preferences file in this location
    // on Chrome OS (and re-enable the section disabled for OS_CHROMEOS further
    // below).
    EXPECT_EQ(PROTECTION_DISABLED_ON_PLATFORM, protection_level_);
    return true;
#endif

    base::FilePath profile_dir;
    EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &profile_dir));
    profile_dir = profile_dir.AppendASCII(TestingProfile::kTestUserProfileDir);

    // Sanity check that old protected pref file is never present in modern
    // Chromes.
    EXPECT_FALSE(base::PathExists(
        profile_dir.Append(chrome::kProtectedPreferencesFilenameDeprecated)));

    // Read the preferences from disk.

    const base::FilePath unprotected_pref_file =
        profile_dir.Append(chrome::kPreferencesFilename);
    EXPECT_TRUE(base::PathExists(unprotected_pref_file));

    const base::FilePath protected_pref_file =
        profile_dir.Append(chrome::kSecurePreferencesFilename);
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM,
              base::PathExists(protected_pref_file));

    std::unique_ptr<base::DictionaryValue> unprotected_preferences(
        ReadPrefsDictionary(unprotected_pref_file));
    if (!unprotected_preferences)
      return false;

    std::unique_ptr<base::DictionaryValue> protected_preferences;
    if (protection_level_ > PROTECTION_DISABLED_ON_PLATFORM) {
      protected_preferences = ReadPrefsDictionary(protected_pref_file);
      if (!protected_preferences)
        return false;
    }

    // Let the underlying test modify the preferences.
    AttackPreferencesOnDisk(unprotected_preferences.get(),
                            protected_preferences.get());

    // Write the modified preferences back to disk.

    JSONFileValueSerializer unprotected_prefs_serializer(unprotected_pref_file);
    EXPECT_TRUE(
        unprotected_prefs_serializer.Serialize(*unprotected_preferences));

    if (protected_preferences) {
      JSONFileValueSerializer protected_prefs_serializer(protected_pref_file);
      EXPECT_TRUE(protected_prefs_serializer.Serialize(*protected_preferences));
    }

    return true;
  }

  void SetUpInProcessBrowserTestFixture() override {
    ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();

    // Bots are on a domain, turn off the domain check for settings hardening in
    // order to be able to test all SettingsEnforcement groups.
    chrome_prefs::DisableDomainCheckForTesting();

#if defined(OS_WIN)
    // Avoid polluting prefs for the user and the bots by writing to a specific
    // testing registry path.
    registry_key_for_external_validation_ = GetRegistryPathForTestProfile();
    ProfilePrefStoreManager::SetPreferenceValidationRegistryPathForTesting(
        &registry_key_for_external_validation_);

    // Keys should be unique, but to avoid flakes in the long run make sure an
    // identical test key wasn't left behind by a previous test.
    if (IsPRETest()) {
      base::win::RegKey key;
      if (key.Open(HKEY_CURRENT_USER,
                   registry_key_for_external_validation_.c_str(),
                   KEY_SET_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS) {
        LONG result = key.DeleteKey(L"");
        ASSERT_TRUE(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND);
      }
    }
#endif
  }

  void TearDown() override {
#if defined(OS_WIN)
    // When done, delete the Registry key to avoid polluting the registry.
    // TODO(proberge): it would be nice to delete keys from interrupted tests
    // as well.
    if (!IsPRETest()) {
      base::string16 registry_key = GetRegistryPathForTestProfile();
      base::win::RegKey key;
      if (key.Open(HKEY_CURRENT_USER, registry_key.c_str(),
                   KEY_SET_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS) {
        LONG result = key.DeleteKey(L"");
        ASSERT_TRUE(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND);
      }
    }
#endif
    ExtensionBrowserTest::TearDown();
  }

  // In the PRE_ test, find the number of tracked preferences that were
  // initialized and save it to a file to be read back in the main test and used
  // as the total number of tracked preferences.
  void SetUpOnMainThread() override {
    ExtensionBrowserTest::SetUpOnMainThread();

    // File in which the PRE_ test will save the number of tracked preferences
    // on this platform.
    const char kNumTrackedPrefFilename[] = "NumTrackedPrefs";

    base::FilePath num_tracked_prefs_file;
    ASSERT_TRUE(
        PathService::Get(chrome::DIR_USER_DATA, &num_tracked_prefs_file));
    num_tracked_prefs_file =
        num_tracked_prefs_file.AppendASCII(kNumTrackedPrefFilename);

    if (IsPRETest()) {
      num_tracked_prefs_ = GetTrackedPrefHistogramCount(
          user_prefs::tracked::kTrackedPrefHistogramNullInitialized, ALLOW_ANY);
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM,
                num_tracked_prefs_ > 0);

      // Split tracked prefs are reported as Unchanged not as NullInitialized
      // when an empty dictionary is encountered on first run (this should only
      // hit for pref #5 in the current design).
      int num_split_tracked_prefs = GetTrackedPrefHistogramCount(
          user_prefs::tracked::kTrackedPrefHistogramUnchanged,
          BEGIN_ALLOW_SINGLE_BUCKET + 5);
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                num_split_tracked_prefs);

      if (SupportsRegistryValidation()) {
        // Same checks as above, but for the registry.
        num_tracked_prefs_ = GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
            user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
            ALLOW_ANY);
        EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM,
                  num_tracked_prefs_ > 0);

        int num_split_tracked_prefs = GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged,
            user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
            BEGIN_ALLOW_SINGLE_BUCKET + 5);
        EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                  num_split_tracked_prefs);
      }

      num_tracked_prefs_ += num_split_tracked_prefs;

      std::string num_tracked_prefs_str = base::IntToString(num_tracked_prefs_);
      EXPECT_EQ(static_cast<int>(num_tracked_prefs_str.size()),
                base::WriteFile(num_tracked_prefs_file,
                                num_tracked_prefs_str.c_str(),
                                num_tracked_prefs_str.size()));
    } else {
      std::string num_tracked_prefs_str;
      EXPECT_TRUE(base::ReadFileToString(num_tracked_prefs_file,
                                         &num_tracked_prefs_str));
      EXPECT_TRUE(
          base::StringToInt(num_tracked_prefs_str, &num_tracked_prefs_));
    }
  }

 protected:
  // Called from the PRE_ test's body. Overrides should use it to setup
  // preferences through Chrome.
  virtual void SetupPreferences() = 0;

  // Called prior to the main test launching its browser. Overrides should use
  // it to attack preferences. |(un)protected_preferences| represent the state
  // on disk prior to launching the main test, they can be modified by this
  // method and modifications will be flushed back to disk before launching the
  // main test. |unprotected_preferences| is never NULL, |protected_preferences|
  // may be NULL if in PROTECTION_DISABLED_ON_PLATFORM mode.
  virtual void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) = 0;

  // Called from the body of the main test. Overrides should use it to verify
  // that the browser had the desired reaction when faced when the attack
  // orchestrated in AttackPreferencesOnDisk().
  virtual void VerifyReactionToPrefAttack() = 0;

  int num_tracked_prefs() const { return num_tracked_prefs_; }

  const SettingsProtectionLevel protection_level_;

 private:
  // Returns true if this is the PRE_ phase of the test.
  bool IsPRETest() {
    return base::StartsWith(
        testing::UnitTest::GetInstance()->current_test_info()->name(), "PRE_",
        base::CompareCase::SENSITIVE);
  }

  SettingsProtectionLevel GetProtectionLevelFromTrialGroup(
      const std::string& trial_group) {
    if (!ProfilePrefStoreManager::kPlatformSupportsPreferenceTracking)
      return PROTECTION_DISABLED_ON_PLATFORM;

// Protection levels can't be adjusted via --force-fieldtrials in official
// builds.
#if defined(OFFICIAL_BUILD)

#if defined(OS_WIN)
    // The strongest mode is enforced on Windows in the absence of a field
    // trial.
    return PROTECTION_ENABLED_ALL;
#else
    return PROTECTION_DISABLED_FOR_GROUP;
#endif

#else  // defined(OFFICIAL_BUILD)

    using namespace chrome_prefs::internals;
    if (trial_group == kSettingsEnforcementGroupNoEnforcement) {
      return PROTECTION_DISABLED_FOR_GROUP;
    } else if (trial_group == kSettingsEnforcementGroupEnforceAlways) {
      return PROTECTION_ENABLED_BASIC;
    } else if (trial_group == kSettingsEnforcementGroupEnforceAlwaysWithDSE) {
      return PROTECTION_ENABLED_DSE;
    } else if (trial_group ==
               kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE) {
      return PROTECTION_ENABLED_EXTENSIONS;
    } else {
      ADD_FAILURE();
      return static_cast<SettingsProtectionLevel>(-1);
    }

#endif  // defined(OFFICIAL_BUILD)

  }

  int num_tracked_prefs_;

#if defined(OS_WIN)
  base::string16 registry_key_for_external_validation_;
#endif
};

}  // namespace

// Verifies that nothing is reset when nothing is tampered with.
// Also sanity checks that the expected preferences files are in place.
class PrefHashBrowserTestUnchangedDefault : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    // Default Chrome setup.
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    // No attack.
  }

  void VerifyReactionToPrefAttack() override {
    // Expect all prefs to be reported as Unchanged with no resets.
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs()
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_NONE));

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramChanged, ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramMigratedLegacyDeviceId,
               ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // Expect all prefs to be reported as Unchanged.
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
                    ? num_tracked_prefs()
                    : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramUnchanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    ALLOW_ANY));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUnchangedDefault, UnchangedDefault);

// Augments PrefHashBrowserTestUnchangedDefault to confirm that nothing is reset
// when nothing is tampered with, even if Chrome itself wrote custom prefs in
// its last run.
class PrefHashBrowserTestUnchangedCustom
    : public PrefHashBrowserTestUnchangedDefault {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");

    InstallExtensionWithUIAutoConfirm(
        test_data_dir_.AppendASCII("good.crx"), 1, browser());
  }

  void VerifyReactionToPrefAttack() override {
    // Make sure the settings written in the last run stuck.
    EXPECT_EQ("http://example.com",
              profile()->GetPrefs()->GetString(prefs::kHomePage));

    EXPECT_TRUE(extension_service()->GetExtensionById(kGoodCrxId, false));

    // Reaction should be identical to unattacked default prefs.
    PrefHashBrowserTestUnchangedDefault::VerifyReactionToPrefAttack();
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUnchangedCustom, UnchangedCustom);

// Verifies that cleared prefs are reported.
class PrefHashBrowserTestClearedAtomic : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    base::DictionaryValue* selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_BASIC ? protected_preferences
                                                      : unprotected_preferences;
    // |selected_prefs| should never be NULL under the protection level picking
    // it.
    EXPECT_TRUE(selected_prefs);
    EXPECT_TRUE(selected_prefs->Remove(prefs::kHomePage, NULL));
  }

  void VerifyReactionToPrefAttack() override {
    // The clearance of homepage should have been noticed (as pref #2 being
    // cleared), but shouldn't have triggered a reset (as there is nothing we
    // can do when the pref is already gone).
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramCleared,
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - 1
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_NONE));

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramChanged, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramMigratedLegacyDeviceId,
               ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // Expect homepage clearance to have been noticed by registry validation.
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramCleared,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 2));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestClearedAtomic, ClearedAtomic);

// Verifies that clearing the MACs results in untrusted Initialized pings for
// non-null protected prefs.
class PrefHashBrowserTestUntrustedInitialized : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    // Explicitly set the DSE (it's otherwise NULL by default, preventing
    // thorough testing of the PROTECTION_ENABLED_DSE level).
    DefaultSearchManager default_search_manager(
        profile()->GetPrefs(), DefaultSearchManager::ObserverCallback());
    DefaultSearchManager::Source dse_source =
        static_cast<DefaultSearchManager::Source>(-1);

    const TemplateURLData* default_template_url_data =
        default_search_manager.GetDefaultSearchEngine(&dse_source);
    EXPECT_EQ(DefaultSearchManager::FROM_FALLBACK, dse_source);

    default_search_manager.SetUserSelectedDefaultSearchEngine(
        *default_template_url_data);

    default_search_manager.GetDefaultSearchEngine(&dse_source);
    EXPECT_EQ(DefaultSearchManager::FROM_USER, dse_source);

    // Also explicitly set an atomic pref that falls under
    // PROTECTION_ENABLED_BASIC.
    profile()->GetPrefs()->SetInteger(prefs::kRestoreOnStartup,
                                      SessionStartupPref::URLS);
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    unprotected_preferences->Remove("protection.macs", NULL);
    if (protected_preferences)
      protected_preferences->Remove("protection.macs", NULL);
  }

  void VerifyReactionToPrefAttack() override {
    // Preferences that are NULL by default will be NullInitialized.
    int num_null_values = GetTrackedPrefHistogramCount(
        user_prefs::tracked::kTrackedPrefHistogramNullInitialized, ALLOW_ANY);
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM,
              num_null_values > 0);
    if (num_null_values > 0) {
      // This test requires that at least 3 prefs be non-null (extensions, DSE,
      // and 1 atomic pref explictly set for this test above).
      EXPECT_GE(num_tracked_prefs() - num_null_values, 3);
    }

    // Expect all non-null prefs to be reported as Initialized (with
    // accompanying resets or wanted resets based on the current protection
    // level).
    EXPECT_EQ(
        num_tracked_prefs() - num_null_values,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramInitialized, ALLOW_ANY));

    int num_protected_prefs = 0;
    // A switch statement falling through each protection level in decreasing
    // levels of protection to add expectations for each level which augments
    // the previous one.
    switch (protection_level_) {
      case PROTECTION_ENABLED_ALL:
        // Falls through.
      case PROTECTION_ENABLED_EXTENSIONS:
        ++num_protected_prefs;
        // Falls through.
      case PROTECTION_ENABLED_DSE:
        ++num_protected_prefs;
        // Falls through.
      case PROTECTION_ENABLED_BASIC:
        num_protected_prefs += num_tracked_prefs() - num_null_values - 2;
        // Falls through.
      case PROTECTION_DISABLED_FOR_GROUP:
        // No protection. Falls through.
      case PROTECTION_DISABLED_ON_PLATFORM:
        // No protection.
        break;
    }

    EXPECT_EQ(
        num_tracked_prefs() - num_null_values - num_protected_prefs,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramWantedReset, ALLOW_ANY));
    EXPECT_EQ(num_protected_prefs,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_ANY));

    // Explicitly verify the result of reported resets.

    DefaultSearchManager default_search_manager(
        profile()->GetPrefs(), DefaultSearchManager::ObserverCallback());
    DefaultSearchManager::Source dse_source =
        static_cast<DefaultSearchManager::Source>(-1);
    default_search_manager.GetDefaultSearchEngine(&dse_source);
    EXPECT_EQ(protection_level_ < PROTECTION_ENABLED_DSE
                  ? DefaultSearchManager::FROM_USER
                  : DefaultSearchManager::FROM_FALLBACK,
              dse_source);

    EXPECT_EQ(protection_level_ < PROTECTION_ENABLED_BASIC,
              profile()->GetPrefs()->GetInteger(prefs::kRestoreOnStartup) ==
                  SessionStartupPref::URLS);

    // Nothing else should have triggered.
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramUnchanged,
                     ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramChanged, ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramMigratedLegacyDeviceId,
               ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // The MACs have been cleared but the preferences have not been tampered.
      // The registry should report all prefs as unchanged.
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
                    ? num_tracked_prefs()
                    : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramUnchanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    ALLOW_ANY));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUntrustedInitialized,
                       UntrustedInitialized);

// Verifies that changing an atomic pref results in it being reported (and reset
// if the protection level allows it).
class PrefHashBrowserTestChangedAtomic : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetInteger(prefs::kRestoreOnStartup,
                                      SessionStartupPref::URLS);

    ListPrefUpdate update(profile()->GetPrefs(),
                          prefs::kURLsToRestoreOnStartup);
    update->AppendString("http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    base::DictionaryValue* selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_BASIC ? protected_preferences
                                                      : unprotected_preferences;
    // |selected_prefs| should never be NULL under the protection level picking
    // it.
    EXPECT_TRUE(selected_prefs);
    base::ListValue* startup_urls;
    EXPECT_TRUE(
        selected_prefs->GetList(prefs::kURLsToRestoreOnStartup, &startup_urls));
    EXPECT_TRUE(startup_urls);
    EXPECT_EQ(1U, startup_urls->GetSize());
    startup_urls->AppendString("http://example.org");
  }

  void VerifyReactionToPrefAttack() override {
    // Expect a single Changed event for tracked pref #4 (startup URLs).
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 4));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - 1
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_BASIC)
                  ? 1
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 4));
    EXPECT_EQ(protection_level_ >= PROTECTION_ENABLED_BASIC ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 4));

// TODO(gab): This doesn't work on OS_CHROMEOS because we fail to attack
// Preferences.
#if !defined(OS_CHROMEOS)
    // Explicitly verify the result of reported resets.
    EXPECT_EQ(protection_level_ >= PROTECTION_ENABLED_BASIC ? 0U : 2U,
              profile()
                  ->GetPrefs()
                  ->GetList(prefs::kURLsToRestoreOnStartup)
                  ->GetSize());
#endif

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramMigratedLegacyDeviceId,
               ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // Expect a single Changed event for tracked pref #4 (startup URLs).
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 4));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestChangedAtomic, ChangedAtomic);

// Verifies that changing or adding an entry in a split pref results in both
// items being reported (and remove if the protection level allows it).
class PrefHashBrowserTestChangedSplitPref : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    InstallExtensionWithUIAutoConfirm(
        test_data_dir_.AppendASCII("good.crx"), 1, browser());
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    base::DictionaryValue* selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_EXTENSIONS
            ? protected_preferences
            : unprotected_preferences;
    // |selected_prefs| should never be NULL under the protection level picking
    // it.
    EXPECT_TRUE(selected_prefs);
    base::DictionaryValue* extensions_dict;
    EXPECT_TRUE(selected_prefs->GetDictionary(
        extensions::pref_names::kExtensions, &extensions_dict));
    EXPECT_TRUE(extensions_dict);

    // Tamper with any installed setting for good.crx
    base::DictionaryValue* good_crx_dict;
    EXPECT_TRUE(extensions_dict->GetDictionary(kGoodCrxId, &good_crx_dict));
    int good_crx_state;
    EXPECT_TRUE(good_crx_dict->GetInteger("state", &good_crx_state));
    EXPECT_EQ(extensions::Extension::ENABLED, good_crx_state);
    good_crx_dict->SetInteger("state", extensions::Extension::DISABLED);

    // Drop a fake extension (for the purpose of this test, dropped settings
    // don't need to be valid extension settings).
    base::DictionaryValue* fake_extension = new base::DictionaryValue;
    fake_extension->SetString("name", "foo");
    extensions_dict->Set(std::string(32, 'a'), fake_extension);
  }

  void VerifyReactionToPrefAttack() override {
    // Expect a single split pref changed report with a count of 2 for tracked
    // pref #5 (extensions).
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 5));
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  "Settings.TrackedSplitPreferenceChanged.extensions.settings",
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));

    // Everything else should have remained unchanged.
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - 1
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_EXTENSIONS)
                  ? 1
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 5));
    EXPECT_EQ(protection_level_ >= PROTECTION_ENABLED_EXTENSIONS ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 5));

    EXPECT_EQ(protection_level_ < PROTECTION_ENABLED_EXTENSIONS,
              extension_service()->GetExtensionById(kGoodCrxId, true) != NULL);

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramMigratedLegacyDeviceId,
               ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // Expect that the registry validation caught the invalid MAC in split
      // pref #5 (extensions).
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 5));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestChangedSplitPref, ChangedSplitPref);

// Verifies that adding a value to unprotected preferences for a key which is
// still using the default (i.e. has no value stored in protected preferences)
// doesn't allow that value to slip in with no valid MAC (regression test for
// http://crbug.com/414554)
class PrefHashBrowserTestUntrustedAdditionToPrefs
    : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    // Ensure there is no user-selected value for kRestoreOnStartup.
    EXPECT_FALSE(
        profile()->GetPrefs()->GetUserPrefValue(prefs::kRestoreOnStartup));
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    unprotected_preferences->SetInteger(prefs::kRestoreOnStartup,
                                        SessionStartupPref::LAST);
  }

  void VerifyReactionToPrefAttack() override {
    // Expect a single Changed event for tracked pref #3 (kRestoreOnStartup) if
    // not protecting; if protection is enabled the change should be a no-op.
    int changed_expected =
        protection_level_ == PROTECTION_DISABLED_FOR_GROUP ? 1 : 0;
    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_BASIC)
                  ? changed_expected
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 3));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - changed_expected
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_BASIC)
                  ? 1
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 3));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_NONE));

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramMigratedLegacyDeviceId,
               ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
                 protection_level_ < PROTECTION_ENABLED_BASIC)
                    ? changed_expected
                    : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 3));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUntrustedAdditionToPrefs,
                       UntrustedAdditionToPrefs);

// Verifies that adding a value to unprotected preferences while wiping a
// user-selected value from protected preferences doesn't allow that value to
// slip in with no valid MAC (regression test for http://crbug.com/414554).
class PrefHashBrowserTestUntrustedAdditionToPrefsAfterWipe
    : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    // Set or change the value in Preferences to the attacker's choice.
    unprotected_preferences->SetString(prefs::kHomePage, "http://example.net");
    // Clear the value in Secure Preferences, if any.
    if (protected_preferences)
      protected_preferences->Remove(prefs::kHomePage, NULL);
  }

  void VerifyReactionToPrefAttack() override {
    // Expect a single Changed event for tracked pref #2 (kHomePage) if
    // not protecting; if protection is enabled the change should be a Cleared.
    int changed_expected =
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
        protection_level_ < PROTECTION_ENABLED_BASIC
        ? 1 : 0;
    int cleared_expected =
        protection_level_ >= PROTECTION_ENABLED_BASIC
        ? 1 : 0;
    EXPECT_EQ(changed_expected,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));
    EXPECT_EQ(cleared_expected,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramCleared,
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - changed_expected - cleared_expected
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ(changed_expected,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_NONE));

    // Nothing else should have triggered.
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramMigratedLegacyDeviceId,
               ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      EXPECT_EQ(changed_expected,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 2));
      EXPECT_EQ(cleared_expected,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramCleared,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 2));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUntrustedAdditionToPrefsAfterWipe,
                       UntrustedAdditionToPrefsAfterWipe);

#if defined(OS_WIN)
class PrefHashBrowserTestRegistryValidationFailure
    : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    base::string16 registry_key =
        GetRegistryPathForTestProfile() + L"\\PreferenceMACs\\Default";
    base::win::RegKey key;
    ASSERT_EQ(ERROR_SUCCESS, key.Open(HKEY_CURRENT_USER, registry_key.c_str(),
                                      KEY_SET_VALUE | KEY_WOW64_32KEY));
    // An incorrect hash should still have the correct size.
    ASSERT_EQ(ERROR_SUCCESS,
              key.WriteValue(L"homepage", base::string16(64, 'A').c_str()));
  }

  void VerifyReactionToPrefAttack() override {
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs()
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    if (SupportsRegistryValidation()) {
      // Expect that the registry validation caught the invalid MAC for pref #2
      // (homepage).
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 2));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestRegistryValidationFailure,
                       RegistryValidationFailure);
#endif

// Verifies that all preferences related to choice of default search engine are
// protected.
class PrefHashBrowserTestDefaultSearch : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    // Set user selected default search engine.
    DefaultSearchManager default_search_manager(
        profile()->GetPrefs(), DefaultSearchManager::ObserverCallback());
    DefaultSearchManager::Source dse_source =
        static_cast<DefaultSearchManager::Source>(-1);

    TemplateURLData user_dse;
    user_dse.SetKeyword(base::UTF8ToUTF16("userkeyword"));
    user_dse.SetShortName(base::UTF8ToUTF16("username"));
    user_dse.SetURL("http://user_default_engine/search?q=good_user_query");
    default_search_manager.SetUserSelectedDefaultSearchEngine(user_dse);

    const TemplateURLData* current_dse =
        default_search_manager.GetDefaultSearchEngine(&dse_source);
    EXPECT_EQ(DefaultSearchManager::FROM_USER, dse_source);
    EXPECT_EQ(current_dse->keyword(), base::UTF8ToUTF16("userkeyword"));
    EXPECT_EQ(current_dse->short_name(), base::UTF8ToUTF16("username"));
    EXPECT_EQ(current_dse->url(),
              "http://user_default_engine/search?q=good_user_query");
  }

  void AttackPreferencesOnDisk(
      base::DictionaryValue* unprotected_preferences,
      base::DictionaryValue* protected_preferences) override {
    static constexpr char default_search_provider_data[] = R"(
    {
      "default_search_provider_data" : {
        "template_url_data" : {
          "keyword" : "badkeyword",
          "short_name" : "badname",
          "url" : "http://bad_default_engine/search?q=dirty_user_query"
        }
      }
    })";
    static constexpr char search_provider_overrides[] = R"(
    {
      "search_provider_overrides" : [
        {
          "keyword" : "badkeyword",
          "name" : "badname",
          "search_url" : "http://bad_default_engine/search?q=dirty_user_query",
          "encoding" : "utf-8",
          "id" : 1
        }, {
          "keyword" : "badkeyword2",
          "name" : "badname2",
          "search_url" : "http://bad_default_engine2/search?q=dirty_user_query",
          "encoding" : "utf-8",
          "id" : 2
        }
      ]
    })";

    // Try to override default search in all three of available preferences.
    auto attack1 = base::DictionaryValue::From(
        base::JSONReader::Read(default_search_provider_data));
    auto attack2 = base::DictionaryValue::From(
        base::JSONReader::Read(search_provider_overrides));
    unprotected_preferences->MergeDictionary(attack1.get());
    unprotected_preferences->MergeDictionary(attack2.get());
    if (protected_preferences) {
      // Override here, too.
      protected_preferences->MergeDictionary(attack1.get());
      protected_preferences->MergeDictionary(attack2.get());
    }
  }

  void VerifyReactionToPrefAttack() override {
    DefaultSearchManager default_search_manager(
        profile()->GetPrefs(), DefaultSearchManager::ObserverCallback());
    DefaultSearchManager::Source dse_source =
        static_cast<DefaultSearchManager::Source>(-1);

    const TemplateURLData* current_dse =
        default_search_manager.GetDefaultSearchEngine(&dse_source);

    if (protection_level_ < PROTECTION_ENABLED_DSE) {
// This doesn't work on OS_CHROMEOS because we fail to attack Preferences.
#if !defined(OS_CHROMEOS)
      // Attack is successful.
      EXPECT_EQ(DefaultSearchManager::FROM_USER, dse_source);
      EXPECT_EQ(current_dse->keyword(), base::UTF8ToUTF16("badkeyword"));
      EXPECT_EQ(current_dse->short_name(), base::UTF8ToUTF16("badname"));
      EXPECT_EQ(current_dse->url(),
                "http://bad_default_engine/search?q=dirty_user_query");
#endif
    } else {
      // Attack fails.
      EXPECT_EQ(DefaultSearchManager::FROM_FALLBACK, dse_source);
      EXPECT_NE(current_dse->keyword(), base::UTF8ToUTF16("badkeyword"));
      EXPECT_NE(current_dse->short_name(), base::UTF8ToUTF16("badname"));
      EXPECT_NE(current_dse->url(),
                "http://bad_default_engine/search?q=dirty_user_query");
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestDefaultSearch, SearchProtected);


text:
                        STARTING AT $120 / NIGHTSIGNATURE WATER VIEW

                        Phasellus laoreet lorem vel dolor tempus vehicula. Integer legentibus erat a ante historiarum dapibus. Plura mihi bona sunt, inclinet, amari petere vellent. Quae vero auctorem tractata ab fiducia dicuntur.

                        Book the Signature Water View Now

                        STARTING AT $120 / NIGHTSIGNATURE WATER SIDE

                        Phasellus laoreet lorem vel dolor tempus vehicula. Integer legentibus erat a ante historiarum dapibus. Plura mihi bona sunt, inclinet, amari petere vellent. Quae vero auctorem tractata ab fiducia dicuntur.

                        Book the Signature Water Side Now

redpajama_set_name: RedPajamaGithub


text:
package net.tatans.rhea.network.event;

import android.widget.AdapterView;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by Yuriy on 16-04-30.
 *  ·µ»ØÀàÐÍ void
 * ´«ÈëµÄ²ÎÊý AdapterView<?> parent, ViewIoc view, int position, long id
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@EventBase(
        listenerType = AdapterView.OnItemClickListener.class,
        listenerSetter = "setOnItemClickListener",
        methodName = "onItemClick")
public @interface OnItemClick {
    int[] value();

    int[] parentId() default 0;
}


text:
#pragma once
#include <aws/states/SFN_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace SFN
{
namespace Model
{

  class AWS_SFN_API ActivitySucceededEventDetails
  {
  public:
    ActivitySucceededEventDetails();
    ActivitySucceededEventDetails(const Aws::Utils::Json::JsonValue& jsonValue);
    ActivitySucceededEventDetails& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The JSON data output by the activity task.

     */
    inline const Aws::String& GetOutput() const{ return m_output; }

    /**
     *
The JSON data output by the activity task.

     */
    inline void SetOutput(const Aws::String& value) { m_outputHasBeenSet = true; m_output = value; }

    /**
     *
The JSON data output by the activity task.

     */
    inline void SetOutput(Aws::String&& value) { m_outputHasBeenSet = true; m_output = std::move(value); }

    /**
     *
The JSON data output by the activity task.

     */
    inline void SetOutput(const char* value) { m_outputHasBeenSet = true; m_output.assign(value); }

    /**
     *
The JSON data output by the activity task.

     */
    inline ActivitySucceededEventDetails& WithOutput(const Aws::String& value) { SetOutput(value); return *this;}

    /**
     *
The JSON data output by the activity task.

     */
    inline ActivitySucceededEventDetails& WithOutput(Aws::String&& value) { SetOutput(std::move(value)); return *this;}

    /**
     *
The JSON data output by the activity task.

     */
    inline ActivitySucceededEventDetails& WithOutput(const char* value) { SetOutput(value); return *this;}

  private:
    Aws::String m_output;
    bool m_outputHasBeenSet;
  };

} // namespace Model
} // namespace SFN
} // namespace Aws


text:
from charmhelpers.core.hookenv import log
from charmhelpers.core.hookenv import config
from charmhelpers.core.hookenv import open_port
from charmhelpers.core.hookenv import close_port
from charmhelpers.core.hookenv import status_set
from charmhelpers.core.hookenv import resource_get
from charmhelpers.core.hookenv import storage_get
from charmhelpers.core.hookenv import DEBUG
from charmhelpers.core import host
from charmhelpers.core import unitdata

from charms import apt, reactive
from charms.docker import Compose

from charms.reactive import hook, when, when_not, set_state
from charms.reactive import when_any
from charms.reactive import remove_state

from charms.templating.jinja2 import render

from subprocess import check_call

import os.path
import shutil
import subprocess
import time
import base64

@hook('start')
def start():
    compose = Compose('files/docker-registry')
    compose.up()
    open_port(config('registry_port'))
    status_set('active', 'Docker registry ready.')

@hook('stop')
def stop():
    compose = Compose('files/docker-registry')
    compose.down()
    close_port(config.previous('registry_port'))
    status_set('maintenance', 'Docker registry stopped.')

@when('docker.available')
@when_not('docker-registry.standalone.running')
def start_standalone():
    path = resource_get('registry')
    if path:
        check_call(['docker', 'load', '-i', path])

    render('docker-compose.yml',
           'files/docker-registry/docker-compose.yml',
           config())

    start()
    set_state('docker-registry.standalone.running')
    status_set('active', 'Docker registry ready.')

@when_any('config.changed.registry_port',
          'config.changed.registry_tag',
          'config.changed.registry_cert',
          'config.changed.registry_key',
          'config.changed.registry_htpasswd',
          'config.changed.registry_config')
def reconfigure():
    cfg = config()
    # guard on first run, no previous values, so do nothing
    if not cfg.previous('registry_port') or not cfg.previous('registry_tag'):
        return

    status_set('maintenance', 'Re-configuring port bindings.')
    close_port(cfg.previous('registry_port'))

    if config('registry_cert') and config('registry_key'):
        status_set('maintenance', 'Writing TLS files to /etc/ssl.')
        with open('/etc/ssl/certs/docker-registry.crt', 'wb') as f:
            f.write(base64.b64decode(config('registry_cert')))
        with open('/etc/ssl/private/docker-registry.key', 'wb') as f:
            f.write(base64.b64decode(config('registry_key')))

    if config('registry_htpasswd') and (not config('registry_key') or
                                        not config('registry_cert')):
        status_set(
            'blocked', 'Registry htpasswd needs TLS for basic-realm security')
        return
    else:
        status_set('maintenance', 'Writing htpasswd to /usr/local/etc.')
        with open('/usr/local/etc/htpasswd', 'wb') as f:
            f.write(base64.b64decode(config('registry_htpasswd')))

    if config('registry_config'):
        status_set('maintenance', 'Writing registry config to /usr/local/etc.')
        with open('/usr/local/etc/registry.yaml', 'wb') as f:
            f.write(base64.b64decode(config('registry_config')))

    status_set('maintenance', 'Re-generating Docker compose YAML.')
    render('docker-compose.yml',
           'files/docker-registry/docker-compose.yml',
           config())

    remove_state('docker-registry.standalone.running')
    remove_state('docker-registry.running')

    status_set('active', 'Docker registry ready.')

@when('website.available')
def configure_website(website):
    website.configure(port=config('registry_port'))

# storage support was all taken from the postgresql charm
data_path_key = 'docker-registry.storage.registry.path'
data_mount_key = 'docker-registry.storage.registry.mount'

@hook('docker-registry-storage-attached')
def attach():
    mount = storage_get()['location']
    unitdata.kv().set(data_mount_key, mount)
    unitdata.kv().set(
        data_path_key, os.path.join(mount, 'var/lib/docker'))

    log('Docker registry storage attached: {}'.format(mount))

    if os.path.exists('/var/lib/docker'):
        required_space = shutil.disk_usage('/var/lib/docker').used
        free_space = shutil.disk_usage(mount).free

        if required_space > free_space:
            status_set('blocked', 'Not enough free storage space.')
        return

    apt.queue_install(['rsync'])
    reactive.set_state('docker-registry.storage.docker-registry.attached')

@hook('docker-registry-storage-detaching')
def detaching():
    unitdata.kv().unset(data_mount_key)
    unitdata.kv().unset(data_path_key)
    reactive.remove_state('docker-registry.storage.docker-registry.attached')

@when('docker-registry.storage.docker-registry.attached')
@when('docker.available')
@when('docker-registry.standalone.running')
@when('apt.installed.rsync')
@when_not('docker-registry.storage.docker-registry.migrated')
def migrate():
    if reactive.is_state('docker-registry.standalone.running'):
        stop()
        host.service_stop('docker')

    old_data_dir = '/var/lib/docker'
    new_data_dir = unitdata.kv().get(data_path_key)

    if old_data_dir == new_data_dir:
        status_set(
            'blocked', 'Cannot migrate {} over itself.'.format(old_data_dir))
        return

    backup_data_dir = '{}-{}'.format(old_data_dir, int(time.time()))

    status_set('maintenance', 'Migrating data from {} to {}'.format(
        old_data_dir, new_data_dir))

    if os.path.exists(new_data_dir):
        assert os.path.isdir(new_data_dir), '{} is not a directory'
    else:
        os.makedirs(new_data_dir)
    shutil.chown(new_data_dir, 'root', 'root')
    os.chmod(new_data_dir, 0o700)

    try:
        rsync_cmd = ['rsync', '-av',
                     old_data_dir + '/',
                     new_data_dir + '/']
        log('Running {}'.format(' '.join(rsync_cmd)), DEBUG)
        subprocess.check_call(rsync_cmd, universal_newlines=True)
    except subprocess.CalledProcessError:
        status_set('blocked', 'Failed to sync data from {} to {}'.format(
            old_data_dir, new_data_dir))
        return

    os.replace(old_data_dir, backup_data_dir)
    os.symlink(new_data_dir, old_data_dir)

    host.service_start('docker')
    start()

    reactive.set_state('docker-registry.storage.docker-registry.migrated')
    status_set('active', 'Docker registry ready.')


text:
The **Buckeye Pronunciation Dictionary** is a data-driven English pronunciation dictionary, suitable for use in speech recognition systems and other applications that use phonological information about English words.
It is comparable to [CMUDict][], but is derived from a large-scale speech corpus, rather than annotator intuitions.

## File Format
The dictionary consists a four columns separated by tabs:

1. Word
2. Phonological transcription, derived from [Arpabet][]
3. Number of occurrences in corpus
4. Mean length of utterance

[CMUDict]: https://en.wikipedia.org/wiki/CMU_Pronouncing_Dictionary
[Arpabet]: https://en.wikipedia.org/wiki/Arpabet


text:
namespace java.lang
{
    public partial class OutOfMemoryError : VirtualMachineError
    {
        public OutOfMemoryError(){}
        public OutOfMemoryError(String prm1){}
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <link href='https://fonts.googleapis.com/css?family=Fira+Sans:400,700,400italic' rel='stylesheet' type='text/css'>
  <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
  <link rel="stylesheet" type="text/css" href="stylesheets/default.css">
  <link rel="stylesheet" type="text/css" href="stylesheets/about.css">

  <title>Eric Gumerlock, Web Developer</title>

 ERIC GUMERLOCK  WEB DEVELOPER

HOME

PROJECTS

BIO

CONTACT

BLOG

Bio

Eric Gumerlock was originally raised in Switzerland, and moved to the Bay Area for high school.  After graduating from UCLA, he began his professional life as a research analyst at CSS, a trading firm in Chicago.  After moving back to the Bay Area, he decided to make a career shift into something that required both technical skills and design; web development.

Aside from coding, Eric also enjoys playing basketball, hiking trails, traveling, and producing music.  Since childhood he has played guitar and has continued in his passion for music by producing his own songs in his free time.  He attended Berklee School of Music for guitar and sound design for a few semesters before making the switch to coding, so great design is in his blood!

Eric loves spicy foods, has two bearded dragons, and loves spending time on the beach or in nature.  He also has a BS in Environmental Science from UCLA, and is very passionate about the environment.

© 2016 Eric Gumerlock ||| eric.gumerlock@gmail.com


text:
<?php
/**
 * Tengu Framework
 *
 * @package  Tengu
 * @version  1.0
 * @author   Shea Lewis (Kai) <shea.lewis89@gmail.com>
 * @license  MIT License
 */
namespace Tengu;

abstract class Controller
{
	/**
	 * Controller __construct method
	 */
	public function __construct()
	{
		$this->tengu = \Tengu\Registry::getInstance();
	}
}

/* End of file core/tengu/Controller.php */


text:
let templateCreate = require('./drawings-create.html');

class DrawingsCreateController {
  constructor($scope, $state, $stateParams, $ngRedux, drawingsActions, serviceRequests, serviceFormatted) {
    $scope.actionLoadList = drawingsActions.all;
    $scope.actionCreateDetail = drawingsActions.create;

    $scope.drawingEdit = {};
    $scope.drawingEdit.dateCreated = new Date();
    $scope.drawingEdit.drawingBase64 = null;

    /* istanbul ignore next */
    this.goList = function () {
      $state.go('drawings', {
        patientId: $stateParams.patientId,
        reportType: $stateParams.reportType,
        searchString: $stateParams.searchString,
        queryType: $stateParams.queryType
      });
    };

    /* istanbul ignore next */
    this.cancel = function () {
      this.goList();
    };

    /* istanbul ignore next */
    this.create = function (drawingForm, drawingEdit) {
      $scope.formSubmitted = true;

      if (drawingForm.$valid && $scope.drawingEdit.drawingBase64) {
        let toAdd = {
          drawingBase64: drawingEdit.drawingBase64,
          name: drawingEdit.name,
          author: drawingEdit.author,
          dateCreated: new Date().getTime(),
          dateUpdated: new Date().getTime(),
        };
        serviceFormatted.propsToString(toAdd);
        $scope.actionCreateDetail($stateParams.patientId, toAdd);
      }
    }.bind(this);

    /* istanbul ignore next */
    $scope.getCanvasImage64 = function (data) {
      $scope.drawingEdit.drawingBase64 = data.image64;
    };
    serviceRequests.subscriber('drawingCanvasChanged', $scope.getCanvasImage64);

    /* istanbul ignore next */
    $scope.resizeDrawing = function () {
      serviceRequests.publisher('resizeDrawing', {});
    };

    /* istanbul ignore next */
    this.setCurrentPageData = function (store) {
      if (store.drawings.dataCreate !== null) {
        $scope.actionLoadList($stateParams.patientId);
        this.goList();
      }
      if (serviceRequests.currentUserData) {
        $scope.currentUser = serviceRequests.currentUserData;
        $scope.drawingEdit.author = $scope.currentUser.email;
      }
    };

    let unsubscribe = $ngRedux.connect(state => ({
      getStoreData: this.setCurrentPageData(state)
    }))(this);
    $scope.$on('$destroy', unsubscribe);
  }
}

const DrawingsCreateComponent = {
  template: templateCreate,
  controller: DrawingsCreateController
};

DrawingsCreateController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'drawingsActions', 'serviceRequests', 'serviceFormatted'];
export default DrawingsCreateComponent;


text:
curl https://start.spring.io/starter.zip \
  -d type=maven-project \
  -d applicationName="HystrixDashboardApplication" \
  -d packageName="jp.bikon" \
  -d groupId="jp.bikon" -d name="Hystrix Dashboard" -d artifactId="hystrix-dashboard" \
  -d description="Spring Hystrix Dashboard Application" \
  -d dependencies=cloud-hystrix-dashboard,cloud-eureka,actuator,devtools \
  -d version="0.5.0-SNAPSHOT" \
  -d javaVersion="1.8" \
  | tar -xzvf -


text:
IsRealFunction::IsRealFunction(DataExtractor *next, ConcreteTableColumn *prototype, FuncDeclaration *condition):DataExtractor(next,prototype,condition){};

TableColumn* IsRealFunction::handleExtraction(AbstractTree &tree) {

	TableColumn *column = prototype->clone();
	std::string value;

	value = "real-function";

	column->init(value,true);
	return column;
}


text:
namespace mshtml
{
    using System;

    public enum _BEHAVIOR_RENDER_INFO
    {
        BEHAVIOR_RENDER_INFO_Max = 0x7fffffff,
        BEHAVIORRENDERINFO_3DSURFACE = 0x200000,
        BEHAVIORRENDERINFO_ABOVECONTENT = 40,
        BEHAVIORRENDERINFO_AFTERBACKGROUND = 2,
        BEHAVIORRENDERINFO_AFTERCONTENT = 8,
        BEHAVIORRENDERINFO_AFTERFOREGROUND = 0x20,
        BEHAVIORRENDERINFO_ALLLAYERS = 0xff,
        BEHAVIORRENDERINFO_BEFOREBACKGROUND = 1,
        BEHAVIORRENDERINFO_BEFORECONTENT = 4,
        BEHAVIORRENDERINFO_DISABLEALLLAYERS = 0xf00,
        BEHAVIORRENDERINFO_DISABLEBACKGROUND = 0x100,
        BEHAVIORRENDERINFO_DISABLECONTENT = 0x400,
        BEHAVIORRENDERINFO_DISABLENEGATIVEZ = 0x200,
        BEHAVIORRENDERINFO_DISABLEPOSITIVEZ = 0x800,
        BEHAVIORRENDERINFO_HITTESTING = 0x1000,
        BEHAVIORRENDERINFO_SURFACE = 0x100000
    }
}


text:
PlayerList = new Mongo.Collection('players');
//UserAccounts = new Mongo.Collection('users');

// Following code was tested on JavaScript Console.
//
// PlayerList.insert( { name : "David", score : 0} );
// PlayerList.find().fetch();
// PlayerList.find().count();
//
// chapter 10.
// Meteor.users.find().fetch();
//

// Commands typed
// chapter 3.
// meteor create leaderboard
//
// chapter 10.
// meteor add accounts-password
// meteor add accounts-ui
// (After CTRL+C),
// meteor reset
//
// chapter 11.
// meteor remove autopublish
//
// chapter 12.
// meteor remove insecure
//
//


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>br.com</groupId>
	<artifactId>catalogofilmes</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.4.190</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.8.7</version>
			<scope>provided</scope>
		</dependency>

		<!-- Escopo de teste -->
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.10.19</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>2.17</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish</groupId>
			<artifactId>javax.json</artifactId>
			<version>1.0.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-processing</artifactId>
			<version>2.17</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>catalogofilmes</finalName>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>com.sebastian-daschner</groupId>
					<artifactId>jaxrs-analyzer-maven-plugin</artifactId>
					<version>0.14</version>
					<executions>
						<execution>
							<goals>
								<goal>analyze-jaxrs</goal>
							</goals>
							<configuration>
								<backend>plaintext</backend>
								<deployedDomain>catalogofilmes.com.br</deployedDomain>
							</configuration>
						</execution>
					</executions>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<failOnMissingWebXml>false</failOnMissingWebXml>
	</properties>
</project>


text:
Application for fast notifications for Facebook friends. </br>
Don't call, dont't text, just push! </br>

It uses:
* Xamarin.Forms
* Xamarin.Forms dependency services
* SimpleIoC container
* ImageCircle plugin
* MVVM pattern
* MVVM Light Toolkit
* Visual Studio Mobile Center
* Realm local database
* Microsoft Azure Notification Hub
* Push notifications for iOS and Android platform

</br>

[![DajSiePoznac2017 Logo](http://uczestnicy.dajsiepoznac.pl/Content/logo/dsp2017-logo.png)](http://dajsiepoznac.pl/)

## Credits
Copyright © Bartosz Radlak.</br> All rights reserved


text:
module Carrierwave
  module Sharefile
    VERSION = "0.0.15"
  end
end


text:
//
//  Player.hpp
//  1v1_server
//
//  Created by Filip Peterek on 12/12/2016.
//  Copyright © 2016 Filip Peterek. All rights reserved.
//

#ifndef Player_hpp
#define Player_hpp

#include <stdio.h>
#include <unordered_map>
#include <functional>

#include "Entity.hpp"
#include "Dorito.hpp"
#include "World.hpp"

class Player : public entity {

    unsigned long  _frameCounter  = 0;
    unsigned char  _moveSpeed     = 1;
    unsigned char  _attackCounter = 0;
    unsigned char  _doritoCounter = 0;
    unsigned short _gamesWon      = 0;
    bool           _canJump;
    Dorito         _dorito;
    /* Force that affects the player, negative force brings the player up, positive force brings the player down */
    float _force = 0;
    constexpr static const float terminalVelocity = 7.f;

    std::reference_wrapper<World> _world;

    sf::RectangleShape _hitbox;
    sf::RectangleShape _attackHitbox;

    // std::unordered_map<char, int> _spellCooldown;

public:

    sf::RectangleShape & getHitbox();
    const sf::RectangleShape & getSwordHitbox();

    Dorito & getDorito();

    void move(enum direction movementDirection);
    void attack();
    void throwDorito();
    void updateDorito();
    void resetDorito();
    void jump();
    void applyForce();
    void resetSprite();
    void update();
    void resetAttackHitbox(); /* Only resets the hitbox */
    void resetAttack(); /* Resets the hitbox as well as the counter and stops the animation */
    void incrementVictoryCounter();
    void takeDamage();

    bool collidesWith(const sf::Shape & shape);
    bool canPerformAction();

    unsigned short victoryCounter() override;

    Player(World & newWorld);

};

#endif /* Player_hpp */


text:
using EngineLayer;
using MzLibUtil;
using Nett;
using System.Collections.Generic;

namespace TaskLayer

{
    public class FileSpecificSettings
    {
        #region Public Constructors

        public FileSpecificSettings(Dictionary<string, KeyValuePair<string, TomlObject>> tomlDict)
        {
            if (tomlDict.ContainsKey("DoPrecursorDeconvolution"))
            {
                DoPrecursorDeconvolution = tomlDict["DoPrecursorDeconvolution"].Value.Get<bool?>();
            }
            if (tomlDict.ContainsKey("UseProvidedPrecursorInfo"))
            {
                UseProvidedPrecursorInfo = tomlDict["UseProvidedPrecursorInfo"].Value.Get<bool?>();
            }
            if (tomlDict.ContainsKey("DeconvolutionIntensityRatio"))
            {
                DeconvolutionIntensityRatio = tomlDict["DeconvolutionIntensityRatio"].Value.Get<double?>();
            }
            if (tomlDict.ContainsKey("DeconvolutionMaxAssumedChargeState"))
            {
                DeconvolutionMaxAssumedChargeState = tomlDict["DeconvolutionMaxAssumedChargeState"].Value.Get<int?>();
            }
            if (tomlDict.ContainsKey("DeconvolutionMassTolerance"))
            {
                DeconvolutionMassTolerance = tomlDict["DeconvolutionMassTolerance"].Value.Get<Tolerance>();
            }
            if (tomlDict.ContainsKey("InitiatorMethionineBehavior"))
            {
                InitiatorMethionineBehavior = tomlDict["InitiatorMethionineBehavior"].Value.Get<InitiatorMethionineBehavior>();
            }
            if (tomlDict.ContainsKey("MaxMissedCleavages"))
            {
                MaxMissedCleavages = tomlDict["MaxMissedCleavages"].Value.Get<int?>();
            }
            if (tomlDict.ContainsKey("MinPeptideLength"))
            {
                MinPeptideLength = tomlDict["MinPeptideLength"].Value.Get<int?>();
            }
            if (tomlDict.ContainsKey("MaxPeptideLength"))
            {
                MaxPeptideLength = tomlDict["MaxPeptideLength"].Value.Get<int?>();
            }
            if (tomlDict.ContainsKey("MaxModificationIsoforms"))
            {
                MaxModificationIsoforms = tomlDict["MaxModificationIsoforms"].Value.Get<int?>();
            }
            if (tomlDict.ContainsKey("TotalPartitions"))
            {
                TotalPartitions = tomlDict["TotalPartitions"].Value.Get<int?>();
            }
            if (tomlDict.ContainsKey("Protease"))
            {
                Protease = tomlDict["Protease"].Value.Get<Protease>();
            }
            if (tomlDict.ContainsKey("ProductMassTolerance"))
            {
                ProductMassTolerance = tomlDict["ProductMassTolerance"].Value.Get<Tolerance>();
            }
            if (tomlDict.ContainsKey("ConserveMemory"))
            {
                ConserveMemory = tomlDict["ConserveMemory"].Value.Get<bool?>();
            }
            if (tomlDict.ContainsKey("ScoreCutoff"))
            {
                ScoreCutoff = tomlDict["ScoreCutoff"].Value.Get<double?>();
            }
            if (tomlDict.ContainsKey("Max_mods_for_peptide"))
            {
                Max_mods_for_peptide = tomlDict["Max_mods_for_peptide"].Value.Get<int?>();
            }
            if (tomlDict.ContainsKey("TrimMsMsPeaks"))
            {
                TrimMsMsPeaks = tomlDict["TrimMsMsPeaks"].Value.Get<bool?>();
            }
            if (tomlDict.ContainsKey("TrimMs1Peaks"))
            {
                TrimMs1Peaks = tomlDict["TrimMs1Peaks"].Value.Get<bool?>();
            }
            if (tomlDict.ContainsKey("MinRatio"))
            {
                MinRatio = tomlDict["MinRatio"].Value.Get<double?>();
            }
            if (tomlDict.ContainsKey("TopNpeaks"))
            {
                TopNpeaks = tomlDict["TopNpeaks"].Value.Get<int?>();
            }
        }

        #endregion Public Constructors

        #region Public Properties

        public Protease Protease { get; set; }
        public int? Max_mods_for_peptide { get; }
        public bool? DoPrecursorDeconvolution { get; }
        public bool? UseProvidedPrecursorInfo { get; }
        public double? DeconvolutionIntensityRatio { get; }
        public double? ScoreCutoff { get; }
        public bool? ConserveMemory { get; }
        public Tolerance ProductMassTolerance { get; }
        public int? TotalPartitions { get; }
        public int? MaxModificationIsoforms { get; }
        public int? MaxPeptideLength { get; }
        public int? MinPeptideLength { get; }
        public int? MaxMissedCleavages { get; }
        public InitiatorMethionineBehavior InitiatorMethionineBehavior { get; }
        public Tolerance DeconvolutionMassTolerance { get; }
        public int? DeconvolutionMaxAssumedChargeState { get; }
        public bool? TrimMsMsPeaks { get; }
        public bool? TrimMs1Peaks { get; }
        public double? MinRatio { get; }
        public int? TopNpeaks { get; }

        #endregion Public Properties
    }
}


text:
<?php

namespace Rax\Data\Driver\Base;

use Rax\Data\Driver\DriverInterface;

/**
 *
 */
class BaseOrmDriver implements DriverInterface
{
    public function set($key, $value = null)
    {

    }

    public function get($key, $default = null, $reload = false)
    {

    }

    public function load($key)
    {

    }

    public function save()
    {

    }
}


text:
module VersionedRecord
  # Builds a set of attributes for a new version of a record
  class AttributeBuilder

    # New Builder
    # @param [ActiveRecord::Base] record the record we are versioning
    def initialize(record)
      @record = record
    end

    # Get new attributes hash for the new version
    # Attributes missing in new_attrs will be filled in from
    # the previous version (specified in the constructor)
    #
    # @param [Hash] new_attrs are the attributes we are changing in this version
    def attributes(new_attrs)
      @new_attrs = new_attrs.symbolize_keys
      attrs = original_attributes.merge(@new_attrs.merge({
        is_current_version: true,
        id:                 @record.id,
        version:            @record.version + 1
      }))
    end

    # The relevant attributes of the previous version
    # i.e: the record we initialized this builder with
    #
    # @return Hash excluding created_at and updated_at keys
    #
    def original_attributes
      @record.attributes.symbolize_keys.select do |(attr, _)|
        !%i(created_at updated_at).include?(attr)
      end
    end
  end
end


text:
namespace av
{
    class Player : public Entity, public sf::CircleShape
    {
    public:
        explicit Player();

        void Update(float timestep) override;
        void Render(sf::RenderWindow& l_window) override;
        void HandleInput(sf::Event l_event) override;
        bool IsAlive() override;
        bool Collide(Entity& l_entity) override;

        void Restart();

        std::vector<Bullet> GetBullets() const;
        sf::RectangleShape GetRifle() const;
        sf::FloatRect GetGlobalBounds() override;

        //All of these should be refractored with getters and setters

        float Left() const;
        float Right() const;

        sf::Vector2f m_mouse_position_;

        // Getters/Setters
        sf::RectangleShape& getRifle();
        void setRifle(sf::RectangleShape l_rifle);

        sf::Vector2f& getVelocity();
        void setVelocity(sf::Vector2f l_velocity);

        float getPlayerVelocity() const;
        void setPlayerVelocity(float l_velocity);

        std::chrono::time_point<std::chrono::system_clock> getSpawnTime() const;
        void setSpawnTime(std::chrono::time_point<std::chrono::system_clock> l_time);

        std::vector<Bullet>& getBullets();
    private:

        // side size to render it properly
        float m_side_distance_;
        float m_player_velocity_;
        sf::Vector2f m_velocity_;

        //Weapons & Tools
        sf::RectangleShape m_rifle_;
        std::vector<Bullet> m_bullets_;

        // timer for the bullet spawn
        std::chrono::time_point<std::chrono::system_clock> m_spawn_time_;

        float X() const;
        float Y() const;
        float Top() const;
        float Bottom() const;

        //Components
        GrapicsComponent* 	m_graphics_;
        InputComponent* 	m_input_;
        //PhysicsComponent*	m_physics_;
    };

}

#endif //AVALONENGINE_PLAYER_H


text:
package org.springframework.security.web.authentication;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServicesTests;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.test.util.ReflectionTestUtils;

/**
 * Tests {@link AbstractAuthenticationProcessingFilter}.
 *
 * @author Ben Alex
 * @author Luke Taylor
 * @author Rob Winch
 */
@SuppressWarnings("deprecation")
public class AbstractAuthenticationProcessingFilterTests {

	SavedRequestAwareAuthenticationSuccessHandler successHandler;

	SimpleUrlAuthenticationFailureHandler failureHandler;

	// ~ Methods
	// ========================================================================================================

	private MockHttpServletRequest createMockAuthenticationRequest() {
		MockHttpServletRequest request = new MockHttpServletRequest();

		request.setServletPath("/j_mock_post");
		request.setScheme("http");
		request.setServerName("www.example.com");
		request.setRequestURI("/mycontext/j_mock_post");
		request.setContextPath("/mycontext");

		return request;
	}

	@Before
	public void setUp() throws Exception {
		successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
		successHandler.setDefaultTargetUrl("/logged_in.jsp");
		failureHandler = new SimpleUrlAuthenticationFailureHandler();
		failureHandler.setDefaultFailureUrl("/failed.jsp");
		SecurityContextHolder.clearContext();
	}

	@After
	public void tearDown() throws Exception {
		SecurityContextHolder.clearContext();
	}

	@Test
	public void testDefaultProcessesFilterUrlMatchesWithPathParameter() throws Exception {
		MockHttpServletRequest request = createMockAuthenticationRequest();
		MockHttpServletResponse response = new MockHttpServletResponse();
		MockAuthenticationFilter filter = new MockAuthenticationFilter();
		filter.setFilterProcessesUrl("/login");

		DefaultHttpFirewall firewall = new DefaultHttpFirewall();
		request.setServletPath("/login;jsessionid=I8MIONOSTHOR");

		// the firewall ensures that path parameters are ignored
		HttpServletRequest firewallRequest = firewall.getFirewalledRequest(request);
		assertThat(filter.requiresAuthentication(firewallRequest, response)).isTrue();
	}

	@Test
	public void testFilterProcessesUrlVariationsRespected() throws Exception {
		// Setup our HTTP request
		MockHttpServletRequest request = createMockAuthenticationRequest();
		request.setServletPath("/j_OTHER_LOCATION");
		request.setRequestURI("/mycontext/j_OTHER_LOCATION");

		// Setup our filter configuration
		MockFilterConfig config = new MockFilterConfig(null, null);

		// Setup our expectation that the filter chain will not be invoked, as we redirect
		// to defaultTargetUrl
		MockFilterChain chain = new MockFilterChain(false);
		MockHttpServletResponse response = new MockHttpServletResponse();

		// Setup our test object, to grant access
		MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
		filter.setFilterProcessesUrl("/j_OTHER_LOCATION");
		filter.setAuthenticationSuccessHandler(successHandler);

		// Test
		filter.doFilter(request, response, chain);
		assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
		assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
		assertThat(
				SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo(
						"test");
	}

	@Test
	public void testGettersSetters() throws Exception {
		AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
		filter.setAuthenticationManager(mock(AuthenticationManager.class));
		filter.setFilterProcessesUrl("/p");
		filter.afterPropertiesSet();

		assertThat(filter.getRememberMeServices()).isNotNull();
		filter.setRememberMeServices(new TokenBasedRememberMeServices("key",
				new AbstractRememberMeServicesTests.MockUserDetailsService()));
		assertThat(filter.getRememberMeServices().getClass()).isEqualTo(
				TokenBasedRememberMeServices.class);
		assertThat(filter.getAuthenticationManager() != null).isTrue();
	}

	@Test
	public void testIgnoresAnyServletPathOtherThanFilterProcessesUrl() throws Exception {
		// Setup our HTTP request
		MockHttpServletRequest request = createMockAuthenticationRequest();
		request.setServletPath("/some.file.html");
		request.setRequestURI("/mycontext/some.file.html");

		// Setup our filter configuration
		MockFilterConfig config = new MockFilterConfig(null, null);

		// Setup our expectation that the filter chain will be invoked, as our request is
		// for a page the filter isn't monitoring
		MockFilterChain chain = new MockFilterChain(true);
		MockHttpServletResponse response = new MockHttpServletResponse();

		// Setup our test object, to deny access
		MockAuthenticationFilter filter = new MockAuthenticationFilter(false);

		// Test
		filter.doFilter(request, response, chain);
	}

	@Test
	public void testNormalOperationWithDefaultFilterProcessesUrl() throws Exception {
		// Setup our HTTP request
		MockHttpServletRequest request = createMockAuthenticationRequest();
		HttpSession sessionPreAuth = request.getSession();

		// Setup our filter configuration
		MockFilterConfig config = new MockFilterConfig(null, null);

		// Setup our expectation that the filter chain will not be invoked, as we redirect
		// to defaultTargetUrl
		MockFilterChain chain = new MockFilterChain(false);
		MockHttpServletResponse response = new MockHttpServletResponse();

		// Setup our test object, to grant access
		MockAuthenticationFilter filter = new MockAuthenticationFilter(true);

		filter.setFilterProcessesUrl("/j_mock_post");
		filter.setSessionAuthenticationStrategy(
				mock(SessionAuthenticationStrategy.class));
		filter.setAuthenticationSuccessHandler(successHandler);
		filter.setAuthenticationFailureHandler(failureHandler);
		filter.setAuthenticationManager(mock(AuthenticationManager.class));
		filter.afterPropertiesSet();

		// Test
		filter.doFilter(request, response, chain);
		assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
		assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
		assertThat(
				SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo(
						"test");
		// Should still have the same session
		assertThat(request.getSession()).isEqualTo(sessionPreAuth);
	}

	@Test
	public void testStartupDetectsInvalidAuthenticationManager() throws Exception {
		AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
		filter.setAuthenticationFailureHandler(failureHandler);
		successHandler.setDefaultTargetUrl("/");
		filter.setAuthenticationSuccessHandler(successHandler);
		filter.setFilterProcessesUrl("/login");

		try {
			filter.afterPropertiesSet();
			fail("Should have thrown IllegalArgumentException");
		}
		catch (IllegalArgumentException expected) {
			assertThat(expected.getMessage()).isEqualTo(
					"authenticationManager must be specified");
		}
	}

	@Test
	public void testStartupDetectsInvalidFilterProcessesUrl() throws Exception {
		AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
		filter.setAuthenticationFailureHandler(failureHandler);
		filter.setAuthenticationManager(mock(AuthenticationManager.class));
		filter.setAuthenticationSuccessHandler(successHandler);

		try {
			filter.setFilterProcessesUrl(null);
			fail("Should have thrown IllegalArgumentException");
		}
		catch (IllegalArgumentException expected) {
			assertThat(expected.getMessage()).isEqualTo(
					"Pattern cannot be null or empty");
		}
	}

	@Test
	public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken()
			throws Exception {
		// Setup our HTTP request
		MockHttpServletRequest request = createMockAuthenticationRequest();

		// Setup our filter configuration
		MockFilterConfig config = new MockFilterConfig(null, null);

		// Setup our expectation that the filter chain will not be invoked, as we redirect
		// to defaultTargetUrl
		MockFilterChain chain = new MockFilterChain(false);
		MockHttpServletResponse response = new MockHttpServletResponse();

		// Setup our test object, to grant access
		MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
		filter.setFilterProcessesUrl("/j_mock_post");
		filter.setAuthenticationSuccessHandler(successHandler);

		// Test
		filter.doFilter(request, response, chain);
		assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
		assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
		assertThat(
				SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo(
						"test");

		// Now try again but this time have filter deny access
		// Setup our HTTP request
		// Setup our expectation that the filter chain will not be invoked, as we redirect
		// to authenticationFailureUrl
		chain = new MockFilterChain(false);
		response = new MockHttpServletResponse();

		// Setup our test object, to deny access
		filter = new MockAuthenticationFilter(false);
		filter.setFilterProcessesUrl("/j_mock_post");
		filter.setAuthenticationFailureHandler(failureHandler);

		// Test
		filter.doFilter(request, response, chain);
		assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
	}

	@Test
	public void testSuccessfulAuthenticationInvokesSuccessHandlerAndSetsContext()
			throws Exception {
		// Setup our HTTP request
		MockHttpServletRequest request = createMockAuthenticationRequest();

		// Setup our filter configuration
		MockFilterConfig config = new MockFilterConfig(null, null);

		// Setup our expectation that the filter chain will be invoked, as we want to go
		// to the location requested in the session
		MockFilterChain chain = new MockFilterChain(true);
		MockHttpServletResponse response = new MockHttpServletResponse();

		// Setup our test object, to grant access
		MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
		filter.setFilterProcessesUrl("/j_mock_post");
		AuthenticationSuccessHandler successHandler = mock(
				AuthenticationSuccessHandler.class);
		filter.setAuthenticationSuccessHandler(successHandler);

		// Test
		filter.doFilter(request, response, chain);

		verify(successHandler).onAuthenticationSuccess(any(HttpServletRequest.class),
				any(HttpServletResponse.class), any(Authentication.class));

		assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
	}

	@Test
	public void testFailedAuthenticationInvokesFailureHandler() throws Exception {
		// Setup our HTTP request
		MockHttpServletRequest request = createMockAuthenticationRequest();

		// Setup our filter configuration
		MockFilterConfig config = new MockFilterConfig(null, null);

		// Setup our expectation that the filter chain will not be invoked, as we redirect
		// to authenticationFailureUrl
		MockFilterChain chain = new MockFilterChain(false);
		MockHttpServletResponse response = new MockHttpServletResponse();

		// Setup our test object, to deny access
		MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
		AuthenticationFailureHandler failureHandler = mock(
				AuthenticationFailureHandler.class);
		filter.setAuthenticationFailureHandler(failureHandler);

		// Test
		filter.doFilter(request, response, chain);

		verify(failureHandler).onAuthenticationFailure(any(HttpServletRequest.class),
				any(HttpServletResponse.class), any(AuthenticationException.class));

		assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
	}

	/**
	 * SEC-571
	 */
	@Test
	public void testNoSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception {
		MockHttpServletRequest request = createMockAuthenticationRequest();

		MockFilterConfig config = new MockFilterConfig(null, null);
		MockFilterChain chain = new MockFilterChain(true);
		MockHttpServletResponse response = new MockHttpServletResponse();

		// Reject authentication, so exception would normally be stored in session
		MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
		failureHandler.setAllowSessionCreation(false);
		filter.setAuthenticationFailureHandler(failureHandler);

		filter.doFilter(request, response, chain);

		assertThat(request.getSession(false)).isNull();
	}

	/**
	 * SEC-462
	 */
	@Test
	public void testLoginErrorWithNoFailureUrlSendsUnauthorizedStatus() throws Exception {
		MockHttpServletRequest request = createMockAuthenticationRequest();

		MockFilterConfig config = new MockFilterConfig(null, null);
		MockFilterChain chain = new MockFilterChain(true);
		MockHttpServletResponse response = new MockHttpServletResponse();

		MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
		successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
		filter.setAuthenticationSuccessHandler(successHandler);

		filter.doFilter(request, response, chain);

		assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
	}

	/**
	 * SEC-1919
	 */
	@Test
	public void loginErrorWithInternAuthenticationServiceExceptionLogsError()
			throws Exception {
		MockHttpServletRequest request = createMockAuthenticationRequest();

		MockFilterChain chain = new MockFilterChain(true);
		MockHttpServletResponse response = new MockHttpServletResponse();

		Log logger = mock(Log.class);
		MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
		ReflectionTestUtils.setField(filter, "logger", logger);
		filter.exceptionToThrow = new InternalAuthenticationServiceException(
				"Mock requested to do so");
		successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
		filter.setAuthenticationSuccessHandler(successHandler);

		filter.doFilter(request, response, chain);

		verify(logger).error(anyString(), eq(filter.exceptionToThrow));
		assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
	}

	/**
	 * https://github.com/spring-projects/spring-security/pull/3905
	 */
	@Test(expected = IllegalArgumentException.class)
	public void setRememberMeServicesShouldntAllowNulls() {
		AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
		filter.setRememberMeServices(null);
	}

	// ~ Inner Classes
	// ==================================================================================================

	private class MockAuthenticationFilter
			extends AbstractAuthenticationProcessingFilter {

		private AuthenticationException exceptionToThrow;

		private boolean grantAccess;

		MockAuthenticationFilter(boolean grantAccess) {
			this();
			setRememberMeServices(new NullRememberMeServices());
			this.grantAccess = grantAccess;
			this.exceptionToThrow = new BadCredentialsException(
					"Mock requested to do so");
		}

		private MockAuthenticationFilter() {
			super("/j_mock_post");
		}

		public Authentication attemptAuthentication(HttpServletRequest request,
				HttpServletResponse response) throws AuthenticationException {
			if (grantAccess) {
				return new UsernamePasswordAuthenticationToken("test", "test",
						AuthorityUtils.createAuthorityList("TEST"));
			}
			else {
				throw exceptionToThrow;
			}
		}
	}

	private class MockFilterChain implements FilterChain {

		private boolean expectToProceed;

		MockFilterChain(boolean expectToProceed) {
			this.expectToProceed = expectToProceed;
		}

		public void doFilter(ServletRequest request, ServletResponse response)
				throws IOException, ServletException {
			if (expectToProceed) {

			}
			else {
				fail("Did not expect filter chain to proceed");
			}
		}
	}
}