You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mesos.apache.org by ti...@apache.org on 2016/01/08 04:22:16 UTC

[1/3] mesos git commit: Added support for modularized HTTP authenticators.

Repository: mesos
Updated Branches:
  refs/heads/master 4615f82b6 -> 9f6a2aab4


Added support for modularized HTTP authenticators.

Includes a basic HTTP authenticator module as an example for
HTTP authenticator implementations.

Review: https://reviews.apache.org/r/38950/


Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/51607398
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/51607398
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/51607398

Branch: refs/heads/master
Commit: 51607398f841747d76f2696bab60e28b1ce237ed
Parents: 4615f82
Author: Alexander Rojas <al...@mesosphere.io>
Authored: Fri Jan 8 03:21:55 2016 +0100
Committer: Till Toenshoff <to...@me.com>
Committed: Fri Jan 8 04:18:14 2016 +0100

----------------------------------------------------------------------
 .../http/basic_authenticator_factory.hpp        |  51 +++++
 include/mesos/module/http_authenticator.hpp     |  64 ++++++
 src/CMakeLists.txt                              |   1 +
 src/Makefile.am                                 |  12 +-
 .../http/basic_authenticator_factory.cpp        |  58 ++++++
 src/examples/test_http_authenticator_module.cpp |  53 +++++
 src/master/constants.cpp                        |   1 +
 src/master/constants.hpp                        |   3 +
 src/module/manager.cpp                          |   1 +
 src/tests/http_authentication_tests.cpp         | 196 +++++++++++++++++++
 src/tests/module.cpp                            |  26 +++
 src/tests/module.hpp                            |   1 +
 12 files changed, 466 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/include/mesos/authentication/http/basic_authenticator_factory.hpp
----------------------------------------------------------------------
diff --git a/include/mesos/authentication/http/basic_authenticator_factory.hpp b/include/mesos/authentication/http/basic_authenticator_factory.hpp
new file mode 100644
index 0000000..066303d
--- /dev/null
+++ b/include/mesos/authentication/http/basic_authenticator_factory.hpp
@@ -0,0 +1,51 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__
+#define __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__
+
+#include <string>
+
+#include <mesos/mesos.hpp>
+
+#include <process/authenticator.hpp>
+
+#include <stout/try.hpp>
+#include <stout/hashmap.hpp>
+
+namespace mesos {
+namespace http {
+namespace authentication {
+
+class BasicAuthenticatorFactory {
+public:
+  ~BasicAuthenticatorFactory() {}
+
+  static Try<process::http::authentication::Authenticator*> create(
+      const Parameters& parameters);
+
+  static Try<process::http::authentication::Authenticator*> create(
+      const hashmap<std::string, std::string>& credentials);
+
+protected:
+  BasicAuthenticatorFactory() {}
+};
+
+} // namespace authentication {
+} // namespace http {
+} // namespace mesos {
+
+#endif // __MESOS_AUTHENTICATION_HTTP_AUTHENTICATOR_FACTORY_HPP__

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/include/mesos/module/http_authenticator.hpp
----------------------------------------------------------------------
diff --git a/include/mesos/module/http_authenticator.hpp b/include/mesos/module/http_authenticator.hpp
new file mode 100644
index 0000000..7344b6f
--- /dev/null
+++ b/include/mesos/module/http_authenticator.hpp
@@ -0,0 +1,64 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef __MESOS_MODULE_HTTP_AUTHENTICATOR_HPP__
+#define __MESOS_MODULE_HTTP_AUTHENTICATOR_HPP__
+
+#include <mesos/mesos.hpp>
+#include <mesos/module.hpp>
+
+#include <process/authenticator.hpp>
+
+namespace mesos {
+namespace modules {
+
+template <>
+inline const char* kind<process::http::authentication::Authenticator>()
+{
+  return "HttpAuthenticator";
+}
+
+
+template <>
+struct Module<process::http::authentication::Authenticator> : ModuleBase
+{
+  Module(
+      const char* _moduleApiVersion,
+      const char* _mesosVersion,
+      const char* _authorName,
+      const char* _authorEmail,
+      const char* _description,
+      bool (*_compatible)(),
+      process::http::authentication::Authenticator* (*_create)(
+          const Parameters& parameters))
+    : ModuleBase(
+        _moduleApiVersion,
+        _mesosVersion,
+        mesos::modules::kind<process::http::authentication::Authenticator>(),
+        _authorName,
+        _authorEmail,
+        _description,
+        _compatible),
+      create(_create) {}
+
+  process::http::authentication::Authenticator* (*create)(
+      const Parameters& parameters);
+};
+
+} // namespace modules {
+} // namespace mesos {
+
+#endif // __MESOS_MODULE_HTTP_AUTHENTICATOR_HPP__

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 81afdc6..6ae44c7 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -87,6 +87,7 @@ set(AUTHENTICATION_SRC
   authentication/cram_md5/authenticatee.cpp
   authentication/cram_md5/authenticator.cpp
   authentication/cram_md5/auxprop.cpp
+  authentication/http/basic_authenticator_factory.cpp
   )
 
 set(AUTHORIZER_SRC

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/Makefile.am
----------------------------------------------------------------------
diff --git a/src/Makefile.am b/src/Makefile.am
index 865926c..bbd0c11 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -370,7 +370,8 @@ authentication_HEADERS =						\
   $(top_srcdir)/include/mesos/authentication/authenticatee.hpp		\
   $(top_srcdir)/include/mesos/authentication/authentication.hpp		\
   $(top_srcdir)/include/mesos/authentication/authentication.proto	\
-  $(top_srcdir)/include/mesos/authentication/authenticator.hpp
+  $(top_srcdir)/include/mesos/authentication/authenticator.hpp		\
+  $(top_srcdir)/include/mesos/authentication/http/basic_authenticator_factory.hpp
 
 nodist_authentication_HEADERS =						\
   ../include/mesos/authentication/authentication.pb.h
@@ -451,6 +452,7 @@ module_HEADERS =							\
   $(top_srcdir)/include/mesos/module/authorizer.hpp			\
   $(top_srcdir)/include/mesos/module/container_logger.hpp		\
   $(top_srcdir)/include/mesos/module/hook.hpp				\
+  $(top_srcdir)/include/mesos/module/http_authenticator.hpp		\
   $(top_srcdir)/include/mesos/module/isolator.hpp			\
   $(top_srcdir)/include/mesos/module/module.hpp				\
   $(top_srcdir)/include/mesos/module/module.proto			\
@@ -556,6 +558,7 @@ libmesos_no_3rdparty_la_SOURCES +=					\
   authentication/cram_md5/authenticatee.cpp				\
   authentication/cram_md5/authenticator.cpp				\
   authentication/cram_md5/auxprop.cpp					\
+  authentication/http/basic_authenticator_factory.cpp			\
   authorizer/authorizer.cpp						\
   authorizer/local/authorizer.cpp					\
   common/attributes.cpp							\
@@ -1668,6 +1671,12 @@ libtestauthorizer_la_SOURCES = examples/test_authorizer_module.cpp
 libtestauthorizer_la_CPPFLAGS = $(MESOS_CPPFLAGS)
 libtestauthorizer_la_LDFLAGS = $(MESOS_TEST_MODULE_LDFLAGS)
 
+# Library containing the test http authenticator module.
+noinst_LTLIBRARIES += libtesthttpauthenticator.la
+libtesthttpauthenticator_la_SOURCES = examples/test_http_authenticator_module.cpp
+libtesthttpauthenticator_la_CPPFLAGS = $(MESOS_CPPFLAGS)
+libtesthttpauthenticator_la_LDFLAGS = $(MESOS_TEST_MODULE_LDFLAGS)
+
 # Library containing the test DRF allocator module.
 noinst_LTLIBRARIES += libtestallocator.la
 libtestallocator_la_SOURCES = examples/test_allocator_module.cpp
@@ -1733,6 +1742,7 @@ mesos_tests_SOURCES =						\
   tests/health_check_tests.cpp					\
   tests/hierarchical_allocator_tests.cpp			\
   tests/hook_tests.cpp						\
+  tests/http_authentication_tests.cpp				\
   tests/log_tests.cpp						\
   tests/logging_tests.cpp					\
   tests/main.cpp						\

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/authentication/http/basic_authenticator_factory.cpp
----------------------------------------------------------------------
diff --git a/src/authentication/http/basic_authenticator_factory.cpp b/src/authentication/http/basic_authenticator_factory.cpp
new file mode 100644
index 0000000..21b9b2f
--- /dev/null
+++ b/src/authentication/http/basic_authenticator_factory.cpp
@@ -0,0 +1,58 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <mesos/authentication/http/basic_authenticator_factory.hpp>
+
+#include <mesos/module/http_authenticator.hpp>
+
+#include "master/constants.hpp"
+
+#include "module/manager.hpp"
+
+namespace mesos {
+namespace http {
+namespace authentication {
+
+using std::string;
+
+using process::http::authentication::Authenticator;
+using process::http::authentication::BasicAuthenticator;
+
+
+Try<Authenticator*> BasicAuthenticatorFactory::create(
+    const Parameters& parameters)
+{
+  hashmap<string, string> credentials;
+
+  foreach (const Parameter& parameter, parameters.parameter()) {
+    credentials.put(parameter.key(), parameter.value());
+  }
+
+  return create(credentials);
+}
+
+
+Try<Authenticator*> BasicAuthenticatorFactory::create(
+    const hashmap<std::string, std::string>& credentials)
+{
+  Authenticator* authenticator = new BasicAuthenticator("mesos", credentials);
+
+  return authenticator;
+}
+
+} // namespace authentication {
+} // namespace http {
+} // namespace mesos {

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/examples/test_http_authenticator_module.cpp
----------------------------------------------------------------------
diff --git a/src/examples/test_http_authenticator_module.cpp b/src/examples/test_http_authenticator_module.cpp
new file mode 100644
index 0000000..acf51a6
--- /dev/null
+++ b/src/examples/test_http_authenticator_module.cpp
@@ -0,0 +1,53 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <string>
+
+#include <mesos/authentication/http/basic_authenticator_factory.hpp>
+
+#include <mesos/mesos.hpp>
+#include <mesos/module.hpp>
+
+#include <mesos/module/http_authenticator.hpp>
+
+#include <process/authenticator.hpp>
+
+#include <stout/hashmap.hpp>
+
+using namespace mesos;
+
+using mesos::http::authentication::BasicAuthenticatorFactory;
+
+using process::http::authentication::Authenticator;
+
+
+static Authenticator* createHttpAuthenticator(const Parameters& parameters)
+{
+  return BasicAuthenticatorFactory::create(parameters).get();
+}
+
+
+// Declares an HTTP Authenticator module named
+// 'org_apache_mesos_TestHttpBasicAuthenticator'.
+mesos::modules::Module<Authenticator>
+org_apache_mesos_TestHttpBasicAuthenticator(
+    MESOS_MODULE_API_VERSION,
+    MESOS_VERSION,
+    "Apache Mesos",
+    "modules@mesos.apache.org",
+    "Test HTTP Authenticator module.",
+    NULL,
+    createHttpAuthenticator);

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/master/constants.cpp
----------------------------------------------------------------------
diff --git a/src/master/constants.cpp b/src/master/constants.cpp
index 589f2ee..7dab19d 100644
--- a/src/master/constants.cpp
+++ b/src/master/constants.cpp
@@ -47,6 +47,7 @@ const std::string DEFAULT_AUTHENTICATOR = "crammd5";
 const std::string DEFAULT_ALLOCATOR = "HierarchicalDRF";
 const Duration DEFAULT_ALLOCATION_INTERVAL = Seconds(1);
 const std::string DEFAULT_AUTHORIZER = "local";
+const std::string DEFAULT_HTTP_AUTHENTICATOR = "basic";
 
 } // namespace master {
 } // namespace internal {

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/master/constants.hpp
----------------------------------------------------------------------
diff --git a/src/master/constants.hpp b/src/master/constants.hpp
index f1624e1..3c264f3 100644
--- a/src/master/constants.hpp
+++ b/src/master/constants.hpp
@@ -131,6 +131,9 @@ extern const Duration DEFAULT_ALLOCATION_INTERVAL;
 // Name of the default, local authorizer.
 extern const std::string DEFAULT_AUTHORIZER;
 
+// Name of the default, basic authenticator.
+extern const std::string DEFAULT_HTTP_AUTHENTICATOR;
+
 } // namespace master {
 } // namespace internal {
 } // namespace mesos {

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/module/manager.cpp
----------------------------------------------------------------------
diff --git a/src/module/manager.cpp b/src/module/manager.cpp
index 127942e..a53f71b 100644
--- a/src/module/manager.cpp
+++ b/src/module/manager.cpp
@@ -66,6 +66,7 @@ void ModuleManager::initialize()
   kindToVersion["Authorizer"] = MESOS_VERSION;
   kindToVersion["ContainerLogger"] = MESOS_VERSION;
   kindToVersion["Hook"] = MESOS_VERSION;
+  kindToVersion["HttpAuthenticator"] = MESOS_VERSION;
   kindToVersion["Isolator"] = MESOS_VERSION;
   kindToVersion["QoSController"] = MESOS_VERSION;
   kindToVersion["ResourceEstimator"] = MESOS_VERSION;

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/tests/http_authentication_tests.cpp
----------------------------------------------------------------------
diff --git a/src/tests/http_authentication_tests.cpp b/src/tests/http_authentication_tests.cpp
new file mode 100644
index 0000000..3d6da53
--- /dev/null
+++ b/src/tests/http_authentication_tests.cpp
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <gtest/gtest.h>
+
+#include <string>
+#include <vector>
+
+#include <mesos/authentication/http/basic_authenticator_factory.hpp>
+
+#include <mesos/module/http_authenticator.hpp>
+
+#include <process/authenticator.hpp>
+#include <process/gtest.hpp>
+#include <process/http.hpp>
+
+#include <stout/base64.hpp>
+#include <stout/hashmap.hpp>
+#include <stout/hashset.hpp>
+
+#include "tests/mesos.hpp"
+#include "tests/module.hpp"
+
+using namespace process;
+
+using std::string;
+using std::vector;
+
+namespace process {
+namespace http {
+
+bool operator==(const Forbidden &left, const Forbidden &right)
+{
+  return left.body == right.body;
+}
+
+
+bool operator==(const Unauthorized &left, const Unauthorized &right)
+{
+  return left.body == right.body &&
+         left.headers.get("WWW-Authenticate") ==
+             right.headers.get("WWW-Authenticate");
+}
+
+
+namespace authentication {
+
+bool operator==(
+    const AuthenticationResult& left,
+    const AuthenticationResult& right)
+{
+  return left.principal == right.principal &&
+      left.unauthorized == right.unauthorized &&
+      left.forbidden == right.forbidden;
+}
+
+} // namespace authentication {
+
+} // namespace http {
+} // namespace process {
+
+namespace mesos {
+namespace internal {
+namespace tests {
+
+using mesos::http::authentication::BasicAuthenticatorFactory;
+
+using process::http::Request;
+using process::http::Unauthorized;
+
+using process::http::authentication::Authenticator;
+using process::http::authentication::AuthenticationResult;
+
+
+template <typename T>
+class HttpAuthenticationTest : public MesosTest {};
+
+typedef ::testing::Types<
+  BasicAuthenticatorFactory,
+  tests::Module<Authenticator, TestHttpBasicAuthenticator>>
+  HttpAuthenticatorTypes;
+
+TYPED_TEST_CASE(HttpAuthenticationTest, HttpAuthenticatorTypes);
+
+
+// Tests the HTTP basic authenticator without credentials.
+// Full HTTP stack tests are located in libprocess-tests.
+TYPED_TEST(HttpAuthenticationTest, BasicWithoutCredentialsTest)
+{
+  Parameters parameters;
+
+  Try<Authenticator*> create = TypeParam::create(parameters);
+  ASSERT_SOME(create);
+  Owned<Authenticator> authenticator(create.get());
+
+  EXPECT_EQ("Basic", authenticator->scheme());
+
+  // No credentials given.
+  {
+    AuthenticationResult unauthorized;
+    unauthorized.unauthorized =
+      Unauthorized(vector<string>({"Basic realm=\"mesos\""}));
+
+    Request request;
+
+    AWAIT_EXPECT_EQ(unauthorized, authenticator->authenticate(request));
+  }
+
+  // Unrecognized credentials.
+  {
+    Request request;
+    request.headers.put(
+        "Authorization",
+        "Basic " + base64::encode("user:password"));
+
+    AuthenticationResult unauthorized;
+    unauthorized.unauthorized =
+      Unauthorized(vector<string>({"Basic realm=\"mesos\""}));
+
+    AWAIT_EXPECT_EQ(unauthorized, authenticator->authenticate(request));
+  }
+}
+
+
+// Tests the HTTP basic authenticator with credentials.
+// Full HTTP stack tests are located in libprocess-tests.
+TYPED_TEST(HttpAuthenticationTest, BasicWithCredentialsTest)
+{
+  Parameters parameters;
+  auto entry = parameters.add_parameter();
+  entry->set_key("user");
+  entry->set_value("password");
+
+  Try<Authenticator*> create = TypeParam::create(parameters);
+  ASSERT_SOME(create);
+  Owned<Authenticator> authenticator(create.get());
+
+  EXPECT_EQ("Basic", authenticator->scheme());
+
+  // No credentials given.
+  {
+    Request request;
+
+    AuthenticationResult unauthorized;
+    unauthorized.unauthorized =
+      Unauthorized(vector<string>({"Basic realm=\"mesos\""}));
+
+    AWAIT_EXPECT_EQ(unauthorized, authenticator->authenticate(request));
+  }
+
+  // Wrong credentials given.
+  {
+    Request request;
+
+    request.headers.put(
+        "Authorization",
+        "Basic " + base64::encode("wronguser:wrongpassword"));
+
+    AuthenticationResult unauthorized;
+    unauthorized.unauthorized =
+      Unauthorized(vector<string>({"Basic realm=\"mesos\""}));
+
+    AWAIT_EXPECT_EQ(unauthorized, authenticator->authenticate(request));
+  }
+
+  // Right credentials given.
+  {
+    Request request;
+
+    AuthenticationResult principal;
+    principal.principal = "user";
+
+    request.headers.put(
+        "Authorization",
+        "Basic " + base64::encode("user:password"));
+
+    AWAIT_EXPECT_EQ(principal, authenticator->authenticate(request));
+  }
+}
+
+} // namespace tests {
+} // namespace internal {
+} // namespace mesos {

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/tests/module.cpp
----------------------------------------------------------------------
diff --git a/src/tests/module.cpp b/src/tests/module.cpp
index 7968519..f0e64f7 100644
--- a/src/tests/module.cpp
+++ b/src/tests/module.cpp
@@ -226,6 +226,29 @@ static void addAuthorizerModules(Modules* modules)
 }
 
 
+static void addHttpAuthenticatorModules(Modules* modules)
+{
+  CHECK_NOTNULL(modules);
+
+  const string libraryPath = path::join(
+      tests::flags.build_dir,
+      "src",
+      ".libs",
+      os::libraries::expandName("testhttpauthenticator"));
+
+  // Now add our test HTTP authenticator module.
+  Modules::Library* library = modules->add_libraries();
+  library->set_file(libraryPath);
+
+  // To add a new module from this library, create a new ModuleID enum
+  // and tie it with a module name.
+  addModule(
+      library,
+      TestHttpBasicAuthenticator,
+      "org_apache_mesos_TestHttpBasicAuthenticator");
+}
+
+
 Try<Nothing> initModules(const Option<Modules>& modules)
 {
   // First get the user provided modules.
@@ -258,6 +281,9 @@ Try<Nothing> initModules(const Option<Modules>& modules)
   // Add authorizer modules from testauthorizer library.
   addAuthorizerModules(&mergedModules);
 
+  // Add HTTP authenticator modules from testhttpauthenticator library.
+  addHttpAuthenticatorModules(&mergedModules);
+
   return ModuleManager::load(mergedModules);
 }
 

http://git-wip-us.apache.org/repos/asf/mesos/blob/51607398/src/tests/module.hpp
----------------------------------------------------------------------
diff --git a/src/tests/module.hpp b/src/tests/module.hpp
index 8e92774..49a9203 100644
--- a/src/tests/module.hpp
+++ b/src/tests/module.hpp
@@ -49,6 +49,7 @@ enum ModuleID
   TestNoopResourceEstimator,
   TestLocalAuthorizer,
   TestSandboxContainerLogger,
+  TestHttpBasicAuthenticator
 };
 
 


[2/3] mesos git commit: Updated support for HTTP authentication.

Posted by ti...@apache.org.
Updated support for HTTP authentication.

1. Adds a flag to load an HTTP authenticator module.

2. If provided, uses the credentials file to initialize the default
HTTP authenticator.

3. Updates the existing endpoints which implemented their own basic
HTTP authenticator with the new, libprocess one.

4. Updates one test which expected the wrong results since now
credentials are checked before the body of the request.

Review: https://reviews.apache.org/r/39043/


Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/b294c3cc
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/b294c3cc
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/b294c3cc

Branch: refs/heads/master
Commit: b294c3ccc4f83924e276a04b1057b5bad9e90ada
Parents: 5160739
Author: Alexander Rojas <al...@mesosphere.io>
Authored: Fri Jan 8 03:29:39 2016 +0100
Committer: Till Toenshoff <to...@me.com>
Committed: Fri Jan 8 04:18:26 2016 +0100

----------------------------------------------------------------------
 docs/configuration.md                           |  13 +++
 .../http/basic_authenticator_factory.hpp        |   3 +
 .../http/basic_authenticator_factory.cpp        |  15 +++
 src/master/constants.cpp                        |   1 +
 src/master/constants.hpp                        |   3 +
 src/master/flags.cpp                            |  11 +-
 src/master/flags.hpp                            |   1 +
 src/master/http.cpp                             | 111 ++++---------------
 src/master/master.cpp                           | 103 +++++++++++++++--
 src/master/master.hpp                           |  37 +++----
 src/master/quota_handler.cpp                    |  31 ++----
 src/tests/master_quota_tests.cpp                |  10 +-
 src/tests/mesos.cpp                             |   5 +
 13 files changed, 194 insertions(+), 150 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/docs/configuration.md
----------------------------------------------------------------------
diff --git a/docs/configuration.md b/docs/configuration.md
index fb6f678..705ea7a 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -347,6 +347,19 @@ file:///path/to/file (where file contains one of the above)</code></pre>
   </tr>
   <tr>
     <td>
+      --http_authenticators=VALUE
+    </td>
+    <td>
+      HTTP authenticator implementation to use when handling requests to
+      authenticated endpoints. Use the default <code>basic<code>, or
+      load an alternate HTTP authenticator module using <code>--modules</code>.
+      <p/>
+      Currently there is no support for multiple HTTP authenticators.
+      (default: basic)
+    </td>
+  </tr>
+  <tr>
+    <td>
       --authorizers=VALUE
     </td>
     <td>

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/include/mesos/authentication/http/basic_authenticator_factory.hpp
----------------------------------------------------------------------
diff --git a/include/mesos/authentication/http/basic_authenticator_factory.hpp b/include/mesos/authentication/http/basic_authenticator_factory.hpp
index 066303d..c11bb47 100644
--- a/include/mesos/authentication/http/basic_authenticator_factory.hpp
+++ b/include/mesos/authentication/http/basic_authenticator_factory.hpp
@@ -38,6 +38,9 @@ public:
       const Parameters& parameters);
 
   static Try<process::http::authentication::Authenticator*> create(
+      const Credentials& credentials);
+
+  static Try<process::http::authentication::Authenticator*> create(
       const hashmap<std::string, std::string>& credentials);
 
 protected:

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/authentication/http/basic_authenticator_factory.cpp
----------------------------------------------------------------------
diff --git a/src/authentication/http/basic_authenticator_factory.cpp b/src/authentication/http/basic_authenticator_factory.cpp
index 21b9b2f..6eb1c5b 100644
--- a/src/authentication/http/basic_authenticator_factory.cpp
+++ b/src/authentication/http/basic_authenticator_factory.cpp
@@ -18,6 +18,8 @@
 
 #include <mesos/module/http_authenticator.hpp>
 
+#include <stout/foreach.hpp>
+
 #include "master/constants.hpp"
 
 #include "module/manager.hpp"
@@ -33,6 +35,19 @@ using process::http::authentication::BasicAuthenticator;
 
 
 Try<Authenticator*> BasicAuthenticatorFactory::create(
+    const Credentials& credentials)
+{
+  hashmap<string, string> credentialMap;
+
+  foreach (const Credential& credential, credentials.credentials()) {
+    credentialMap.put(credential.principal(), credential.secret());
+  }
+
+  return create(credentialMap);
+}
+
+
+Try<Authenticator*> BasicAuthenticatorFactory::create(
     const Parameters& parameters)
 {
   hashmap<string, string> credentials;

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/master/constants.cpp
----------------------------------------------------------------------
diff --git a/src/master/constants.cpp b/src/master/constants.cpp
index 7dab19d..77dd314 100644
--- a/src/master/constants.cpp
+++ b/src/master/constants.cpp
@@ -48,6 +48,7 @@ const std::string DEFAULT_ALLOCATOR = "HierarchicalDRF";
 const Duration DEFAULT_ALLOCATION_INTERVAL = Seconds(1);
 const std::string DEFAULT_AUTHORIZER = "local";
 const std::string DEFAULT_HTTP_AUTHENTICATOR = "basic";
+const std::string DEFAULT_HTTP_AUTHENTICATION_REALM = "mesos";
 
 } // namespace master {
 } // namespace internal {

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/master/constants.hpp
----------------------------------------------------------------------
diff --git a/src/master/constants.hpp b/src/master/constants.hpp
index 3c264f3..ebab341 100644
--- a/src/master/constants.hpp
+++ b/src/master/constants.hpp
@@ -134,6 +134,9 @@ extern const std::string DEFAULT_AUTHORIZER;
 // Name of the default, basic authenticator.
 extern const std::string DEFAULT_HTTP_AUTHENTICATOR;
 
+// Name of the default, "mesos" HTTP authentication realm.
+extern const std::string DEFAULT_HTTP_AUTHENTICATION_REALM;
+
 } // namespace master {
 } // namespace internal {
 } // namespace mesos {

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/master/flags.cpp
----------------------------------------------------------------------
diff --git a/src/master/flags.cpp b/src/master/flags.cpp
index f864419..de068ee 100644
--- a/src/master/flags.cpp
+++ b/src/master/flags.cpp
@@ -430,7 +430,6 @@ mesos::internal::master::Flags::Flags()
         return None();
       });
 
-
   add(&Flags::authorizers,
       "authorizers",
       "Authorizer implementation to use when authorizating actions that\n"
@@ -444,4 +443,14 @@ mesos::internal::master::Flags::Flags()
       "\n"
       "Currently there's no support for multiple authorizers.",
       DEFAULT_AUTHORIZER);
+
+  add(&Flags::http_authenticators,
+      "http_authenticators",
+      "HTTP authenticator implementation to use when handling requests to\n"
+      "authenticated endpoints. Use the default\n"
+      "'" + DEFAULT_HTTP_AUTHENTICATOR + "', or load an alternate HTTP\n"
+      "authenticator module using --modules.\n"
+      "\n"
+      "Currently there is no support for multiple HTTP authenticators.",
+      DEFAULT_HTTP_AUTHENTICATOR);
 }

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/master/flags.hpp
----------------------------------------------------------------------
diff --git a/src/master/flags.hpp b/src/master/flags.hpp
index 9af6c68..c3dae1c 100644
--- a/src/master/flags.hpp
+++ b/src/master/flags.hpp
@@ -78,6 +78,7 @@ public:
   Duration slave_ping_timeout;
   size_t max_slave_ping_timeouts;
   std::string authorizers;
+  std::string http_authenticators;
 
 #ifdef WITH_NETWORK_ISOLATOR
   Option<size_t> max_executors_per_slave;

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/master/http.cpp
----------------------------------------------------------------------
diff --git a/src/master/http.cpp b/src/master/http.cpp
index d7afa2a..bcafc7a 100644
--- a/src/master/http.cpp
+++ b/src/master/http.cpp
@@ -527,18 +527,15 @@ static Resources removeDiskInfos(const Resources& resources)
 }
 
 
-Future<Response> Master::Http::createVolumes(const Request& request) const
+Future<Response> Master::Http::createVolumes(
+    const Request& request,
+    const Option<string>& principal) const
 {
   if (request.method != "POST") {
     return MethodNotAllowed(
         {"POST"}, "Expecting 'POST', received '" + request.method + "'");
   }
 
-  Result<Credential> credential = authenticate(request);
-  if (credential.isError()) {
-    return Unauthorized("Mesos master", credential.error());
-  }
-
   // Parse the query string in the request body.
   Try<hashmap<string, string>> decode =
     process::http::query::decode(request.body);
@@ -595,9 +592,6 @@ Future<Response> Master::Http::createVolumes(const Request& request) const
     return BadRequest("Invalid CREATE operation: " + validate.get().message);
   }
 
-  Option<string> principal =
-    credential.isSome() ? credential.get().principal() : Option<string>::none();
-
   return master->authorizeCreateVolume(operation.create(), principal)
     .then(defer(master->self(), [=](bool authorized) -> Future<Response> {
       if (!authorized) {
@@ -624,18 +618,15 @@ string Master::Http::DESTROY_VOLUMES_HELP()
 }
 
 
-Future<Response> Master::Http::destroyVolumes(const Request& request) const
+Future<Response> Master::Http::destroyVolumes(
+    const Request& request,
+    const Option<string>& principal) const
 {
   if (request.method != "POST") {
     return MethodNotAllowed(
         {"POST"}, "Expecting 'POST', received '" + request.method + "'");
   }
 
-  Result<Credential> credential = authenticate(request);
-  if (credential.isError()) {
-    return Unauthorized("Mesos master", credential.error());
-  }
-
   // Parse the query string in the request body.
   Try<hashmap<string, string>> decode =
     process::http::query::decode(request.body);
@@ -692,9 +683,6 @@ Future<Response> Master::Http::destroyVolumes(const Request& request) const
     return BadRequest("Invalid DESTROY operation: " + validate.get().message);
   }
 
-  Option<string> principal =
-    credential.isSome() ? credential.get().principal() : Option<string>::none();
-
   return master->authorizeDestroyVolume(operation.destroy(), principal)
     .then(defer(master->self(), [=](bool authorized) -> Future<Response> {
       if (!authorized) {
@@ -959,18 +947,15 @@ string Master::Http::RESERVE_HELP()
 }
 
 
-Future<Response> Master::Http::reserve(const Request& request) const
+Future<Response> Master::Http::reserve(
+    const Request& request,
+    const Option<string>& principal) const
 {
   if (request.method != "POST") {
     return MethodNotAllowed(
         {"POST"}, "Expecting 'POST', received '" + request.method + "'");
   }
 
-  Result<Credential> credential = authenticate(request);
-  if (credential.isError()) {
-    return Unauthorized("Mesos master", credential.error());
-  }
-
   // Parse the query string in the request body.
   Try<hashmap<string, string>> decode =
     process::http::query::decode(request.body);
@@ -1020,9 +1005,6 @@ Future<Response> Master::Http::reserve(const Request& request) const
   operation.set_type(Offer::Operation::RESERVE);
   operation.mutable_reserve()->mutable_resources()->CopyFrom(resources);
 
-  Option<string> principal =
-    credential.isSome() ? credential.get().principal() : Option<string>::none();
-
   Option<Error> error = validation::operation::validate(
       operation.reserve(), None(), principal);
 
@@ -1086,7 +1068,9 @@ string Master::Http::QUOTA_HELP()
 }
 
 
-Future<Response> Master::Http::quota(const Request& request) const
+Future<Response> Master::Http::quota(
+    const Request& request,
+    const Option<string>& principal) const
 {
   // Dispatch based on HTTP method to separate `QuotaHandler`.
   if (request.method == "GET") {
@@ -1094,11 +1078,11 @@ Future<Response> Master::Http::quota(const Request& request) const
   }
 
   if (request.method == "POST") {
-    return quotaHandler.set(request);
+    return quotaHandler.set(request, principal);
   }
 
   if (request.method == "DELETE") {
-    return quotaHandler.remove(request);
+    return quotaHandler.remove(request, principal);
   }
 
   // TODO(joerg84): Add update logic for PUT requests
@@ -1644,18 +1628,15 @@ string Master::Http::TEARDOWN_HELP()
 }
 
 
-Future<Response> Master::Http::teardown(const Request& request) const
+Future<Response> Master::Http::teardown(
+    const Request& request,
+    const Option<string>& principal) const
 {
   if (request.method != "POST") {
     return MethodNotAllowed(
         {"POST"}, "Expecting 'POST', received '" + request.method + "'");
   }
 
-  Result<Credential> credential = authenticate(request);
-  if (credential.isError()) {
-    return Unauthorized("Mesos master", credential.error());
-  }
-
   // Parse the query string in the request body (since this is a POST)
   // in order to determine the framework ID to shutdown.
   Try<hashmap<string, string>> decode =
@@ -1687,8 +1668,8 @@ Future<Response> Master::Http::teardown(const Request& request) const
 
   mesos::ACL::ShutdownFramework shutdown;
 
-  if (credential.isSome()) {
-    shutdown.mutable_principals()->add_values(credential.get().principal());
+  if (principal.isSome()) {
+    shutdown.mutable_principals()->add_values(principal.get());
   } else {
     shutdown.mutable_principals()->set_type(ACL::Entity::ANY);
   }
@@ -2262,18 +2243,15 @@ string Master::Http::UNRESERVE_HELP()
 }
 
 
-Future<Response> Master::Http::unreserve(const Request& request) const
+Future<Response> Master::Http::unreserve(
+    const Request& request,
+    const Option<string>& principal) const
 {
   if (request.method != "POST") {
     return MethodNotAllowed(
         {"POST"}, "Expecting 'POST', received '" + request.method + "'");
   }
 
-  Result<Credential> credential = authenticate(request);
-  if (credential.isError()) {
-    return Unauthorized("Mesos master", credential.error());
-  }
-
   // Parse the query string in the request body.
   Try<hashmap<string, string>> decode =
     process::http::query::decode(request.body);
@@ -2323,9 +2301,6 @@ Future<Response> Master::Http::unreserve(const Request& request) const
   operation.set_type(Offer::Operation::UNRESERVE);
   operation.mutable_unreserve()->mutable_resources()->CopyFrom(resources);
 
-  Option<string> principal =
-    credential.isSome() ? credential.get().principal() : Option<string>::none();
-
   Option<Error> error = validation::operation::validate(
       operation.unreserve(), principal.isSome());
 
@@ -2345,48 +2320,6 @@ Future<Response> Master::Http::unreserve(const Request& request) const
 }
 
 
-Result<Credential> Master::Http::authenticate(const Request& request) const
-{
-  // By default, assume everyone is authenticated if no credentials
-  // were provided.
-  if (master->credentials.isNone()) {
-    return None();
-  }
-
-  Option<string> authorization = request.headers.get("Authorization");
-
-  if (authorization.isNone()) {
-    return Error("Missing 'Authorization' request header");
-  }
-
-  Try<string> decode =
-    base64::decode(strings::split(authorization.get(), " ", 2)[1]);
-
-  if (decode.isError()) {
-    return Error("Failed to decode 'Authorization' header: " + decode.error());
-  }
-
-  vector<string> pairs = strings::split(decode.get(), ":", 2);
-
-  if (pairs.size() != 2) {
-    return Error("Malformed 'Authorization' request header");
-  }
-
-  const string& username = pairs[0];
-  const string& password = pairs[1];
-
-  foreach (const Credential& credential,
-          master->credentials.get().credentials()) {
-    if (credential.principal() == username &&
-        credential.secret() == password) {
-      return credential;
-    }
-  }
-
-  return Error("Could not authenticate '" + username + "'");
-}
-
-
 Future<Response> Master::Http::_operation(
     const SlaveID& slaveId,
     Resources required,

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/master/master.cpp
----------------------------------------------------------------------
diff --git a/src/master/master.cpp b/src/master/master.cpp
index 145c593..44c5193 100644
--- a/src/master/master.cpp
+++ b/src/master/master.cpp
@@ -28,11 +28,14 @@
 
 #include <mesos/authentication/authenticator.hpp>
 
+#include <mesos/authentication/http/basic_authenticator_factory.hpp>
+
 #include <mesos/authorizer/authorizer.hpp>
 
 #include <mesos/master/allocator.hpp>
 
 #include <mesos/module/authenticator.hpp>
+#include <mesos/module/http_authenticator.hpp>
 
 #include <process/check.hpp>
 #include <process/collect.hpp>
@@ -113,8 +116,12 @@ namespace mesos {
 namespace internal {
 namespace master {
 
+namespace authentication = process::http::authentication;
+
 using mesos::master::allocator::Allocator;
 
+using mesos::http::authentication::BasicAuthenticatorFactory;
+
 
 class SlaveObserver : public ProtobufProcess<SlaveObserver>
 {
@@ -420,6 +427,7 @@ void Master::initialize()
   }
 
   // Load credentials.
+  Option<Credentials> credentials;
   if (flags.credentials.isSome()) {
     Result<Credentials> _credentials =
       credentials::read(flags.credentials.get());
@@ -489,6 +497,65 @@ void Master::initialize()
     }
   }
 
+  // TODO(arojas): Consider creating a factory function for the instantiation
+  // of the HTTP authenticator the same way the allocator does.
+  vector<string> httpAuthenticatorNames =
+    strings::split(flags.http_authenticators, ",");
+
+  // At least the default authenticator is always specified.
+  // Passing an empty string into the `http_authenticators`
+  // flag is considered an error.
+  if (httpAuthenticatorNames.empty()) {
+    EXIT(1) << "No HTTP authenticator specified";
+  }
+  if (httpAuthenticatorNames.size() > 1) {
+    EXIT(1) << "Multiple HTTP authenticators not supported";
+  }
+  if (httpAuthenticatorNames[0] != DEFAULT_HTTP_AUTHENTICATOR &&
+      !modules::ModuleManager::contains<Authenticator>(
+          httpAuthenticatorNames[0])) {
+    EXIT(1) << "HTTP authenticator '" << httpAuthenticatorNames[0] << "' not "
+            << "found. Check the spelling (compare to '"
+            << DEFAULT_HTTP_AUTHENTICATOR << "'') or verify that the "
+            << "authenticator was loaded successfully (see --modules)";
+  }
+
+  Option<authentication::Authenticator*> httpAuthenticator;
+
+  if (httpAuthenticatorNames[0] == DEFAULT_HTTP_AUTHENTICATOR &&
+      credentials.isSome()) {
+    LOG(INFO) << "Using default '" << DEFAULT_HTTP_AUTHENTICATOR
+              << "' HTTP authenticator";
+
+    Try<authentication::Authenticator*> authenticator =
+      BasicAuthenticatorFactory::create(credentials.get());
+    if (authenticator.isError()) {
+      EXIT(1) << "Could not create HTTP authenticator module '"
+              << httpAuthenticatorNames[0] << "': " << authenticator.error();
+    }
+
+    httpAuthenticator = authenticator.get();
+  } else if (httpAuthenticatorNames[0] != DEFAULT_HTTP_AUTHENTICATOR) {
+    Try<authentication::Authenticator*> module =
+      modules::ModuleManager::create<authentication::Authenticator>(
+          httpAuthenticatorNames[0]);
+    if (module.isError()) {
+      EXIT(1) << "Could not create HTTP authenticator module '"
+              << httpAuthenticatorNames[0] << "': " << module.error();
+    }
+    LOG(INFO) << "Using '" << httpAuthenticatorNames[0]
+              << "' HTTP authenticator";
+    httpAuthenticator = module.get();
+  }
+
+  if (httpAuthenticator.isSome() && httpAuthenticator.get() != NULL) {
+    // Ownership of the `httpAuthenticator` is passed to libprocess.
+    process::http::authentication::setAuthenticator(
+        DEFAULT_HTTP_AUTHENTICATION_REALM,
+        Owned<authentication::Authenticator>(httpAuthenticator.get()));
+    httpAuthenticator = None();
+  }
+
   if (authorizer.isSome()) {
     LOG(INFO) << "Authorization enabled";
   }
@@ -744,16 +811,20 @@ void Master::initialize()
           return http.scheduler(request);
         });
   route("/create-volumes",
+        DEFAULT_HTTP_AUTHENTICATION_REALM,
         Http::CREATE_VOLUMES_HELP(),
-        [this](const process::http::Request& request) {
+        [this](const process::http::Request& request,
+               const Option<string>& principal) {
           Http::log(request);
-          return http.createVolumes(request);
+          return http.createVolumes(request, principal);
         });
   route("/destroy-volumes",
+        DEFAULT_HTTP_AUTHENTICATION_REALM,
         Http::DESTROY_VOLUMES_HELP(),
-        [this](const process::http::Request& request) {
+        [this](const process::http::Request& request,
+               const Option<string>& principal) {
           Http::log(request);
-          return http.destroyVolumes(request);
+          return http.destroyVolumes(request, principal);
         });
   route("/frameworks",
         Http::FRAMEWORKS(),
@@ -784,10 +855,12 @@ void Master::initialize()
           return http.redirect(request);
         });
   route("/reserve",
+        DEFAULT_HTTP_AUTHENTICATION_REALM,
         Http::RESERVE_HELP(),
-        [this](const process::http::Request& request) {
+        [this](const process::http::Request& request,
+               const Option<string>& principal) {
           Http::log(request);
-          return http.reserve(request);
+          return http.reserve(request, principal);
         });
   // TODO(ijimenez): Remove this endpoint at the end of the
   // deprecation cycle on 0.26.
@@ -804,10 +877,12 @@ void Master::initialize()
           return http.roles(request);
         });
   route("/teardown",
+        DEFAULT_HTTP_AUTHENTICATION_REALM,
         Http::TEARDOWN_HELP(),
-        [this](const process::http::Request& request) {
+        [this](const process::http::Request& request,
+               const Option<string>& principal) {
           Http::log(request);
-          return http.teardown(request);
+          return http.teardown(request, principal);
         });
   route("/slaves",
         Http::SLAVES_HELP(),
@@ -874,16 +949,20 @@ void Master::initialize()
           return http.machineUp(request);
         });
   route("/unreserve",
+        DEFAULT_HTTP_AUTHENTICATION_REALM,
         Http::UNRESERVE_HELP(),
-        [this](const process::http::Request& request) {
+        [this](const process::http::Request& request,
+               const Option<string>& principal) {
           Http::log(request);
-          return http.unreserve(request);
+          return http.unreserve(request, principal);
         });
   route("/quota",
+        DEFAULT_HTTP_AUTHENTICATION_REALM,
         Http::QUOTA_HELP(),
-        [this](const process::http::Request& request) {
+        [this](const process::http::Request& request,
+               const Option<string>& principal) {
           Http::log(request);
-          return http.quota(request);
+          return http.quota(request, principal);
         });
 
   // Provide HTTP assets from a "webui" directory. This is either

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/master/master.hpp
----------------------------------------------------------------------
diff --git a/src/master/master.hpp b/src/master/master.hpp
index f764915..f02d165 100644
--- a/src/master/master.hpp
+++ b/src/master/master.hpp
@@ -830,8 +830,6 @@ protected:
   OfferID newOfferId();
   SlaveID newSlaveId();
 
-  Option<Credentials> credentials;
-
 private:
   void _apply(Slave* slave, const Offer::Operation& operation);
 
@@ -947,10 +945,12 @@ private:
         const process::http::Request& request) const;
 
     process::Future<process::http::Response> set(
-        const process::http::Request& request) const;
+        const process::http::Request& request,
+        const Option<std::string>& principal) const;
 
     process::Future<process::http::Response> remove(
-        const process::http::Request& request) const;
+        const process::http::Request& request,
+        const Option<std::string>& principal) const;
 
   private:
     // Heuristically tries to determine whether a quota request could
@@ -1035,11 +1035,13 @@ private:
 
     // /master/create-volumes
     process::Future<process::http::Response> createVolumes(
-        const process::http::Request& request) const;
+        const process::http::Request& request,
+        const Option<std::string>& principal) const;
 
     // /master/destroy-volumes
     process::Future<process::http::Response> destroyVolumes(
-        const process::http::Request& request) const;
+        const process::http::Request& request,
+        const Option<std::string>& principal) const;
 
     // /master/flags
     process::Future<process::http::Response> flags(
@@ -1063,7 +1065,8 @@ private:
 
     // /master/reserve
     process::Future<process::http::Response> reserve(
-        const process::http::Request& request) const;
+        const process::http::Request& request,
+        const Option<std::string>& principal) const;
 
     // /master/roles
     process::Future<process::http::Response> roles(
@@ -1071,7 +1074,8 @@ private:
 
     // /master/teardown
     process::Future<process::http::Response> teardown(
-        const process::http::Request& request) const;
+        const process::http::Request& request,
+        const Option<std::string>& principal) const;
 
     // /master/slaves
     process::Future<process::http::Response> slaves(
@@ -1107,11 +1111,13 @@ private:
 
     // /master/unreserve
     process::Future<process::http::Response> unreserve(
-        const process::http::Request& request) const;
+        const process::http::Request& request,
+        const Option<std::string>& principal) const;
 
     // /master/quota
     process::Future<process::http::Response> quota(
-        const process::http::Request& request) const;
+        const process::http::Request& request,
+        const Option<std::string>& principal) const;
 
     static std::string SCHEDULER_HELP();
     static std::string FLAGS_HELP();
@@ -1136,12 +1142,6 @@ private:
     static std::string QUOTA_HELP();
 
   private:
-    // Helper for doing authentication, returns the credential used if
-    // the authentication was successful (or none if no credentials
-    // have been given to the master), otherwise an Error.
-    Result<Credential> authenticate(
-        const process::http::Request& request) const;
-
     // Continuations.
     process::Future<process::http::Response> _teardown(
         const FrameworkID& id) const;
@@ -1175,11 +1175,6 @@ private:
     // NOTE: The quota specific pieces of the Operator API are factored
     // out into this separate class.
     QuotaHandler quotaHandler;
-
-    // Access to `authenticate`.
-    // TODO(alexr): Remove this once `authenticate` is moved to libprocess,
-    // see MESOS-4149.
-    friend class QuotaHandler;
   };
 
   Master(const Master&);              // No copying.

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/master/quota_handler.cpp
----------------------------------------------------------------------
diff --git a/src/master/quota_handler.cpp b/src/master/quota_handler.cpp
index 93960f3..134a93b 100644
--- a/src/master/quota_handler.cpp
+++ b/src/master/quota_handler.cpp
@@ -240,16 +240,11 @@ void Master::QuotaHandler::rescindOffers(const QuotaInfo& request) const
 
 
 Future<http::Response> Master::QuotaHandler::set(
-    const http::Request& request) const
+    const http::Request& request,
+    const Option<string>& principal) const
 {
   VLOG(1) << "Setting quota from request: '" << request.body << "'";
 
-  // Authenticate the request.
-  Result<Credential> credential = master->http.authenticate(request);
-  if (credential.isError()) {
-    return Unauthorized("Mesos master", credential.error());
-  }
-
   // Check that the request type is POST which is guaranteed by the master.
   CHECK_EQ("POST", request.method);
 
@@ -335,15 +330,12 @@ Future<http::Response> Master::QuotaHandler::set(
         request.body + "': " + force.error());
   }
 
-  // Extract principal from request credentials.
-  Option<string> principal = None();
-  if (credential.isSome()) {
-    principal = credential.get().principal();
+  const bool forced = force.isSome() ? force.get().value : false;
+
+  if (principal.isSome()) {
     quotaInfo.set_principal(principal.get());
   }
 
-  const bool forced = force.isSome() ? force.get().value : false;
-
   return authorizeSetQuota(principal, quotaInfo.role())
     .then(defer(master->self(), [=](bool authorized) -> Future<http::Response> {
       if (!authorized) {
@@ -405,16 +397,11 @@ Future<http::Response> Master::QuotaHandler::_set(
 
 
 Future<http::Response> Master::QuotaHandler::remove(
-    const http::Request& request) const
+    const http::Request& request,
+    const Option<string>& principal) const
 {
   VLOG(1) << "Removing quota for request path: '" << request.url.path << "'";
 
-  // Authenticate the request.
-  Result<Credential> credential = master->http.authenticate(request);
-  if (credential.isError()) {
-    return Unauthorized("Mesos master", credential.error());
-  }
-
   // Check that the request type is DELETE which is guaranteed by the master.
   CHECK_EQ("DELETE", request.method);
 
@@ -452,10 +439,6 @@ Future<http::Response> Master::QuotaHandler::remove(
         "': Role '" + role + "' has no quota set");
   }
 
-  // Extract principal from request credentials.
-  Option<string> principal =
-    credential.isSome() ? credential.get().principal() : Option<string>::none();
-
   Option<string> quota_principal = master->quotas[role].info.has_principal()
     ? master->quotas[role].info.principal()
     : Option<string>::none();

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/tests/master_quota_tests.cpp
----------------------------------------------------------------------
diff --git a/src/tests/master_quota_tests.cpp b/src/tests/master_quota_tests.cpp
index bc8a117..1bf08ab 100644
--- a/src/tests/master_quota_tests.cpp
+++ b/src/tests/master_quota_tests.cpp
@@ -569,7 +569,11 @@ TEST_F(MasterQuotaTest, StatusSingleQuota)
   AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response) << response.get().body;
 
   // Query the master quota endpoint.
-  response = process::http::get(master.get(), "quota");
+  response = process::http::get(
+      master.get(),
+      "quota",
+      None(),
+      createBasicAuthHeaders(DEFAULT_CREDENTIAL));
   AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response) << response.get().body;
 
   EXPECT_SOME_EQ(
@@ -1187,7 +1191,7 @@ TEST_F(MasterQuotaTest, UnauthenticatedQuotaRequest)
       createRequestBody(quotaResources));
 
   AWAIT_EXPECT_RESPONSE_STATUS_EQ(
-      Unauthorized("Mesos master").status, response1) << response1.get().body;
+      Unauthorized(vector<string>()).status, response1) << response1.get().body;
 
   // The absense of credentials leads to authentication failure as well.
   Future<Response> response2 = process::http::post(
@@ -1197,7 +1201,7 @@ TEST_F(MasterQuotaTest, UnauthenticatedQuotaRequest)
       createRequestBody(quotaResources));
 
   AWAIT_EXPECT_RESPONSE_STATUS_EQ(
-      Unauthorized("Mesos master").status, response2) << response2.get().body;
+      Unauthorized(vector<string>()).status, response2) << response2.get().body;
 
   Shutdown();
 }

http://git-wip-us.apache.org/repos/asf/mesos/blob/b294c3cc/src/tests/mesos.cpp
----------------------------------------------------------------------
diff --git a/src/tests/mesos.cpp b/src/tests/mesos.cpp
index 3867ed2..4208847 100644
--- a/src/tests/mesos.cpp
+++ b/src/tests/mesos.cpp
@@ -432,6 +432,11 @@ void MesosTest::Stop(const PID<slave::Slave>& pid, bool shutdown)
 
 void MesosTest::Shutdown()
 {
+  // TODO(arojas): Authenticators' lifetimes are tied to libprocess's lifetime.
+  // Consider unsetting the authenticator in the master shutdown.
+  // NOTE: This means that multiple masters in tests are not supported.
+  process::http::authentication::unsetAuthenticator(
+      master::DEFAULT_HTTP_AUTHENTICATION_REALM);
   ShutdownMasters();
   ShutdownSlaves();
 }


[3/3] mesos git commit: Added flag for enabling HTTP authentication.

Posted by ti...@apache.org.
Added flag for enabling HTTP authentication.

Adds new `authenticate_http` flag to the master.
Also updates some tests that were using the credentials
for de/activating HTTP authentication.

Review: https://reviews.apache.org/r/42025/


Project: http://git-wip-us.apache.org/repos/asf/mesos/repo
Commit: http://git-wip-us.apache.org/repos/asf/mesos/commit/9f6a2aab
Tree: http://git-wip-us.apache.org/repos/asf/mesos/tree/9f6a2aab
Diff: http://git-wip-us.apache.org/repos/asf/mesos/diff/9f6a2aab

Branch: refs/heads/master
Commit: 9f6a2aab4717780c1e98a05b0f1be3a19a554d20
Parents: b294c3c
Author: Till Toenshoff <to...@me.com>
Authored: Thu Jan 7 14:04:10 2016 +0100
Committer: Till Toenshoff <to...@me.com>
Committed: Fri Jan 8 04:19:43 2016 +0100

----------------------------------------------------------------------
 docs/configuration.md            | 12 +++++++++
 src/master/flags.cpp             |  7 +++++
 src/master/flags.hpp             |  1 +
 src/master/master.cpp            | 51 ++++++++++++++++++++---------------
 src/tests/master_quota_tests.cpp |  8 +++---
 src/tests/mesos.cpp              |  1 +
 6 files changed, 54 insertions(+), 26 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mesos/blob/9f6a2aab/docs/configuration.md
----------------------------------------------------------------------
diff --git a/docs/configuration.md b/docs/configuration.md
index 705ea7a..cbe7f5a 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -336,6 +336,18 @@ file:///path/to/file (where file contains one of the above)</code></pre>
   </tr>
   <tr>
     <td>
+      --[no-]authenticate_http
+    </td>
+    <td>
+      If <code>true</code> only authenticated requests for HTTP endpoints
+      supporting authentication are allowed.
+      <p/>
+      If <code>false</code> unauthenticated HTTP endpoint requests are also allowed.
+      (default: false)
+    </td>
+  </tr>
+  <tr>
+    <td>
       --authenticators=VALUE
     </td>
     <td>

http://git-wip-us.apache.org/repos/asf/mesos/blob/9f6a2aab/src/master/flags.cpp
----------------------------------------------------------------------
diff --git a/src/master/flags.cpp b/src/master/flags.cpp
index de068ee..8890959 100644
--- a/src/master/flags.cpp
+++ b/src/master/flags.cpp
@@ -207,6 +207,13 @@ mesos::internal::master::Flags::Flags()
       "If 'false' unauthenticated slaves are also allowed to register.",
       false);
 
+  add(&Flags::authenticate_http,
+      "authenticate_http",
+      "If 'true' only authenticated requests for HTTP endpoints supporting\n"
+      "authentication are allowed.\n"
+      "If 'false' unauthenticated HTTP endpoint requests are also allowed.\n",
+      false);
+
   add(&Flags::credentials,
       "credentials",
       "Either a path to a text file with a list of credentials,\n"

http://git-wip-us.apache.org/repos/asf/mesos/blob/9f6a2aab/src/master/flags.hpp
----------------------------------------------------------------------
diff --git a/src/master/flags.hpp b/src/master/flags.hpp
index c3dae1c..d923b1b 100644
--- a/src/master/flags.hpp
+++ b/src/master/flags.hpp
@@ -66,6 +66,7 @@ public:
   Option<std::string> weights;
   bool authenticate_frameworks;
   bool authenticate_slaves;
+  bool authenticate_http;
   Option<Path> credentials;
   Option<ACLs> acls;
   Option<Firewall> firewall_rules;

http://git-wip-us.apache.org/repos/asf/mesos/blob/9f6a2aab/src/master/master.cpp
----------------------------------------------------------------------
diff --git a/src/master/master.cpp b/src/master/master.cpp
index 44c5193..2d9b7f9 100644
--- a/src/master/master.cpp
+++ b/src/master/master.cpp
@@ -522,30 +522,37 @@ void Master::initialize()
 
   Option<authentication::Authenticator*> httpAuthenticator;
 
-  if (httpAuthenticatorNames[0] == DEFAULT_HTTP_AUTHENTICATOR &&
-      credentials.isSome()) {
-    LOG(INFO) << "Using default '" << DEFAULT_HTTP_AUTHENTICATOR
-              << "' HTTP authenticator";
-
-    Try<authentication::Authenticator*> authenticator =
-      BasicAuthenticatorFactory::create(credentials.get());
-    if (authenticator.isError()) {
-      EXIT(1) << "Could not create HTTP authenticator module '"
-              << httpAuthenticatorNames[0] << "': " << authenticator.error();
-    }
+  if (flags.authenticate_http) {
+    if (httpAuthenticatorNames[0] == DEFAULT_HTTP_AUTHENTICATOR) {
+      if (credentials.isNone()) {
+        EXIT(1) << "No credentials provided for the default '"
+                << DEFAULT_HTTP_AUTHENTICATOR
+                << "' HTTP authenticator";
+      }
 
-    httpAuthenticator = authenticator.get();
-  } else if (httpAuthenticatorNames[0] != DEFAULT_HTTP_AUTHENTICATOR) {
-    Try<authentication::Authenticator*> module =
-      modules::ModuleManager::create<authentication::Authenticator>(
-          httpAuthenticatorNames[0]);
-    if (module.isError()) {
-      EXIT(1) << "Could not create HTTP authenticator module '"
-              << httpAuthenticatorNames[0] << "': " << module.error();
+      LOG(INFO) << "Using default '" << DEFAULT_HTTP_AUTHENTICATOR
+                << "' HTTP authenticator";
+
+      Try<authentication::Authenticator*> authenticator =
+        BasicAuthenticatorFactory::create(credentials.get());
+      if (authenticator.isError()) {
+        EXIT(1) << "Could not create HTTP authenticator module '"
+                << httpAuthenticatorNames[0] << "': " << authenticator.error();
+      }
+
+      httpAuthenticator = authenticator.get();
+    } else {
+      Try<authentication::Authenticator*> module =
+        modules::ModuleManager::create<authentication::Authenticator>(
+            httpAuthenticatorNames[0]);
+      if (module.isError()) {
+        EXIT(1) << "Could not create HTTP authenticator module '"
+                << httpAuthenticatorNames[0] << "': " << module.error();
+      }
+      LOG(INFO) << "Using '" << httpAuthenticatorNames[0]
+                << "' HTTP authenticator";
+      httpAuthenticator = module.get();
     }
-    LOG(INFO) << "Using '" << httpAuthenticatorNames[0]
-              << "' HTTP authenticator";
-    httpAuthenticator = module.get();
   }
 
   if (httpAuthenticator.isSome() && httpAuthenticator.get() != NULL) {

http://git-wip-us.apache.org/repos/asf/mesos/blob/9f6a2aab/src/tests/master_quota_tests.cpp
----------------------------------------------------------------------
diff --git a/src/tests/master_quota_tests.cpp b/src/tests/master_quota_tests.cpp
index 1bf08ab..776a168 100644
--- a/src/tests/master_quota_tests.cpp
+++ b/src/tests/master_quota_tests.cpp
@@ -1094,14 +1094,14 @@ TEST_F(MasterQuotaTest, NoAuthenticationNoAuthorization)
   TestAllocator<> allocator;
   EXPECT_CALL(allocator, initialize(_, _, _, _));
 
-  // Disable authentication and authorization by providing neither
-  // credentials nor ACLs.
+  // Disable authentication and authorization.
   // TODO(alexr): Setting master `--acls` flag to `ACLs()` or `None()` seems
   // to be semantically equal, however, the test harness currently does not
   // allow `None()`. Once MESOS-4196 is resolved, use `None()` for clarity.
   master::Flags masterFlags = CreateMasterFlags();
-  masterFlags.credentials = None();
   masterFlags.acls = ACLs();
+  masterFlags.authenticate_http = false;
+  masterFlags.credentials = None();
 
   Try<PID<Master>> master = StartMaster(&allocator, masterFlags);
   ASSERT_SOME(master);
@@ -1353,9 +1353,9 @@ TEST_F(MasterQuotaTest, AuthorizeQuotaRequestsWithoutPrincipal)
   acl2->mutable_principals()->set_type(mesos::ACL::Entity::ANY);
   acl2->mutable_quota_principals()->set_type(mesos::ACL::Entity::ANY);
 
-  // Disable authentication by not providing credentials.
   master::Flags masterFlags = CreateMasterFlags();
   masterFlags.acls = acls;
+  masterFlags.authenticate_http = false;
   masterFlags.credentials = None();
 
   Try<PID<Master>> master = StartMaster(&allocator, masterFlags);

http://git-wip-us.apache.org/repos/asf/mesos/blob/9f6a2aab/src/tests/mesos.cpp
----------------------------------------------------------------------
diff --git a/src/tests/mesos.cpp b/src/tests/mesos.cpp
index 4208847..365ebe8 100644
--- a/src/tests/mesos.cpp
+++ b/src/tests/mesos.cpp
@@ -95,6 +95,7 @@ master::Flags MesosTest::CreateMasterFlags()
 
   CHECK_SOME(os::mkdir(flags.work_dir.get()));
 
+  flags.authenticate_http = true;
   flags.authenticate_frameworks = true;
   flags.authenticate_slaves = true;