authpolicy: Clean state on startup

Cleans state on startup when install attributes are not set to Active
Directory enrollment. This might occur if something unexpected happens
during enrollment, e.g. the user cancels domain join.

Also cleans up AuthPolicy construction and simplifies ownership of
metrics and paths, which makes some *ForTesting accessors obsolete.

BUG=chromium:713754
TEST=Compiled, ran tests, tested on device.

Change-Id: If1cf6c406c75423d1900d460e9200737a800730e
Reviewed-on: https://chromium-review.googlesource.com/485601
Commit-Ready: Lutz Justen <ljusten@chromium.org>
Tested-by: Lutz Justen <ljusten@chromium.org>
Reviewed-by: Thiemo Nagel <tnagel@chromium.org>
diff --git a/authpolicy/authpolicy.cc b/authpolicy/authpolicy.cc
index 5196ca4..f680b39 100644
--- a/authpolicy/authpolicy.cc
+++ b/authpolicy/authpolicy.cc
@@ -61,34 +61,29 @@
       org::chromium::AuthPolicyAdaptor::GetObjectPath());
 }
 
-AuthPolicy::AuthPolicy(
-    std::unique_ptr<brillo::dbus_utils::DBusObject> dbus_object,
-    std::unique_ptr<AuthPolicyMetrics> metrics,
-    std::unique_ptr<PathService> path_service)
+AuthPolicy::AuthPolicy(AuthPolicyMetrics* metrics,
+                       const PathService* path_service)
     : org::chromium::AuthPolicyAdaptor(this),
-      // Note: We own |metrics|, but SambaInterface owns |path_service|. Also
-      // note that |metrics_| has to be initialized before |samba_| or else
-      // |samba_|'s metrics pointer isn't valid in |samba_|'s destructor.
-      metrics_(std::move(metrics)),
-      samba_(base::ThreadTaskRunnerHandle::Get(),
-             metrics_.get(),
-             std::move(path_service)),
-      dbus_object_(std::move(dbus_object)),
-      weak_ptr_factory_(this) {
-  // Make sure the task runner passed to |samba_| is actually the D-Bus task
-  // runner. This guarantees that automatic TGT renewal won't interfere with
-  // D-Bus calls. Note that |GetDBusTaskRunner()| returns a TaskRunner, which is
-  // a base class of SingleThreadTaskRunner accepted by |samba_|.
-  CHECK_EQ(base::ThreadTaskRunnerHandle::Get(),
-           dbus_object_->GetBus()->GetDBusTaskRunner());
-}
+      metrics_(metrics),
+      samba_(base::ThreadTaskRunnerHandle::Get(), metrics, path_service),
+      weak_ptr_factory_(this) {}
 
 ErrorType AuthPolicy::Initialize(bool expect_config) {
   return samba_.Initialize(expect_config);
 }
 
 void AuthPolicy::RegisterAsync(
+    std::unique_ptr<brillo::dbus_utils::DBusObject> dbus_object,
     const AsyncEventSequencer::CompletionAction& completion_callback) {
+  DCHECK(!dbus_object_);
+  dbus_object_ = std::move(dbus_object);
+  // Make sure the task runner passed to |samba_| in the constructor is actually
+  // the D-Bus task runner. This guarantees that automatic TGT renewal won't
+  // interfere with D-Bus calls. Note that |GetDBusTaskRunner()| returns a
+  // TaskRunner, which is a base class of SingleThreadTaskRunner accepted by
+  // |samba_|.
+  CHECK_EQ(base::ThreadTaskRunnerHandle::Get(),
+           dbus_object_->GetBus()->GetDBusTaskRunner());
   RegisterWithDBusObject(dbus_object_.get());
   dbus_object_->RegisterAsync(completion_callback);
   session_manager_proxy_ = dbus_object_->GetBus()->GetObjectProxy(
diff --git a/authpolicy/authpolicy.h b/authpolicy/authpolicy.h
index 28810af..727b163 100644
--- a/authpolicy/authpolicy.h
+++ b/authpolicy/authpolicy.h
@@ -39,17 +39,21 @@
   static std::unique_ptr<brillo::dbus_utils::DBusObject> GetDBusObject(
       brillo::dbus_utils::ExportedObjectManager* object_manager);
 
-  AuthPolicy(std::unique_ptr<brillo::dbus_utils::DBusObject> dbus_object,
-             std::unique_ptr<AuthPolicyMetrics> metrics,
-             std::unique_ptr<PathService> path_service);
+  AuthPolicy(AuthPolicyMetrics* metrics, const PathService* path_service);
 
   // Initializes internals. See SambaInterface::Initialize() for details.
   ErrorType Initialize(bool expect_config);
 
-  // Register the D-Bus object and interfaces.
+  // Registers the D-Bus object and interfaces.
   void RegisterAsync(
+      std::unique_ptr<brillo::dbus_utils::DBusObject> dbus_object,
       const AsyncEventSequencer::CompletionAction& completion_callback);
 
+  // Cleans all persistent state files. Returns true if all files were cleared.
+  static bool CleanState(const PathService* path_service) {
+    return SambaInterface::CleanState(path_service);
+  }
+
   // org::chromium::AuthPolicyInterface: (see org.chromium.AuthPolicy.xml).
   // |account_info_blob| is a serialized ActiveDirectoryAccountInfo protobuf.
   // TODO(ljusten): Temp wrapper to handle addition of |account_id|.
@@ -77,9 +81,6 @@
 
   void RefreshDevicePolicy(PolicyResponseCallback callback) override;
 
-  // Metrics accessor for unit tests.
-  AuthPolicyMetrics* GetMetricsForTesting() const { return metrics_.get(); }
-
   // Disable retry sleep for unit tests.
   void DisableRetrySleepForTesting() { samba_.DisableRetrySleepForTesting(); }
 
@@ -97,7 +98,7 @@
                       PolicyResponseCallback callback,
                       dbus::Response* response);
 
-  std::unique_ptr<AuthPolicyMetrics> metrics_;
+  AuthPolicyMetrics* metrics_;  // Not owned.
   SambaInterface samba_;
   std::unique_ptr<brillo::dbus_utils::DBusObject> dbus_object_;
   dbus::ObjectProxy* session_manager_proxy_ = nullptr;
diff --git a/authpolicy/authpolicy_main.cc b/authpolicy/authpolicy_main.cc
index f06dff0..7dbb73c 100644
--- a/authpolicy/authpolicy_main.cc
+++ b/authpolicy/authpolicy_main.cc
@@ -37,15 +37,19 @@
       : DBusServiceDaemon(kAuthPolicyServiceName, kObjectServicePath),
         expect_config_(expect_config) {}
 
+  // Cleans the authpolicy daemon state directory. Returns true if all files
+  // were cleared.
+  static bool CleanState() {
+    PathService path_service;
+    return AuthPolicy::CleanState(&path_service);
+  }
+
  protected:
   void RegisterDBusObjectsAsync(AsyncEventSequencer* sequencer) override {
-    auth_policy_ = base::MakeUnique<AuthPolicy>(
+    auth_policy_.RegisterAsync(
         AuthPolicy::GetDBusObject(object_manager_.get()),
-        base::MakeUnique<AuthPolicyMetrics>(),
-        base::MakeUnique<PathService>());
-    auth_policy_->RegisterAsync(
         sequencer->GetHandler("AuthPolicy.RegisterAsync() failed.", true));
-    ErrorType error = auth_policy_->Initialize(expect_config_);
+    ErrorType error = auth_policy_.Initialize(expect_config_);
     if (error != ERROR_NONE) {
       LOG(ERROR) << "SambaInterface failed to initialize with error code "
                  << error;
@@ -55,12 +59,15 @@
 
   void OnShutdown(int* return_code) override {
     DBusServiceDaemon::OnShutdown(return_code);
-    auth_policy_.reset();
   }
 
  private:
   bool expect_config_;
-  std::unique_ptr<AuthPolicy> auth_policy_;
+
+  // Keep this order! auth_policy_ must be last as it depends on the other two.
+  AuthPolicyMetrics metrics_;
+  PathService path_service_;
+  AuthPolicy auth_policy_{&metrics_, &path_service_};
 
   DISALLOW_COPY_AND_ASSIGN(Daemon);
 };
@@ -116,7 +123,8 @@
         InstallAttributesReader::kAttrMode);
     if (mode != InstallAttributesReader::kDeviceModeEnterpriseAD) {
       LOG(ERROR) << "OOBE completed but device not in Active Directory "
-                    "management mode.";
+                    "management mode. Cleaning state and exiting.";
+      CHECK(authpolicy::Daemon::CleanState());
       exit(kExitCodeStartupFailure);
     } else {
       LOG(INFO) << "Install attributes locked to Active Directory mode.";
@@ -125,7 +133,8 @@
       expect_config = true;
     }
   } else {
-    LOG(INFO) << "No install attributes found.";
+    LOG(INFO) << "No install attributes found. Cleaning state.";
+    CHECK(authpolicy::Daemon::CleanState());
   }
 
   // Run daemon.
diff --git a/authpolicy/authpolicy_unittest.cc b/authpolicy/authpolicy_unittest.cc
index c96a651..d1d0b93 100644
--- a/authpolicy/authpolicy_unittest.cc
+++ b/authpolicy/authpolicy_unittest.cc
@@ -149,13 +149,13 @@
     std::string log_str;
     for (const auto& kv : metrics_report_count_) {
       log_str += base::StringPrintf(
-          "\n  EXPECT_EQ(%i, Metrics()->GetMetricReportCount(%s));",
+          "\n  EXPECT_EQ(%i, metrics_->GetMetricReportCount(%s));",
           kv.second,
           metrics_str[kv.first]);
     }
     for (const auto& kv : dbus_report_count_) {
       log_str += base::StringPrintf(
-          "\n  EXPECT_EQ(%i, Metrics()->GetDBusReportCount(%s));",
+          "\n  EXPECT_EQ(%i, metrics_->GetDBusReportCount(%s));",
           kv.second,
           dbus_str[kv.first]);
     }
@@ -244,20 +244,23 @@
     auto dbus_object =
         base::MakeUnique<DBusObject>(nullptr, mock_bus_, object_path);
 
+    metrics_ = base::MakeUnique<TestMetrics>();
+
     // Create path service with all paths pointing into a temp directory.
     CHECK(base::CreateNewTempDirectory("" /* prefix (ignored) */, &base_path_));
-    auto paths = base::MakeUnique<TestPathService>(base_path_);
+    paths_ = base::MakeUnique<TestPathService>(base_path_);
 
     // Create the state directory since authpolicyd assumes its existence.
-    base::FilePath state_path(paths->Get(Path::STATE_DIR));
+    const base::FilePath state_path =
+        base::FilePath(paths_->Get(Path::STATE_DIR));
     CHECK(base::CreateDirectory(state_path));
 
     // Set stub preg path. Since it is not trivial to pass the full path to the
     // stub binaries, we simply use the directory from the krb5.conf file.
     const base::FilePath gpo_dir =
-        base::FilePath(paths->Get(Path::USER_KRB5_CONF)).DirName();
+        base::FilePath(paths_->Get(Path::USER_KRB5_CONF)).DirName();
     DCHECK(gpo_dir ==
-           base::FilePath(paths->Get(Path::DEVICE_KRB5_CONF)).DirName());
+           base::FilePath(paths_->Get(Path::DEVICE_KRB5_CONF)).DirName());
     stub_gpo1_path_ = gpo_dir.Append(kGpo1Filename);
     stub_gpo2_path_ = gpo_dir.Append(kGpo2Filename);
 
@@ -274,9 +277,7 @@
         .Times(8);
 
     // Create AuthPolicy instance.
-    authpolicy_ = base::MakeUnique<AuthPolicy>(std::move(dbus_object),
-                                               base::MakeUnique<TestMetrics>(),
-                                               std::move(paths));
+    authpolicy_ = base::MakeUnique<AuthPolicy>(metrics_.get(), paths_.get());
     EXPECT_EQ(ERROR_NONE, authpolicy_->Initialize(false /* expect_config */));
 
     // Don't sleep for kinit/smbclient retries, it just prolongs our tests.
@@ -296,7 +297,7 @@
         .WillRepeatedly(
             Invoke(this, &AuthPolicyTest::StubCallStorePolicyMethod));
 
-    authpolicy_->RegisterAsync(base::Bind(&DoNothing));
+    authpolicy_->RegisterAsync(std::move(dbus_object), base::Bind(&DoNothing));
   }
 
   // Stub method called by the Session Manager mock to store policy. Validates
@@ -376,11 +377,6 @@
   }
 
  protected:
-  // Accessor for testing metrics.
-  TestMetrics* Metrics() const {
-    return static_cast<TestMetrics*>(authpolicy_->GetMetricsForTesting());
-  }
-
   // Joins a (stub) Active Directory domain. Returns the error code.
   ErrorType Join(const std::string& machine_name) {
     return CastError(authpolicy_->JoinADDomain(
@@ -507,7 +503,12 @@
   scoped_refptr<MockBus> mock_bus_ = new MockBus(dbus::Bus::Options());
   scoped_refptr<MockExportedObject> mock_exported_object_;
   scoped_refptr<MockObjectProxy> mock_session_manager_proxy_;
+
+  // Keep this order! auth_policy_ must be last as it depends on the other two.
+  std::unique_ptr<TestMetrics> metrics_;
+  std::unique_ptr<TestPathService> paths_;
   std::unique_ptr<AuthPolicy> authpolicy_;
+
   base::FilePath base_path_;
   base::FilePath stub_gpo1_path_;
   base::FilePath stub_gpo2_path_;
@@ -542,34 +543,34 @@
 // Can't fetch user policy if the user is not logged in.
 TEST_F(AuthPolicyTest, UserPolicyFailsNotLoggedIn) {
   FetchAndValidateUserPolicy("account_id_key", ERROR_NOT_LOGGED_IN);
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // Can't fetch device policy if the device is not joined.
 TEST_F(AuthPolicyTest, DevicePolicyFailsNotJoined) {
   FetchAndValidateDevicePolicy(ERROR_NOT_JOINED);
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
 }
 
 // Authentication fails if the machine is not joined.
 TEST_F(AuthPolicyTest, AuthFailsNotJoined) {
   EXPECT_EQ(ERROR_NOT_JOINED, Auth(kUserPrincipal, "", MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
 }
 
 // Successful domain join.
 TEST_F(AuthPolicyTest, JoinSucceeds) {
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Successful user authentication.
 TEST_F(AuthPolicyTest, AuthSucceeds) {
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_NONE, Auth(kUserPrincipal, "", MakePasswordFd()));
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Successful user authentication with given account id.
@@ -579,9 +580,9 @@
   EXPECT_EQ(ERROR_NONE,
             Auth(kUserPrincipal, kAccountId, MakePasswordFd(), &account_info));
   EXPECT_EQ(kAccountId, account_info.account_id());
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
 }
 
 // User authentication fails with bad (non-existent) account id.
@@ -589,9 +590,9 @@
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_BAD_USER_NAME,
             Auth(kUserPrincipal, kBadAccountId, MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
 }
 
 // Successful user authentication.
@@ -604,9 +605,9 @@
   EXPECT_EQ(kDisplayName, account_info.display_name());
   EXPECT_EQ(kGivenName, account_info.given_name());
   EXPECT_EQ(kUserName, account_info.sam_account_name());
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Authentication fails for badly formatted user principal name.
@@ -614,8 +615,8 @@
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_PARSE_UPN_FAILED,
             Auth(kInvalidUserPrincipal, "", MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Authentication fails for non-existing user principal name.
@@ -623,9 +624,9 @@
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_BAD_USER_NAME,
             Auth(kNonExistingUserPrincipal, "", MakePasswordFd()));
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Authentication fails for wrong password.
@@ -633,9 +634,9 @@
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_BAD_PASSWORD,
             Auth(kUserPrincipal, "", MakeFileDescriptor(kWrongPassword)));
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Authentication fails for expired password.
@@ -643,9 +644,9 @@
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_PASSWORD_EXPIRED,
             Auth(kUserPrincipal, "", MakeFileDescriptor(kExpiredPassword)));
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Authentication fails if there's a network issue.
@@ -653,33 +654,33 @@
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_NETWORK_PROBLEM,
             Auth(kNetworkErrorUserPrincipal, "", MakePasswordFd()));
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Authentication retries without KDC if it fails the first time.
 TEST_F(AuthPolicyTest, AuthSucceedsKdcRetry) {
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_NONE, Auth(kKdcRetryUserPrincipal, "", MakePasswordFd()));
-  EXPECT_EQ(3, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(3, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Can't get user status before domain join.
 TEST_F(AuthPolicyTest, GetUserStatusFailsNotJoined) {
   EXPECT_EQ(ERROR_NOT_JOINED, GetUserStatus(kAccountId));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
 }
 
 // GetUserStatus fails with bad account id.
 TEST_F(AuthPolicyTest, GetUserStatusFailsBadAccountId) {
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_BAD_USER_NAME, GetUserStatus(kBadAccountId));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
 }
 
 // GetUserStatus succeeds without auth, but tgt is invalid.
@@ -688,9 +689,9 @@
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   EXPECT_EQ(ERROR_NONE, GetUserStatus(kAccountId, &status));
   EXPECT_EQ(ActiveDirectoryUserStatus::TGT_NOT_FOUND, status.tgt_status());
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
 }
 
 // GetUserStatus succeeds with join and auth, but with an expired TGT.
@@ -700,10 +701,10 @@
   EXPECT_EQ(ERROR_NONE, Auth(kExpiredTgtUserPrincipal, "", MakePasswordFd()));
   EXPECT_EQ(ERROR_NONE, GetUserStatus(kAccountId, &status));
   EXPECT_EQ(ActiveDirectoryUserStatus::TGT_EXPIRED, status.tgt_status());
-  EXPECT_EQ(3, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
+  EXPECT_EQ(3, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
 }
 
 // GetUserStatus succeeds with join and auth.
@@ -717,10 +718,10 @@
   EXPECT_EQ(kGivenName, status.account_info().given_name());
   EXPECT_EQ(kUserName, status.account_info().sam_account_name());
   EXPECT_EQ(ActiveDirectoryUserStatus::TGT_VALID, status.tgt_status());
-  EXPECT_EQ(3, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
+  EXPECT_EQ(3, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_GET_USER_STATUS));
 }
 
 // Join fails if there's a network issue.
@@ -728,7 +729,7 @@
   EXPECT_EQ(ERROR_NETWORK_PROBLEM,
             authpolicy_->JoinADDomain(
                 kMachineName, kNetworkErrorUserPrincipal, MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Join fails for badly formatted user principal name.
@@ -736,7 +737,7 @@
   EXPECT_EQ(ERROR_PARSE_UPN_FAILED,
             authpolicy_->JoinADDomain(
                 kMachineName, kInvalidUserPrincipal, MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Join fails for non-existing user principal name, but the error message is the
@@ -745,7 +746,7 @@
   EXPECT_EQ(ERROR_BAD_PASSWORD,
             authpolicy_->JoinADDomain(
                 kMachineName, kNonExistingUserPrincipal, MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Join fails for wrong password.
@@ -754,7 +755,7 @@
       ERROR_BAD_PASSWORD,
       authpolicy_->JoinADDomain(
           kMachineName, kUserPrincipal, MakeFileDescriptor(kWrongPassword)));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Join fails if user can't join a machine to the domain.
@@ -762,7 +763,7 @@
   EXPECT_EQ(ERROR_JOIN_ACCESS_DENIED,
             authpolicy_->JoinADDomain(
                 kMachineName, kAccessDeniedUserPrincipal, MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Join fails if the machine name is too long.
@@ -770,7 +771,7 @@
   EXPECT_EQ(ERROR_MACHINE_NAME_TOO_LONG,
             authpolicy_->JoinADDomain(
                 kTooLongMachineName, kUserPrincipal, MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Join fails if the machine name contains invalid characters.
@@ -778,7 +779,7 @@
   EXPECT_EQ(ERROR_INVALID_MACHINE_NAME,
             authpolicy_->JoinADDomain(
                 kInvalidMachineName, kUserPrincipal, MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Join fails if the user can't join additional machines.
@@ -787,7 +788,7 @@
       ERROR_USER_HIT_JOIN_QUOTA,
       authpolicy_->JoinADDomain(
           kMachineName, kInsufficientQuotaUserPrincipal, MakePasswordFd()));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 // Successful user policy fetch with empty policy.
@@ -795,11 +796,11 @@
   validate_user_policy_ = check_user_policy_empty_;
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_NONE);
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // Successful user policy fetch with actual data.
@@ -828,13 +829,13 @@
   };
   EXPECT_EQ(ERROR_NONE, Join(kOneGpoMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_NONE);
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // Verify that PolicyLevel is encoded properly.
@@ -858,13 +859,13 @@
   };
   EXPECT_EQ(ERROR_NONE, Join(kOneGpoMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_NONE);
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // Verifies that a POLICY_LEVEL_MANDATORY policy is not overwritten by a
@@ -895,13 +896,13 @@
   };
   EXPECT_EQ(ERROR_NONE, Join(kTwoGposMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_NONE);
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // Verify that GPO containing policies with the wrong data type are not set.
@@ -928,13 +929,13 @@
   };
   EXPECT_EQ(ERROR_NONE, Join(kOneGpoMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_NONE);
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // GPOs with version 0 should be ignored.
@@ -956,13 +957,13 @@
   };
   EXPECT_EQ(ERROR_NONE, Join(kOneGpoMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_NONE);
-  EXPECT_EQ(4, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(4, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(2, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(2, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(2, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(2, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(2, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(2, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // GPOs with an ignore flag set should be ignored. Sounds reasonable, hmm?
@@ -984,13 +985,13 @@
   };
   EXPECT_EQ(ERROR_NONE, Join(kOneGpoMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_NONE);
-  EXPECT_EQ(4, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(4, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(2, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(2, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(2, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(2, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(2, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(2, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // User policy fetch should ignore GPO files that are missing on the server.
@@ -1000,13 +1001,13 @@
   validate_user_policy_ = check_user_policy_empty_;
   EXPECT_EQ(ERROR_NONE, Join(kOneGpoMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_NONE);
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // User policy fetch fails if a file fails to download (unless it's missing,
@@ -1014,13 +1015,13 @@
 TEST_F(AuthPolicyTest, UserPolicyFetchFailsDownloadError) {
   EXPECT_EQ(ERROR_NONE, Join(kGpoDownloadErrorMachineName));
   FetchAndValidateUserPolicy(DefaultAuth(), ERROR_SMBCLIENT_FAILED);
-  EXPECT_EQ(2, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_USER_POLICY));
 }
 
 // Successful device policy fetch with empty policy.
@@ -1028,10 +1029,10 @@
   validate_device_policy_ = check_device_policy_empty_;
   EXPECT_EQ(ERROR_NONE, Join(kMachineName));
   FetchAndValidateDevicePolicy(ERROR_NONE);
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
 }
 
 // Device policy fetch fails if the machine account doesn't exist.
@@ -1039,9 +1040,9 @@
   validate_device_policy_ = check_device_policy_empty_;
   EXPECT_EQ(ERROR_NONE, Join(kNonExistingMachineName));
   FetchAndValidateDevicePolicy(ERROR_BAD_MACHINE_NAME);
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
 }
 
 // Successful device policy fetch with a few kinit retries because the machine
@@ -1050,12 +1051,12 @@
   validate_device_policy_ = check_device_policy_empty_;
   EXPECT_EQ(ERROR_NONE, Join(kPropagationRetryMachineName));
   FetchAndValidateDevicePolicy(ERROR_NONE);
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(kNumPropagationRetries,
-            Metrics()->GetLastMetricSample(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
+            metrics_->GetLastMetricSample(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
 }
 
 // Successful device policy fetch with actual data.
@@ -1082,12 +1083,12 @@
   };
   EXPECT_EQ(ERROR_NONE, Join(kOneGpoMachineName));
   FetchAndValidateDevicePolicy(ERROR_NONE);
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
 }
 
 // Completely empty GPO list fails. GPO lists should always contain at least
@@ -1095,9 +1096,9 @@
 TEST_F(AuthPolicyTest, DevicePolicyFetchFailsEmptyGpoList) {
   EXPECT_EQ(ERROR_NONE, Join(kEmptyGpoMachineName));
   FetchAndValidateDevicePolicy(ERROR_PARSE_FAILED);
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
 }
 
 // A GPO later in the list overrides prior GPOs.
@@ -1134,12 +1135,26 @@
   };
   EXPECT_EQ(ERROR_NONE, Join(kTwoGposMachineName));
   FetchAndValidateDevicePolicy(ERROR_NONE);
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
   EXPECT_EQ(1,
-            Metrics()->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
-  EXPECT_EQ(1, Metrics()->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
-  EXPECT_EQ(1, Metrics()->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
+            metrics_->GetMetricReportCount(METRIC_SMBCLIENT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetMetricReportCount(METRIC_DOWNLOAD_GPO_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_REFRESH_DEVICE_POLICY));
+}
+
+// Make sure cleaning state works.
+TEST_F(AuthPolicyTest, CleanStateDir) {
+  const base::FilePath state_path =
+      base::FilePath(paths_->Get(Path::STATE_DIR));
+  EXPECT_EQ(ERROR_NONE, Join(kMachineName));
+  EXPECT_EQ(ERROR_NONE, Auth(kUserPrincipal, "", MakePasswordFd()));
+  EXPECT_FALSE(base::IsDirectoryEmpty(state_path));
+  EXPECT_TRUE(AuthPolicy::CleanState(paths_.get()));
+  EXPECT_TRUE(base::IsDirectoryEmpty(state_path));
+  EXPECT_EQ(2, metrics_->GetMetricReportCount(METRIC_KINIT_FAILED_TRY_COUNT));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_AUTHENTICATE_USER));
+  EXPECT_EQ(1, metrics_->GetDBusReportCount(DBUS_CALL_JOIN_AD_DOMAIN));
 }
 
 }  // namespace authpolicy
diff --git a/authpolicy/samba_interface.cc b/authpolicy/samba_interface.cc
index a005191..4fbb8bc 100644
--- a/authpolicy/samba_interface.cc
+++ b/authpolicy/samba_interface.cc
@@ -198,18 +198,18 @@
 SambaInterface::SambaInterface(
     scoped_refptr<base::SingleThreadTaskRunner> task_runner,
     AuthPolicyMetrics* metrics,
-    std::unique_ptr<PathService> path_service)
+    const PathService* path_service)
     : metrics_(metrics),
-      paths_(std::move(path_service)),
-      jail_helper_(paths_.get()),
+      paths_(path_service),
+      jail_helper_(paths_),
       user_tgt_manager_(task_runner,
-                        paths_.get(),
+                        paths_,
                         metrics_,
                         &jail_helper_,
                         Path::USER_KRB5_CONF,
                         Path::USER_CREDENTIAL_CACHE),
       device_tgt_manager_(task_runner,
-                          paths_.get(),
+                          paths_,
                           metrics_,
                           &jail_helper_,
                           Path::DEVICE_KRB5_CONF,
@@ -265,6 +265,20 @@
   return ERROR_NONE;
 }
 
+// static
+bool SambaInterface::CleanState(const PathService* path_service) {
+  // Note: We're not permitted to delete the folder and DeleteFile apparently
+  // doesn't support wildcards, so DeleteFile returns false.
+  DCHECK(path_service);
+  base::FilePath state_dir(path_service->Get(Path::STATE_DIR));
+  base::DeleteFile(state_dir, true /* recursive */);
+  if (!base::IsDirectoryEmpty(state_dir)) {
+    LOG(ERROR) << "Failed to clean state dir '" << state_dir.value() << "'";
+    return false;
+  }
+  return true;
+}
+
 ErrorType SambaInterface::AuthenticateUser(
     const std::string& user_principal_name,
     const std::string& account_id,
diff --git a/authpolicy/samba_interface.h b/authpolicy/samba_interface.h
index 065216a..b7c3373 100644
--- a/authpolicy/samba_interface.h
+++ b/authpolicy/samba_interface.h
@@ -38,7 +38,7 @@
  public:
   SambaInterface(scoped_refptr<base::SingleThreadTaskRunner> task_runner,
                  AuthPolicyMetrics* metrics,
-                 std::unique_ptr<PathService> path_service);
+                 const PathService* path_service);
 
   // Creates directories required by Samba code and loads configuration, if it
   // exists. Also loads the debug flags file. Returns error
@@ -46,6 +46,9 @@
   // - if |expect_config| is true and the config file fails to load.
   ErrorType Initialize(bool expect_config);
 
+  // Cleans all persistent state files. Returns true if all files were cleared.
+  static bool CleanState(const PathService* path_service);
+
   // Calls kinit to get a Kerberos ticket-granting-ticket (TGT) for the given
   // |user_principal_name| (format: user_name@workgroup.domain). If a TGT
   // already exists, it is renewed. The password must be readable from the pipe
@@ -186,8 +189,8 @@
   // UMA statistics, not owned.
   AuthPolicyMetrics* metrics_;
 
-  // Lookup for file paths.
-  std::unique_ptr<PathService> paths_;
+  // Lookup for file paths, not owned.
+  const PathService* paths_;
 
   // Helper to setup and run minijailed processes.
   JailHelper jail_helper_;