Skip to content
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

feat: implement single prefix #32

Merged
merged 3 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion .bandit
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
# SPDX-License-Identifier: BSD-3-Clause

assert_used:
skips: ['multiauthenticator/tests/test_*.py']
skips: ['*_test.py', '*test_*.py']
26 changes: 17 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
repos:
# Autoformat: Python code, syntax patterns are modernized
- repo: https://github.com/asottile/pyupgrade
rev: v3.4.0
rev: v3.16.0
hooks:
- id: pyupgrade
args:
- --py38-plus

# Autoformat: Python code
- repo: https://github.com/PyCQA/autoflake
rev: v2.1.1
rev: v2.3.1
hooks:
- id: autoflake
# args ref: https://github.com/PyCQA/autoflake#advanced-usage
Expand All @@ -32,25 +32,25 @@ repos:

# Autoformat: Python code
- repo: https://github.com/pycqa/isort
rev: 5.12.0
rev: 5.13.2
hooks:
- id: isort

# Autoformat: Python code
- repo: https://github.com/psf/black
rev: 23.3.0
rev: 24.4.2
hooks:
- id: black

# Autoformat: markdown, yaml
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.0-alpha.9-for-vscode
rev: v4.0.0-alpha.8
hooks:
- id: prettier

# Misc...
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.6.0
# ref: https://github.com/pre-commit/pre-commit-hooks#hooks-available
hooks:
- id: end-of-file-fixer
Expand All @@ -59,23 +59,31 @@ repos:

# Lint: Python code
- repo: https://github.com/pycqa/flake8
rev: "6.0.0"
rev: "7.1.0"
hooks:
- id: flake8

# Lint: ensure code does not contain vulnerable patterns
- repo: https://github.com/PyCQA/bandit
rev: 1.7.5
rev: 1.7.9
hooks:
- id: bandit
args: [-c, .bandit]

# Ensure project content is properly license and copyrighted
- repo: https://github.com/fsfe/reuse-tool
rev: v2.1.0
rev: v4.0.3
hooks:
- id: reuse

# Follow conventional commits standard
- repo: https://github.com/compilerla/conventional-pre-commit
rev: "v3.3.0"
hooks:
- id: conventional-pre-commit
stages: [commit-msg]
args: []

# pre-commit.ci config reference: https://pre-commit.ci/#configuration
ci:
autoupdate_schedule: monthly
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ more than one authentication option with JupyterHub.

```
$ pip install git+https://github.com/idiap/multiauthenticator
$ pip install jupyter-multiauthenticator
```

## Configuration
Expand All @@ -33,6 +34,9 @@ from oauthenticator.google import GoogleOAuthenticator
from oauthenticator.gitlab import GitLabOAuthenticator
from jupyterhub.auth import PAMAuthenticator

class MyPamAutenticator(PAMAuthenticator):
login_service = "PAM"

c.MultiAuthenticator.authenticators = [
(GitHubOAuthenticator, '/github', {
'client_id': 'XXXX',
Expand All @@ -50,7 +54,7 @@ c.MultiAuthenticator.authenticators = [
"oauth_callback_url": "https://jupyterhub.example.com/hub/gitlab/oauth_callback",
"gitlab_url": "https://gitlab.example.com"
}),
(PAMAuthenticator, "/pam", {"service_name": "PAM"}),
(MyPamAutenticator, "/pam", {}),
]

c.JupyterHub.authenticator_class = 'multiauthenticator.multiauthenticator.MultiAuthenticator'
Expand Down
18 changes: 16 additions & 2 deletions multiauthenticator/multiauthenticator.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from jupyterhub.auth import Authenticator
from jupyterhub.utils import url_path_join
from traitlets import List
from traitlets import Unicode

PREFIX_SEPARATOR = ":"

Expand Down Expand Up @@ -66,6 +67,12 @@ class MultiAuthenticator(Authenticator):
for JupyterHub"""

authenticators = List(help="The subauthenticators to use", config=True)
username_prefix = Unicode(
Copy link
Contributor

Choose a reason for hiding this comment

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

Another option (not better/worse, just another option) is to have this as a Callable(...) which takes the authenticator as a parameter and returns the prefix, with the default being the current behaviour.

The advantage is flexibility since you could have a mix of shared and unique prefixes, the downside is someone has to define a callable instead of a string if they want a common/no prefix c.MultiAuthenticator.username_prefix=lambda a: ""

Copy link
Member Author

Choose a reason for hiding this comment

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

That's an interesting take !

@lahwaacz since you are behind the feature request, I would like to know whether you would prefer @manics suggestion over the current implementation.

help="Prefix to prepend to username",
config=True,
allow_none=True,
default_value=None,
)

def __init__(self, *arg, **kwargs):
super().__init__(*arg, **kwargs)
Expand All @@ -81,7 +88,9 @@ class WrapperAuthenticator(URLScopeMixin, authenticator_klass):

@property
def username_prefix(self):
prefix = f"{getattr(self, 'service_name', self.login_service)}{PREFIX_SEPARATOR}"
prefix = getattr(self, "prefix", None)
if prefix is None:
prefix = f"{getattr(self, 'service_name', self.login_service)}{PREFIX_SEPARATOR}"
return self.normalize_username(prefix)

async def authenticate(self, handler, data=None, **kwargs):
Expand Down Expand Up @@ -116,7 +125,12 @@ def check_blocked_users(self, username, authentication=None):
parent=self, **authenticator_configuration
)

if service_name is not None:
if self.username_prefix is not None:
authenticator.prefix = self.username_prefix
elif service_name is not None:
self.log.warning(
"service_name is deprecated, please create a subclass and set the login_service class variable"
)
if PREFIX_SEPARATOR in service_name:
raise ValueError(f"Service name cannot contain {PREFIX_SEPARATOR}")
authenticator.service_name = service_name
Expand Down
12 changes: 12 additions & 0 deletions multiauthenticator/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Copyright © Idiap Research Institute <[email protected]>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Test Configuration"""
import pytest

from ..multiauthenticator import PREFIX_SEPARATOR


@pytest.fixture(params=[f"test me{PREFIX_SEPARATOR}", f"second{PREFIX_SEPARATOR} test"])
def invalid_name(request):
yield request.param
107 changes: 107 additions & 0 deletions multiauthenticator/tests/test_deprecated.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# Copyright © Idiap Research Institute <[email protected]>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Test module for the deprecated features of the MultiAuthenticator class"""
import pytest

from jupyterhub.auth import PAMAuthenticator
from oauthenticator.gitlab import GitLabOAuthenticator
from oauthenticator.google import GoogleOAuthenticator

from ..multiauthenticator import PREFIX_SEPARATOR
from ..multiauthenticator import MultiAuthenticator


def test_service_name():
gitlab_service_name = "gitlab-service"
google_service_name = "google-service"
authenticators = [
(
GitLabOAuthenticator,
"/gitlab",
{
"service_name": gitlab_service_name,
"client_id": "xxxx",
"client_secret": "xxxx",
"oauth_callback_url": "http://example.com/hub/gitlab/oauth_callback",
},
),
(
GoogleOAuthenticator,
"/google",
{
"service_name": google_service_name,
"client_id": "xxxx",
"client_secret": "xxxx",
"oauth_callback_url": "http://example.com/hub/othergoogle/oauth_callback",
},
),
]
MultiAuthenticator.authenticators = authenticators

multi_authenticator = MultiAuthenticator()

custom_html = multi_authenticator.get_custom_html("http://example.com")

assert f"Sign in with {gitlab_service_name}" in custom_html
assert f"Sign in with {google_service_name}" in custom_html


def test_same_authenticators():
MultiAuthenticator.authenticators = [
(
GoogleOAuthenticator,
"/mygoogle",
{
"service_name": "My Google",
"client_id": "yyyyy",
"client_secret": "yyyyy",
"oauth_callback_url": "http://example.com/hub/mygoogle/oauth_callback",
},
),
(
GoogleOAuthenticator,
"/othergoogle",
{
"service_name": "Other Google",
"client_id": "xxxx",
"client_secret": "xxxx",
"oauth_callback_url": "http://example.com/hub/othergoogle/oauth_callback",
},
),
]

multi_authenticator = MultiAuthenticator()
assert len(multi_authenticator._authenticators) == 2
assert multi_authenticator.get_custom_html("").count("\n") == 13

handlers = multi_authenticator.get_handlers("")
assert len(handlers) == 6
for path, handler in handlers:
assert isinstance(handler.authenticator, GoogleOAuthenticator)
if "mygoogle" in path:
assert handler.authenticator.service_name == "My Google"
elif "othergoogle" in path:
assert handler.authenticator.service_name == "Other Google"
else:
raise ValueError(f"Unknown path: {path}")


def test_username_prefix_validation_with_service_name(invalid_name, caplog):
MultiAuthenticator.authenticators = [
(
PAMAuthenticator,
"/pam",
{"service_name": invalid_name, "allowed_users": {"test"}},
),
]

with pytest.raises(ValueError) as excinfo:
MultiAuthenticator()

assert f"Service name cannot contain {PREFIX_SEPARATOR}" in str(excinfo.value)
assert len(caplog.records) == 1
assert (
caplog.records[0].message
== "service_name is deprecated, please create a subclass and set the login_service class variable"
)
Loading
Loading