Skip to content

Refactor AuthContext creation into standalone AuthContextMiddleware. #6131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 5, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions tensorboard/backend/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,14 @@ py_library(
srcs_version = "PY3",
visibility = ["//visibility:public"],
deps = [
":auth_context",
":client_feature_flags",
":empty_path_redirect",
":experiment_id",
":experimental_plugin",
":http_util",
":path_prefix",
":security_validator",
"//tensorboard:auth",
"//tensorboard:context",
"//tensorboard:errors",
"//tensorboard:plugin_util",
"//tensorboard/plugins/core:core_plugin",
Expand All @@ -88,6 +87,31 @@ py_test(
],
)

py_library(
name = "auth_context",
srcs = ["auth_context.py"],
srcs_version = "PY3",
deps = [
"//tensorboard:auth",
"//tensorboard:context",
],
)

py_test(
name = "auth_context_test",
size = "small",
srcs = ["auth_context_test.py"],
srcs_version = "PY3",
tags = ["support_notf"],
deps = [
":auth_context",
"//tensorboard:auth",
"//tensorboard:context",
"//tensorboard:test",
"@org_pocoo_werkzeug",
],
)

py_library(
name = "empty_path_redirect",
srcs = ["empty_path_redirect.py"],
Expand Down
16 changes: 2 additions & 14 deletions tensorboard/backend/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@

from tensorboard import errors
from tensorboard import plugin_util
from tensorboard import auth
from tensorboard import context
from tensorboard.backend import auth_context
from tensorboard.backend import client_feature_flags
from tensorboard.backend import empty_path_redirect
from tensorboard.backend import experiment_id
Expand Down Expand Up @@ -326,7 +325,7 @@ def _create_wsgi_app(self):
app = self._route_request
for middleware in self._extra_middlewares:
app = middleware(app)
app = _auth_context_middleware(app, self._auth_providers)
app = auth_context.AuthContextMiddleware(app, self._auth_providers)
app = client_feature_flags.ClientFeatureFlagsMiddleware(app)
app = empty_path_redirect.EmptyPathRedirectMiddleware(app)
app = experiment_id.ExperimentIdMiddleware(app)
Expand Down Expand Up @@ -582,17 +581,6 @@ def wrapper(environ, start_response):
return wrapper


def _auth_context_middleware(wsgi_app, auth_providers):
def wrapper(environ, start_response):
environ = dict(environ)
auth_ctx = auth.AuthContext(auth_providers, environ)
ctx = context.from_environ(environ).replace(auth=auth_ctx)
context.set_in_environ(environ, ctx)
return wsgi_app(environ, start_response)

return wrapper


def _clean_path(path):
"""Removes a trailing slash from a non-root path.

Expand Down
38 changes: 38 additions & 0 deletions tensorboard/backend/auth_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
#
# Licensed 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.
# ==============================================================================
from tensorboard import auth
from tensorboard import context


class AuthContextMiddleware:
"""WSGI middleware to inject an AuthContext into the RequestContext."""

def __init__(self, application, auth_providers):
"""Initializes this middleware.

Args:
application: A WSGI application to delegate to.
auth_providers: The auth_providers to provide to the AuthContext.
"""
self._application = application
self._auth_providers = auth_providers

def __call__(self, environ, start_response):
"""Invoke this WSGI application."""
environ = dict(environ)
auth_ctx = auth.AuthContext(self._auth_providers, environ)
ctx = context.from_environ(environ).replace(auth=auth_ctx)
context.set_in_environ(environ, ctx)
return self._application(environ, start_response)
73 changes: 73 additions & 0 deletions tensorboard/backend/auth_context_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
#
# Licensed 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.
# ==============================================================================
"""Tests for `tensorboard.backend.auth_context`."""
from werkzeug import test as werkzeug_test
from werkzeug import wrappers

from tensorboard import auth
from tensorboard import context
from tensorboard import test as tb_test
from tensorboard.backend import auth_context


class SimpleAuthProvider(auth.AuthProvider):
"""Simple AuthProvider that returns the value it is initialized with."""

def __init__(self, credential):
self._credential = credential

def authenticate(self, environ):
return self._credential


def _create_auth_provider_verifier_app(expected_auth_key):
"""Generates a WSGI application for verifying AuthContextMiddleware.

It should be placed downstream from the AuthContextMiddleware. It will
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I wasn't sure of what this "downstream" terminology meant. For some reason I was imagining the opposite of what you're doing in the test below, although perhaps that doesn't make much sense.

This is just for this test/file, so it doesn't matter much, but consider whether a different phrasing or a 2-line example would be worth adding.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just tried to reword since adding an example just duplicates the code below. Since the WSGI PEP (https://peps.python.org/pep-0333/) makes a passing reference to the "Chain of Responsibility" pattern, I reworded in those terms.

generate a credential using the AuthContext and the given key.

Args:
expected_auth_key: The auth key to be used for invoking the AuthContext.
This key should correspond to the auth_providers used to configure
the AuthContextMiddleware .
"""

def _app(environ, start_response):
ctx = context.from_environ(environ)
credential = ctx.auth.get(expected_auth_key)
start_response("200 OK", [("Content-Type", "text\plain")])
return f"credential: {credential}"

return _app


class AuthContextMiddlewareTest(tb_test.TestCase):
"""Tests for `AuthContextMiddleware`"""

def test_populates_auth_context(self):
app = auth_context.AuthContextMiddleware(
_create_auth_provider_verifier_app("my_key"),
{"my_key": SimpleAuthProvider("my_credential")},
)

server = werkzeug_test.Client(app, wrappers.Response)
response = server.get("")
self.assertEqual(
"credential: my_credential", response.get_data().decode()
)


if __name__ == "__main__":
tb_test.main()