diff --git a/pyproject.toml b/pyproject.toml index f8dbd93..6b736b5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ authors = [{name="Yaal Coop", email="contact@yaal.coop"}] maintainers = [{name="Éloi Rivard", email="eloi@yaal.coop"}] dependencies = [ - "authlib>=1.9.1", + "authlib>=1.10.0b1", "babel>=2.14.0", "cachelib>=0.10.0", "flask>=3.1.2", diff --git a/src/auth_playground/__init__.py b/src/auth_playground/__init__.py index 74fe91e..301174f 100644 --- a/src/auth_playground/__init__.py +++ b/src/auth_playground/__init__.py @@ -134,17 +134,9 @@ def setup_oauth(app): client_secret = config.get("client_secret") client_auth_methods = [ClientSecretJWT()] if config["token_endpoint_auth_method"] == KEY_METHOD: - client_key = config["client_key"] - # Authlib 1.9.4 reads a key given as text as an RSA key only. - # TODO: with Authlib 1.10, pass client_key itself. - client_secret = load_key(client_key) + client_secret = load_key(config["client_key"]) client_auth_methods.append( - PrivateKeyJWT( - alg=config["token_endpoint_auth_signing_alg"], - # Authlib 1.9.4 does not put the kid of the key in the header. - # TODO: remove with Authlib 1.10, which does. - headers={"kid": client_key["kid"]}, - ) + PrivateKeyJWT(alg=config["token_endpoint_auth_signing_alg"]) ) registry.register( diff --git a/src/auth_playground/endpoints.py b/src/auth_playground/endpoints.py index 98b3e21..8539429 100644 --- a/src/auth_playground/endpoints.py +++ b/src/auth_playground/endpoints.py @@ -39,8 +39,35 @@ def _get_metadata_document(url: str, timeout: int) -> dict: return metadata +class IssuerMismatchError(Exception): + """The issuer of the server metadata is not the issuer URL entered. + + The issuer is ``None`` when the metadata has none. + """ + + def __init__(self, issuer): + super().__init__(issuer) + self.issuer = issuer + + def fetch_server_metadata(issuer_url: str, timeout: int = 10) -> tuple[dict, str]: - """Fetch server metadata from well-known OIDC or OAuth2 endpoints.""" + """Fetch server metadata from well-known OIDC or OAuth2 endpoints. + + Per OIDC Discovery §4.3 and RFC 8414 §3.3, the issuer of the metadata must + be the issuer URL the well-known URL is built from. ``issuer_url`` has no + trailing slash, and a trailing slash in the issuer is accepted. + """ + metadata, server_type = _fetch_metadata_document(issuer_url, timeout) + issuer = metadata.get("issuer") + if not isinstance(issuer, str): + raise IssuerMismatchError(None) + if issuer.rstrip("/") != issuer_url: + raise IssuerMismatchError(issuer) + return metadata, server_type + + +def _fetch_metadata_document(issuer_url: str, timeout: int) -> tuple[dict, str]: + """Fetch the OIDC metadata document, or else the OAuth2 one.""" oidc_url = f"{issuer_url}/.well-known/openid-configuration" try: return _get_metadata_document(oidc_url, timeout), "oidc" @@ -54,7 +81,17 @@ def fetch_server_metadata(issuer_url: str, timeout: int = 10) -> tuple[dict, str def _flash_metadata_error(exception: Exception) -> None: """Flash user-friendly error messages for metadata loading errors.""" - if isinstance(exception, requests.exceptions.ConnectionError): + if isinstance(exception, IssuerMismatchError) and exception.issuer is None: + flash(_("The server metadata has no issuer."), "error") + elif isinstance(exception, IssuerMismatchError): + flash( + _( + "The issuer of the server metadata is {issuer}, not the URL " + "you entered. A server must not use the issuer of another one." + ).format(issuer=exception.issuer), + "error", + ) + elif isinstance(exception, requests.exceptions.ConnectionError): flash(_("Cannot connect to the server. Please check the URL."), "error") elif isinstance(exception, requests.exceptions.Timeout): flash(_("Connection timeout. The server is not responding."), "error") @@ -108,6 +145,7 @@ def load_server_metadata( if not issuer_url: return None + issuer_url = issuer_url.rstrip("/") try: metadata, server_type = fetch_server_metadata(issuer_url) except Exception as e: @@ -117,7 +155,7 @@ def load_server_metadata( if update_config and g.server_config: g.server_config.metadata = metadata g.server_config.server_type = server_type - g.server_config.issuer_url = issuer_url.rstrip("/") + g.server_config.issuer_url = issuer_url # The client was set up before the metadata, which can change its # signing algorithm. auth_playground.setup_oauth(current_app) diff --git a/src/auth_playground/forms.py b/src/auth_playground/forms.py index adb10a2..7aeeda3 100644 --- a/src/auth_playground/forms.py +++ b/src/auth_playground/forms.py @@ -8,6 +8,7 @@ from flask import current_app from flask import g from flask import render_template +from flask import session from flask import url_for from flask_babel import lazy_gettext as _ from flask_wtforms_htmx import HtmxFlaskForm @@ -34,6 +35,7 @@ from wtforms.validators import Optional from wtforms.widgets import CheckboxInput from wtforms.widgets import ListWidget +from wtforms.widgets import RadioInput from wtforms.widgets import html_params import auth_playground @@ -58,7 +60,19 @@ from auth_playground.client_key import preferred_algorithm from auth_playground.client_key import publish_key from auth_playground.grants import GRANTS +from auth_playground.grants import JWT_BEARER from auth_playground.grants import advertised_grant_types +from auth_playground.jwt_bearer import DEFAULT_LIFETIME +from auth_playground.jwt_bearer import FORM_CLAIMS +from auth_playground.jwt_bearer import KEY_SOURCE +from auth_playground.jwt_bearer import PASTED_SOURCE +from auth_playground.jwt_bearer import SECRET_SOURCE +from auth_playground.jwt_bearer import assertion_alg +from auth_playground.jwt_bearer import available_sources +from auth_playground.jwt_bearer import build_assertion_preview +from auth_playground.jwt_bearer import claims_object +from auth_playground.jwt_bearer import jwt_bearer_preview +from auth_playground.jwt_bearer import pasted_assertion from auth_playground.session import server_metadata from auth_playground.token_request import TOKEN_RESERVED_PARAMS from auth_playground.token_request import client_credentials_preview @@ -69,6 +83,7 @@ "refresh_token", "client_credentials", "password", + JWT_BEARER, ) DEFAULT_REGISTERED_GRANT_TYPES = ["authorization_code", "refresh_token"] @@ -654,17 +669,20 @@ def get_pkce_default(): return "" -class RequestPreviewWidget: - """Render the request that the form builds.""" +class PreviewWidget: + """Render what the form builds, with ``template``.""" + + def __init__(self, template): + self.template = template def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) return Markup( render_template( - "_request_preview.html", + self.template, attributes=Markup(html_params(**kwargs)), label=field.label.text, - request=field.build(field._form), + preview=field.build(field._form), ) ) @@ -672,7 +690,7 @@ def __call__(self, field, **kwargs): class RequestPreviewField(Field): """A read-only preview of the request that ``build(form)`` returns.""" - widget = RequestPreviewWidget() + widget = PreviewWidget("_request_preview.html") def __init__(self, label=None, build=None, **kwargs): super().__init__(label, **kwargs) @@ -694,6 +712,12 @@ def scopes_field(default=None): ) +class AssertionPreviewField(RequestPreviewField): + """A read-only preview of the assertion that ``build(form)`` returns.""" + + widget = PreviewWidget("_assertion_preview.html") + + class RequestParamsForm(BaseForm): """Parameters common to the requests that obtain tokens. @@ -835,6 +859,196 @@ class PasswordForm(RequestParamsForm): request_tokens = ButtonField(_("Request tokens"), render_kw={"class": "primary"}) +class ChoiceRadioInput(RadioInput): + """A radio button that applies the render_kw of its choice.""" + + # WTForms 3.3.2 applies the render_kw of the choices to the options of a + # select, but not to radio buttons. + def __call__(self, field, **kwargs): + return super().__call__(field, **{**field.choice.render_kw, **kwargs}) + + +def assertion_source_choices(): + """Offer the sources of the assertion, and disable those the client lacks.""" + oauth_config = auth_playground.get_oauth_config(current_app) + available = available_sources(oauth_config) + if KEY_SOURCE in available: + key_label = _("Sign with the client key: {alg}").format( + alg=assertion_alg(KEY_SOURCE, oauth_config) + ) + else: + key_label = _("Sign with the client key: this client has none.") + if SECRET_SOURCE in available: + secret_label = _("Sign with the client secret: {alg}").format( + alg=assertion_alg(SECRET_SOURCE, oauth_config) + ) + else: + secret_label = _("Sign with the client secret: this client has none.") + return [ + SelectChoice( + KEY_SOURCE, key_label, render_kw={"disabled": KEY_SOURCE not in available} + ), + SelectChoice( + SECRET_SOURCE, + secret_label, + render_kw={"disabled": SECRET_SOURCE not in available}, + ), + SelectChoice( + PASTED_SOURCE, + _("Paste an assertion issued elsewhere"), + ), + ] + + +def assertion_source_default(): + """Return the first source of the assertion the client can use.""" + return available_sources(auth_playground.get_oauth_config(current_app))[0] + + +def signed_in_subject(): + """Return the sub of the signed-in user, or an empty string.""" + return (session.get("user") or {}).get("sub", "") + + +def configured_client_id(): + """Return the ID of the configured client, or an empty string.""" + return auth_playground.get_oauth_config(current_app).get("client_id", "") + + +def audience_choices(): + """Offer the issuer and the token endpoint as the audience.""" + metadata = server_metadata() + return [ + SelectChoice( + "issuer", _("{url} (issuer)").format(url=metadata.get("issuer", "")) + ), + SelectChoice( + "token_endpoint", + _("{url} (token endpoint)").format(url=metadata.get("token_endpoint", "")), + ), + ] + + +class JwtBearerForm(RequestParamsForm): + """Form to request tokens with a JWT that says who they are for (RFC 7523 §2.1).""" + + endpoint = "oauth.jwt_bearer" + reserved_params = TOKEN_RESERVED_PARAMS | {"assertion"} + + source = RadioField( + _("Assertion:"), + choices=assertion_source_choices, + default=assertion_source_default, + option_widget=ChoiceRadioInput(), + description=_( + "A client gets a key with private_key_jwt, and a secret with the " + "other confidential methods." + ), + ) + assertion = TextAreaField( + _("Assertion (JWT):"), + description=_( + "Sent as is. The playground only decodes it, it does not check " + "the signature." + ), + render_kw={"rows": 5, "autocomplete": "off", "spellcheck": "false"}, + ).triggered_by("source", on="change") + subject = StringField( + _("Subject (sub):"), + default=signed_in_subject, + description=_( + "Who the tokens are for. Filled with the sub of the signed-in user." + ), + render_kw={"autocomplete": "off"}, + ).triggered_by("source", on="change") + issuer = StringField( + _("Issuer (iss):"), + default=configured_client_id, + description=_("The client ID, unless another party issues the assertion."), + ).triggered_by("source", on="change") + audience = SelectField( + _("Audience (aud):"), + choices=audience_choices, + default="issuer", + description=_("Per RFC 10070 §4, both are allowed for a grant."), + ).triggered_by("source", on="change") + lifetime = IntegerField( + _("Lifetime (seconds):"), + default=DEFAULT_LIFETIME, + description=_("From now to exp."), + render_kw={"min": 1}, + ).triggered_by("source", on="change") + extra_claims = TextAreaField( + _("Extra claims:"), + description=_("A JSON object, added to the claims above."), + render_kw={"placeholder": '{"act": {"sub": "admin"}}'}, + ).triggered_by("source", on="change") + scopes = scopes_field(default=get_scopes_default) + preview = RequestPreviewField( + _("Token request"), build=jwt_bearer_preview, wrapper=False + ).triggered_by("*") + assertion_preview = AssertionPreviewField( + _("Assertion"), build=build_assertion_preview, wrapper=False + ).triggered_by("*") + request_tokens = ButtonField(_("Request tokens"), render_kw={"class": "primary"}) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + signing = self.signing() + show_field(self.assertion, not signing) + for field in ( + self.subject, + self.issuer, + self.audience, + self.lifetime, + self.extra_claims, + ): + show_field(field, signing) + + def signing(self): + """Tell whether the playground signs the assertion.""" + return self.source.data != PASTED_SOURCE + + def validate_source(self, field): + oauth_config = auth_playground.get_oauth_config(current_app) + if field.data not in available_sources(oauth_config): + raise ValidationError(_("This client cannot sign the assertion this way.")) + + def validate_assertion(self, field): + if not self.signing() and not pasted_assertion(self): + raise ValidationError(_("Paste the assertion.")) + + def validate_subject(self, field): + if self.signing() and not field.data: + raise ValidationError(_("Enter who the tokens are for.")) + + def validate_issuer(self, field): + if self.signing() and not field.data: + raise ValidationError(_("Enter who issues the assertion.")) + + def validate_lifetime(self, field): + if not self.signing(): + # Like Optional, forget that the hidden value is not a number. + field.errors[:] = [] + return + if field.data is not None and field.data < 1: + raise ValidationError(_("Enter a number of seconds, 1 or more.")) + + def validate_extra_claims(self, field): + if not self.signing() or not field.data: + return + + claims = claims_object(field.data) + if claims is None: + raise ValidationError(_("The extra claims must be a JSON object.")) + if form_claims := [name for name in FORM_CLAIMS if name in claims]: + raise ValidationError( + _("The form already sets these claims: {claims}.").format( + claims=", ".join(form_claims) + ) + ) + + def grant_label(grant): """Mark the label of a deprecated grant type, or one the server does not advertise.""" marks = [] @@ -852,7 +1066,7 @@ def grant_label(grant): def get_grant_choices(): """Group the grant types, and label the ones the server does not advertise.""" return [ - SelectChoice(grant.value, grant_label(grant), optgroup=grant.group) + SelectChoice(grant.name, grant_label(grant), optgroup=grant.group) for grant in GRANTS ] diff --git a/src/auth_playground/grants.py b/src/auth_playground/grants.py index 87eed03..91b30fa 100644 --- a/src/auth_playground/grants.py +++ b/src/auth_playground/grants.py @@ -2,6 +2,7 @@ from dataclasses import dataclass +from authlib.oauth2.rfc7523 import JWTBearerGrant from flask import session from flask_babel import lazy_gettext as _ @@ -10,6 +11,8 @@ # Per RFC 8414 §2, when the server does not publish grant_types_supported. DEFAULT_GRANT_TYPES = ["authorization_code", "implicit"] +JWT_BEARER = JWTBearerGrant.GRANT_TYPE + def advertised_grant_types(): """Return the grant types the server advertises.""" @@ -31,6 +34,13 @@ class Grant: user: bool = True # The user signs in at the provider, which keeps a session for them. provider_session: bool = False + # The name in the playground URLs, for a grant type that is a URN. + short_name: str | None = None + + @property + def name(self): + """Return the name of the grant type in the playground URLs.""" + return self.short_name or self.value @property def advertised(self): @@ -83,9 +93,22 @@ def advertised(self): ), deprecated=True, ), + Grant( + JWT_BEARER, + _("JWT bearer"), + _("Direct"), + _( + "The client sends a signed JWT that says who the tokens are for. " + "The provider checks the signature and the claims, then issues tokens " + "for the subject." + ), + (("RFC 7523 §2.1", "https://www.rfc-editor.org/rfc/rfc7523#section-2.1"),), + short_name="jwt_bearer", + ), ) GRANTS_BY_VALUE = {grant.value: grant for grant in GRANTS} +GRANTS_BY_NAME = {grant.name: grant for grant in GRANTS} def tokens_grant(): @@ -94,6 +117,6 @@ def tokens_grant(): return GRANTS_BY_VALUE.get(grant, GRANTS[0]) -def get_grant(value): - """Return the grant type ``value``, or else the one that obtained the tokens.""" - return GRANTS_BY_VALUE.get(value) or tokens_grant() +def get_grant(name): + """Return the grant type called ``name``, or else the one that obtained the tokens.""" + return GRANTS_BY_NAME.get(name) or tokens_grant() diff --git a/src/auth_playground/jwt_bearer.py b/src/auth_playground/jwt_bearer.py new file mode 100644 index 0000000..2832015 --- /dev/null +++ b/src/auth_playground/jwt_bearer.py @@ -0,0 +1,276 @@ +"""Assertions of the JWT bearer grant (RFC 7523 §2.1).""" + +import json +import math +import time +from dataclasses import dataclass +from dataclasses import field + +from authlib.oauth2.rfc7523 import JWTBearerGrant +from flask import current_app +from flask_babel import format_datetime +from flask_babel import gettext as _ +from joserfc import jws +from joserfc.errors import JoseError +from joserfc.jwk import OctKey + +import auth_playground +from auth_playground.client_key import load_key +from auth_playground.grants import JWT_BEARER +from auth_playground.preview import GENERATED +from auth_playground.preview import NOW +from auth_playground.session import server_metadata +from auth_playground.token_request import signed_header +from auth_playground.token_request import token_preview + +KEY_SOURCE = "key" +SECRET_SOURCE = "secret" +PASTED_SOURCE = "paste" + +# A MAC with the client secret, like client_secret_jwt. +SECRET_ALG = "HS256" + +DEFAULT_LIFETIME = 300 + +# The server metadata the audience can be. +AUDIENCES = ("issuer", "token_endpoint") + +# The claims shown as dates under a decoded assertion. +TIME_CLAIMS = ("iat", "nbf", "exp") + +# The claims the form sets. The extra claims cannot replace them. +FORM_CLAIMS = ("iss", "sub", "aud", "iat", "exp") + + +@dataclass +class AssertionPreview: + """The assertion of the grant, as shown to the user.""" + + note: str + header: str | None = None + claims: str | None = None + dates: list[tuple[str, str]] = field(default_factory=list) + notices: list[tuple[str, str]] = field(default_factory=list) + + +def json_object(text, **kwargs): + """Return the JSON object in ``text``, or ``None`` when it is not one.""" + try: + data = json.loads(text, **kwargs) + except ValueError: + return None + return data if isinstance(data, dict) else None + + +def reject_constant(name): + """Refuse NaN and Infinity, which are not JSON (RFC 8259 §6).""" + raise ValueError(name) + + +def claims_object(text): + """Return the JSON object of claims to sign, or ``None`` when it is not one.""" + return json_object(text, parse_constant=reject_constant) + + +def extra_claims(form): + """Return the extra claims of the form, or an empty dict.""" + return claims_object(form.extra_claims.data or "{}") or {} + + +def audience(form): + """Return the audience the form chose: the issuer or the token endpoint.""" + if form.audience.data not in AUDIENCES: + return "" + return server_metadata().get(form.audience.data, "") + + +def assertion_alg(source, oauth_config): + """Return the algorithm that signs the assertion.""" + if source == SECRET_SOURCE: + return SECRET_ALG + return oauth_config["token_endpoint_auth_signing_alg"] + + +def assertion_header(source, oauth_config): + """Return the header of the assertion the playground signs. + + Like Authlib, it takes the kid of the signing key. + """ + kid = signing_key(source, oauth_config).kid + return signed_header(assertion_alg(source, oauth_config), kid) + + +def signing_key(source, oauth_config): + """Return the key that signs the assertion.""" + if source == SECRET_SOURCE: + return OctKey.import_key(oauth_config["client_secret"]) + return load_key(oauth_config["client_key"]) + + +def sign_assertion(form): + """Sign the assertion the form describes.""" + oauth_config = auth_playground.get_oauth_config(current_app) + source = form.source.data + # Authlib adds the kid of the key. + header = signed_header(assertion_alg(source, oauth_config)) + issued_at = int(time.time()) + return JWTBearerGrant.sign( + signing_key(source, oauth_config), + issuer=form.issuer.data, + audience=audience(form), + subject=form.subject.data, + issued_at=issued_at, + expires_at=issued_at + form.lifetime.data, + claims=extra_claims(form), + header=header, + ) + + +def pasted_assertion(form): + """Return the pasted assertion, without the spaces a copy may add.""" + return "".join((form.assertion.data or "").split()) + + +def decode_assertion(text): + """Return the header and the claims of a JWT, or ``None``. + + The signature is not checked. + """ + try: + token = jws.extract_compact(text.encode()) + except JoseError: + return None + + claims = json_object(token.payload) + if claims is None: + return None + return token.protected, claims + + +def assertion_subject(form): + """Return who the assertion is for, or ``None`` when it does not say.""" + if form.signing(): + return form.subject.data + decoded = decode_assertion(pasted_assertion(form)) + return decoded[1].get("sub") if decoded else None + + +def jwt_bearer_preview(form): + """Return the JWT bearer token request built from the form. + + Like Authlib, it leaves out an empty assertion. + """ + assertion = GENERATED if form.signing() else pasted_assertion(form) + params = [("assertion", assertion)] if assertion else [] + return token_preview(form, JWT_BEARER, params) + + +def build_assertion_preview(form): + """Return the assertion built from the form, or the pasted one, decoded.""" + if not form.signing(): + return pasted_assertion_preview(pasted_assertion(form)) + + oauth_config = auth_playground.get_oauth_config(current_app) + if form.source.data not in available_sources(oauth_config): + return AssertionPreview(_("This client cannot sign the assertion.")) + + header = assertion_header(form.source.data, oauth_config) + claims = {"iss": form.issuer.data or "", "aud": audience(form)} + if form.subject.data: + claims["sub"] = form.subject.data + claims["iat"] = NOW + claims["exp"] = f"[now + {form.lifetime.data or 0} s]" + # In the order Authlib writes them: the extra claims come last. + claims["jti"] = GENERATED + claims.update(extra_claims(form)) + return AssertionPreview( + _("Signed with {alg} when the request is sent").format(alg=header["alg"]), + header=json.dumps(header), + claims=json.dumps(claims, indent=2), + ) + + +def pasted_assertion_preview(text): + """Return the pasted assertion decoded, with what the provider may refuse.""" + note = _("Decoded, the signature is not checked") + if not text: + return AssertionPreview(note) + + decoded = decode_assertion(text) + if decoded is None: + return AssertionPreview( + note, + notices=[ + ( + "warning", + _("This is not a JWT the playground can decode. It is sent as is."), + ) + ], + ) + + header, claims = decoded + dates = {name: format_date(claims.get(name)) for name in TIME_CLAIMS} + return AssertionPreview( + note, + header=json.dumps(header), + claims=json.dumps(claims, indent=2), + dates=[(name, date) for name, date in dates.items() if date], + notices=assertion_notices(claims, dates["exp"]), + ) + + +def format_date(value): + """Return a NumericDate claim as a date, or ``None`` when it is not one.""" + if isinstance(value, bool) or not isinstance(value, int | float): + return None + if not math.isfinite(value): + return None + try: + return format_datetime(value) + except (ValueError, OverflowError, OSError): + return None + + +def assertion_notices(claims, exp_date): + """Return why the provider may refuse the claims of a pasted assertion.""" + notices = [] + if exp_date and claims["exp"] < time.time(): + notices.append( + ( + "warning", + _( + "The assertion expired on {date}. The provider will refuse it." + ).format(date=exp_date), + ) + ) + + metadata = server_metadata() + aud = claims.get("aud") + audiences = { + value + for value in (aud if isinstance(aud, list) else [aud]) + if isinstance(value, str) + } + if audiences & {metadata.get("issuer"), metadata.get("token_endpoint")}: + return notices + + notices.append( + ( + "warning", + _( + "The audience is neither the issuer nor the token endpoint. " + "The provider will likely refuse the assertion." + ), + ) + ) + return notices + + +def available_sources(oauth_config): + """Return the sources of the assertion the client can use.""" + sources = [] + if oauth_config.get("client_key"): + sources.append(KEY_SOURCE) + if oauth_config.get("client_secret"): + sources.append(SECRET_SOURCE) + return [*sources, PASTED_SOURCE] diff --git a/src/auth_playground/oauth.py b/src/auth_playground/oauth.py index 4807845..7fcc036 100644 --- a/src/auth_playground/oauth.py +++ b/src/auth_playground/oauth.py @@ -42,13 +42,18 @@ from auth_playground.forms import AuthorizationParamsForm from auth_playground.forms import ClientCredentialsForm from auth_playground.forms import DynamicRegistrationForm +from auth_playground.forms import JwtBearerForm from auth_playground.forms import LogoutLocalForm from auth_playground.forms import LogoutParamsForm from auth_playground.forms import PasswordForm from auth_playground.forms import RefreshTokenForm from auth_playground.forms import UnregisterClientForm from auth_playground.forms import UserInfoForm +from auth_playground.grants import JWT_BEARER from auth_playground.grants import tokens_grant +from auth_playground.jwt_bearer import assertion_subject +from auth_playground.jwt_bearer import pasted_assertion +from auth_playground.jwt_bearer import sign_assertion from auth_playground.pages import render_tokens_page from auth_playground.session import server_metadata from auth_playground.token_request import extra_token_params @@ -466,11 +471,11 @@ def fetch_tokens(grant_type, form=None, **params): return None -def render_grant_form(grant_type, form): - """Render the request tab again, with the form of ``grant_type``.""" +def render_grant_form(grant, form): + """Render the request tab again, with the form of the grant type called ``grant``.""" if "csrf_token" in form.errors: flash(_("Invalid request"), "error") - return render_tokens_page("request", grant=grant_type, grant_form=form) + return render_tokens_page("request", grant=grant, grant_form=form) @bp.route("/token/client-credentials", methods=["POST"]) @@ -519,15 +524,55 @@ def password(): forget_tokens() store_token(token, "password", requested_scope=scope or None) + sign_in_user(claims, form.username.data) + return redirect(url_for("routes.tokens", tab="current")) + + +@bp.route("/token/jwt-bearer", methods=["POST"]) +@server_config_needed +def jwt_bearer(): + """Request tokens with a JWT that says who they are for.""" + form = JwtBearerForm() + if not form.validate_on_submit(): + return render_grant_form("jwt_bearer", form) + + if not form.signing(): + assertion = pasted_assertion(form) + else: + try: + assertion = sign_assertion(form) + except (JoseError, ValueError) as exc: + flash( + _("The assertion could not be signed: {error}").format(error=exc), + "error", + ) + return render_grant_form("jwt_bearer", form) + + scope = requested_scope(form) + token = fetch_tokens(JWT_BEARER, form, assertion=assertion, scope=scope) + if token is None: + return render_grant_form("jwt_bearer", form) + + claims, reason = read_id_token(token) + if reason: + flash(_("The tokens are not kept. {reason}").format(reason=reason), "error") + return render_grant_form("jwt_bearer", form) + + forget_tokens() + store_token(token, JWT_BEARER, requested_scope=scope or None) + sign_in_user(claims, assertion_subject(form)) + return redirect(url_for("routes.tokens", tab="current")) + + +def sign_in_user(claims, subject): + """Sign in the user of the ID token, or else say who the tokens are for.""" session["user"] = claims if claims: flash(_("You have been successfully logged in."), "success") + elif subject: + flash(_("Tokens obtained for {subject}.").format(subject=subject), "success") else: - flash( - _("Tokens obtained for {username}.").format(username=form.username.data), - "success", - ) - return redirect(url_for("routes.tokens", tab="current")) + flash(_("Tokens obtained."), "success") def read_id_token(token): @@ -535,7 +580,7 @@ def read_id_token(token): When the reason is ``None``, the token can be kept. The claims are then ``None`` if the token has no ID token. - No nonce is checked. The password grant sends none, and neither does an + No nonce is checked. The direct grant types send none, and neither does an authorization request without the openid scope. Per OIDC Core §12.2, a refreshed ID token should have none, and Authlib does not compare it with the original ID token. @@ -727,13 +772,19 @@ def refresh(): def bearer_token(): - """Return the access token alone, to send it to the provider as it is. + """Return the access token to send to the provider as it is. With an expiry date or a refresh token, Authlib could refuse the token - before sending it, or refresh it without the playground knowing. + before sending it, or refresh it without the playground knowing. The ID + token claims let Authlib check the UserInfo sub (OIDC Core §5.3.2). """ token = session.get("token", {}) - return {key: token[key] for key in ("access_token", "token_type") if token.get(key)} + bearer = { + key: token[key] for key in ("access_token", "token_type") if token.get(key) + } + if session.get("user"): + bearer["userinfo"] = session["user"] + return bearer @bp.route("/userinfo", methods=["POST"]) @@ -766,6 +817,8 @@ def userinfo(): error = _("The response is not JSON.") except requests.RequestException as exc: error = get_response_error(exc) or www_authenticate(exc) or exc + except (JoseError, RuntimeError, KeyError) as exc: + error = _("The signed response is not valid: {error}").format(error=exc) except (TypeError, ValueError): error = _("The response is not a JSON object.") else: diff --git a/src/auth_playground/pages.py b/src/auth_playground/pages.py index 8c0212b..cb819e4 100644 --- a/src/auth_playground/pages.py +++ b/src/auth_playground/pages.py @@ -11,6 +11,7 @@ from auth_playground.forms import AuthorizationParamsForm from auth_playground.forms import ClientCredentialsForm from auth_playground.forms import GrantForm +from auth_playground.forms import JwtBearerForm from auth_playground.forms import LogoutLocalForm from auth_playground.forms import LogoutParamsForm from auth_playground.forms import PasswordForm @@ -24,13 +25,14 @@ "authorization_code": AuthorizationParamsForm, "client_credentials": ClientCredentialsForm, "password": PasswordForm, + "jwt_bearer": JwtBearerForm, } def render_tokens_page(tab, grant=None, grant_form=None): """Render a tab of the tokens page. - The grant type comes from ``grant``, or else from the query string. + The grant type is called ``grant``, or else is in the query string. """ oauth_config = auth_playground.get_oauth_config(current_app) logout_params_form = LogoutParamsForm( @@ -46,8 +48,8 @@ def render_tokens_page(tab, grant=None, grant_form=None): grant_forms = {} if tab == "request": grant_forms = { - "grant_selector": GrantForm(data={"grant": grant.value}), - "grant_form": grant_form or GRANT_FORMS[grant.value](), + "grant_selector": GrantForm(data={"grant": grant.name}), + "grant_form": grant_form or GRANT_FORMS[grant.name](), } return render_template( diff --git a/src/auth_playground/templates/_assertion_preview.html b/src/auth_playground/templates/_assertion_preview.html new file mode 100644 index 0000000..8e5b111 --- /dev/null +++ b/src/auth_playground/templates/_assertion_preview.html @@ -0,0 +1,18 @@ +
+
{{ label }} {{ preview.note }}
+ {% for type, message in preview.notices %} +
{{ message }}
+ {% endfor %} + {% if preview.claims %} +
{% trans %}Header{% endtrans %}
+{{ preview.header }}
+
+{% trans %}Claims{% endtrans %}
+{{ preview.claims }}
+{%- if preview.dates %}
+
+{% trans %}Dates{% endtrans %}
+{% for name, date in preview.dates %}{{ name }}: {{ date }}
+{% endfor %}{% endif %}
+ {% endif %} +
diff --git a/src/auth_playground/templates/_grant_jwt_bearer.html b/src/auth_playground/templates/_grant_jwt_bearer.html new file mode 100644 index 0000000..eca58b8 --- /dev/null +++ b/src/auth_playground/templates/_grant_jwt_bearer.html @@ -0,0 +1,32 @@ +{% from "_form.html" import render_form %} +{% call render_form(grant_form, url_for('oauth.jwt_bearer'), id="jwt-bearer-form") %} +
+
+ {% trans %}Assertion{% endtrans %} + {{ grant_form.source() }} + {{ grant_form.assertion() }} + {{ grant_form.subject() }} + {{ grant_form.issuer() }} + {{ grant_form.audience() }} + {{ grant_form.lifetime() }} + {{ grant_form.extra_claims() }} +
+
+ {% trans %}Request{% endtrans %} + {% if grant_form.scopes.choices %} + {{ grant_form.scopes() }} + {% endif %} + {{ grant_form.other_scopes() }} +
+
+ {% trans %}Advanced{% endtrans %} + {{ grant_form.extra_params() }} +
+
+ + {{ grant_form.preview() }} + + {{ grant_form.assertion_preview() }} + + {{ grant_form.request_tokens() }} +{% endcall %} diff --git a/src/auth_playground/templates/_grant_panel.html b/src/auth_playground/templates/_grant_panel.html index a20bf94..470cb61 100644 --- a/src/auth_playground/templates/_grant_panel.html +++ b/src/auth_playground/templates/_grant_panel.html @@ -28,5 +28,5 @@ {% endif %} - {% include "_grant_" ~ grant.value ~ ".html" %} + {% include "_grant_" ~ grant.name ~ ".html" %} diff --git a/src/auth_playground/templates/_request_preview.html b/src/auth_playground/templates/_request_preview.html index c73e25f..62926b4 100644 --- a/src/auth_playground/templates/_request_preview.html +++ b/src/auth_playground/templates/_request_preview.html @@ -1,12 +1,12 @@
{{ label }}
-
{{ request.lines()|join("\n") }}
- {% if request.assertion %} +
{{ preview.lines()|join("\n") }}
+ {% if preview.assertion %}

{% trans %}Client assertion{% endtrans %} {% trans %}Signed when the request is sent{% endtrans %}

{% trans %}Header{% endtrans %}
-{{ request.assertion.header }}
+{{ preview.assertion.header }}
 
 {% trans %}Claims{% endtrans %}
-{{ request.assertion.claims }}
+{{ preview.assertion.claims }} {% endif %}
diff --git a/src/auth_playground/token_request.py b/src/auth_playground/token_request.py index f97187d..d13d55f 100644 --- a/src/auth_playground/token_request.py +++ b/src/auth_playground/token_request.py @@ -53,6 +53,17 @@ def client_auth_preview(method, client_id): return [], [("client_id", client_id)] +def signed_header(alg, kid=None): + """Return the header of a JWT the playground signs. + + It is in the order joserfc writes it. + """ + header = {"typ": "JWT", "alg": alg} + if kid: + header["kid"] = kid + return header + + def client_assertion_preview(oauth_config, token_endpoint): """Return the header and the claims of the client assertion, or ``None``. @@ -62,13 +73,12 @@ def client_assertion_preview(oauth_config, token_endpoint): if method not in JWT_METHODS: return None - header = {"alg": "HS256", "typ": "JWT"} + header = signed_header("HS256") if method == KEY_METHOD: - header = { - "alg": oauth_config["token_endpoint_auth_signing_alg"], - "kid": oauth_config["client_key"]["kid"], - "typ": "JWT", - } + header = signed_header( + oauth_config["token_endpoint_auth_signing_alg"], + oauth_config["client_key"]["kid"], + ) client_id = oauth_config.get("client_id", "") claims = { "iss": client_id, diff --git a/src/auth_playground/translations/messages.pot b/src/auth_playground/translations/messages.pot index 0327e23..887ef65 100644 --- a/src/auth_playground/translations/messages.pot +++ b/src/auth_playground/translations/messages.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2026-11-12 15:40+0100\n" +"POT-Creation-Date: 2026-11-12 17:53+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -17,7 +17,7 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.18.0\n" -#: src/auth_playground/__init__.py:281 +#: src/auth_playground/__init__.py:273 #, python-format msgid "This request should be sent to %(server_name)s" msgstr "" @@ -56,515 +56,694 @@ msgstr "" msgid "This is not an RSA, EC or Ed25519 key in PEM format." msgstr "" -#: src/auth_playground/endpoints.py:58 +#: src/auth_playground/endpoints.py:85 +msgid "The server metadata has no issuer." +msgstr "" + +#: src/auth_playground/endpoints.py:89 +#, python-brace-format +msgid "" +"The issuer of the server metadata is {issuer}, not the URL you entered. A" +" server must not use the issuer of another one." +msgstr "" + +#: src/auth_playground/endpoints.py:95 msgid "Cannot connect to the server. Please check the URL." msgstr "" -#: src/auth_playground/endpoints.py:60 +#: src/auth_playground/endpoints.py:97 msgid "Connection timeout. The server is not responding." msgstr "" -#: src/auth_playground/endpoints.py:65 +#: src/auth_playground/endpoints.py:102 msgid "" "This server does not support OIDC Discovery or OAuth 2.0 Authorization " "Server Metadata" msgstr "" -#: src/auth_playground/endpoints.py:71 +#: src/auth_playground/endpoints.py:108 #, python-brace-format msgid "Server returned an error: HTTP {status_code}" msgstr "" -#: src/auth_playground/endpoints.py:77 +#: src/auth_playground/endpoints.py:114 msgid "Invalid response from server" msgstr "" -#: src/auth_playground/endpoints.py:79 +#: src/auth_playground/endpoints.py:116 msgid "Failed to connect to the server. Please check the URL." msgstr "" -#: src/auth_playground/endpoints.py:82 +#: src/auth_playground/endpoints.py:119 msgid "Cannot load the server metadata." msgstr "" -#: src/auth_playground/endpoints.py:179 +#: src/auth_playground/endpoints.py:217 msgid "Server metadata successfully loaded" msgstr "" -#: src/auth_playground/endpoints.py:199 src/auth_playground/oauth.py:136 -#: src/auth_playground/oauth.py:295 src/auth_playground/oauth.py:369 -#: src/auth_playground/oauth.py:472 src/auth_playground/oauth.py:611 -#: src/auth_playground/oauth.py:696 src/auth_playground/oauth.py:745 +#: src/auth_playground/endpoints.py:237 src/auth_playground/oauth.py:141 +#: src/auth_playground/oauth.py:300 src/auth_playground/oauth.py:374 +#: src/auth_playground/oauth.py:477 src/auth_playground/oauth.py:656 +#: src/auth_playground/oauth.py:741 src/auth_playground/oauth.py:796 msgid "Invalid request" msgstr "" -#: src/auth_playground/endpoints.py:206 +#: src/auth_playground/endpoints.py:244 msgid "You can now configure a different identity provider" msgstr "" -#: src/auth_playground/endpoints.py:256 +#: src/auth_playground/endpoints.py:294 msgid "OAuth configuration completed successfully" msgstr "" -#: src/auth_playground/endpoints.py:292 +#: src/auth_playground/endpoints.py:330 msgid "No server configured" msgstr "" -#: src/auth_playground/forms.py:144 src/auth_playground/forms.py:155 +#: src/auth_playground/forms.py:159 src/auth_playground/forms.py:170 msgid "Default" msgstr "" -#: src/auth_playground/forms.py:145 +#: src/auth_playground/forms.py:160 msgid "None - No UI" msgstr "" -#: src/auth_playground/forms.py:146 +#: src/auth_playground/forms.py:161 msgid "Login - Authentication page" msgstr "" -#: src/auth_playground/forms.py:147 +#: src/auth_playground/forms.py:162 msgid "Consent - Consent page" msgstr "" -#: src/auth_playground/forms.py:148 +#: src/auth_playground/forms.py:163 msgid "Select account - Account selection page" msgstr "" -#: src/auth_playground/forms.py:149 +#: src/auth_playground/forms.py:164 msgid "Create - Registration page" msgstr "" -#: src/auth_playground/forms.py:183 +#: src/auth_playground/forms.py:198 msgid "Renew tokens" msgstr "" -#: src/auth_playground/forms.py:189 +#: src/auth_playground/forms.py:204 msgid "Get user info" msgstr "" -#: src/auth_playground/forms.py:205 +#: src/auth_playground/forms.py:220 msgid "URL must start with http:// or https://" msgstr "" -#: src/auth_playground/forms.py:218 +#: src/auth_playground/forms.py:233 msgid "" "HTTP is only allowed for localhost or in debug/testing mode. Use HTTPS in" " production." msgstr "" -#: src/auth_playground/forms.py:227 +#: src/auth_playground/forms.py:242 msgid "Provider URL:" msgstr "" -#: src/auth_playground/forms.py:229 +#: src/auth_playground/forms.py:244 msgid "Provider URL is required" msgstr "" -#: src/auth_playground/forms.py:238 +#: src/auth_playground/forms.py:253 msgid "Continue" msgstr "" -#: src/auth_playground/forms.py:245 +#: src/auth_playground/forms.py:260 #, python-brace-format msgid "{value} (not advertised)" msgstr "" -#: src/auth_playground/forms.py:345 +#: src/auth_playground/forms.py:360 msgid "Client key:" msgstr "" -#: src/auth_playground/forms.py:347 +#: src/auth_playground/forms.py:362 msgid "Generate a key" msgstr "" -#: src/auth_playground/forms.py:348 +#: src/auth_playground/forms.py:363 msgid "Import a key" msgstr "" -#: src/auth_playground/forms.py:352 +#: src/auth_playground/forms.py:367 msgid "The client signs its token requests with this key." msgstr "" -#: src/auth_playground/forms.py:355 +#: src/auth_playground/forms.py:370 msgid "Private key:" msgstr "" -#: src/auth_playground/forms.py:358 +#: src/auth_playground/forms.py:373 msgid "PEM or JWK: RSA, EC or Ed25519. Kept in your session, never shown again." msgstr "" -#: src/auth_playground/forms.py:368 +#: src/auth_playground/forms.py:383 msgid "Key ID (kid):" msgstr "" -#: src/auth_playground/forms.py:371 +#: src/auth_playground/forms.py:386 msgid "" "Sent in the assertion header. Leave empty to use the key thumbprint (RFC " "7638)." msgstr "" -#: src/auth_playground/forms.py:376 +#: src/auth_playground/forms.py:391 msgid "Signing algorithm:" msgstr "" -#: src/auth_playground/forms.py:379 +#: src/auth_playground/forms.py:394 msgid "From token_endpoint_auth_signing_alg_values_supported." msgstr "" -#: src/auth_playground/forms.py:382 +#: src/auth_playground/forms.py:397 msgid "Generate another key" msgstr "" -#: src/auth_playground/forms.py:469 +#: src/auth_playground/forms.py:484 msgid "Paste the private key of the client." msgstr "" -#: src/auth_playground/forms.py:480 src/auth_playground/forms.py:878 +#: src/auth_playground/forms.py:495 src/auth_playground/forms.py:1092 #: src/auth_playground/templates/configure_client.html:43 msgid "Client ID:" msgstr "" -#: src/auth_playground/forms.py:482 +#: src/auth_playground/forms.py:497 msgid "Client ID is required" msgstr "" -#: src/auth_playground/forms.py:486 +#: src/auth_playground/forms.py:501 msgid "Client ID must be between 1 and 255 characters" msgstr "" -#: src/auth_playground/forms.py:492 src/auth_playground/forms.py:550 +#: src/auth_playground/forms.py:507 src/auth_playground/forms.py:565 msgid "Token endpoint authentication:" msgstr "" -#: src/auth_playground/forms.py:495 +#: src/auth_playground/forms.py:510 msgid "How the client proves its identity to the token endpoint." msgstr "" -#: src/auth_playground/forms.py:498 +#: src/auth_playground/forms.py:513 msgid "Client secret:" msgstr "" -#: src/auth_playground/forms.py:499 +#: src/auth_playground/forms.py:514 msgid "Leave empty for a public client." msgstr "" -#: src/auth_playground/forms.py:510 +#: src/auth_playground/forms.py:525 msgid "Complete configuration" msgstr "" -#: src/auth_playground/forms.py:528 +#: src/auth_playground/forms.py:543 msgid "This authentication method needs a client secret." msgstr "" -#: src/auth_playground/forms.py:534 +#: src/auth_playground/forms.py:549 msgid "A public client has no secret. Leave the secret empty." msgstr "" -#: src/auth_playground/forms.py:542 +#: src/auth_playground/forms.py:557 msgid "Client type:" msgstr "" -#: src/auth_playground/forms.py:544 +#: src/auth_playground/forms.py:559 msgid "Confidential, with a secret or a key" msgstr "" -#: src/auth_playground/forms.py:545 +#: src/auth_playground/forms.py:560 msgid "Public, without a secret, with PKCE" msgstr "" -#: src/auth_playground/forms.py:553 +#: src/auth_playground/forms.py:568 msgid "A public client uses none." msgstr "" -#: src/auth_playground/forms.py:566 +#: src/auth_playground/forms.py:581 msgid "Public key sent to the provider:" msgstr "" -#: src/auth_playground/forms.py:568 +#: src/auth_playground/forms.py:583 msgid "jwks: the key goes in the registration request" msgstr "" -#: src/auth_playground/forms.py:572 +#: src/auth_playground/forms.py:587 msgid "" "jwks_uri: the provider downloads the key from the playground, which must " "be reachable from the provider" msgstr "" -#: src/auth_playground/forms.py:581 +#: src/auth_playground/forms.py:596 msgid "Grant types to register:" msgstr "" -#: src/auth_playground/forms.py:588 +#: src/auth_playground/forms.py:603 msgid "Initial access token:" msgstr "" -#: src/auth_playground/forms.py:591 +#: src/auth_playground/forms.py:606 msgid "Leave empty if not required" msgstr "" -#: src/auth_playground/forms.py:595 +#: src/auth_playground/forms.py:610 msgid "Register client" msgstr "" -#: src/auth_playground/forms.py:612 +#: src/auth_playground/forms.py:627 msgid "Choose at least one grant type." msgstr "" -#: src/auth_playground/forms.py:618 +#: src/auth_playground/forms.py:633 msgid "Change provider" msgstr "" -#: src/auth_playground/forms.py:624 +#: src/auth_playground/forms.py:639 msgid "Unregister client" msgstr "" -#: src/auth_playground/forms.py:630 +#: src/auth_playground/forms.py:645 msgid "Log out" msgstr "" -#: src/auth_playground/forms.py:637 +#: src/auth_playground/forms.py:652 msgid "Disabled" msgstr "" -#: src/auth_playground/forms.py:688 +#: src/auth_playground/forms.py:706 msgid "Scopes:" msgstr "" -#: src/auth_playground/forms.py:691 +#: src/auth_playground/forms.py:709 msgid "Select the scopes to request from the authorization server" msgstr "" -#: src/auth_playground/forms.py:710 +#: src/auth_playground/forms.py:734 msgid "Other scopes:" msgstr "" -#: src/auth_playground/forms.py:711 +#: src/auth_playground/forms.py:735 msgid "Space-separated, sent as they are." msgstr "" -#: src/auth_playground/forms.py:714 +#: src/auth_playground/forms.py:738 msgid "Extra parameters:" msgstr "" -#: src/auth_playground/forms.py:715 +#: src/auth_playground/forms.py:739 msgid "One name=value per line, added to the request as they are." msgstr "" -#: src/auth_playground/forms.py:728 +#: src/auth_playground/forms.py:752 #, python-brace-format msgid "" "Each line must be name=value, with a parameter the playground does not " "set itself: {errors}" msgstr "" -#: src/auth_playground/forms.py:740 +#: src/auth_playground/forms.py:764 #: src/auth_playground/templates/_tokens.html:14 msgid "PKCE:" msgstr "" -#: src/auth_playground/forms.py:744 +#: src/auth_playground/forms.py:768 msgid "Sends a code_challenge here, and the code_verifier with the token request." msgstr "" -#: src/auth_playground/forms.py:749 +#: src/auth_playground/forms.py:773 msgid "Prompt:" msgstr "" -#: src/auth_playground/forms.py:751 +#: src/auth_playground/forms.py:775 msgid "Control the authentication UI behavior" msgstr "" -#: src/auth_playground/forms.py:754 src/auth_playground/forms.py:890 +#: src/auth_playground/forms.py:778 src/auth_playground/forms.py:1104 msgid "UI Locale:" msgstr "" -#: src/auth_playground/forms.py:757 +#: src/auth_playground/forms.py:781 msgid "Preferred language for the authentication UI" msgstr "" -#: src/auth_playground/forms.py:760 +#: src/auth_playground/forms.py:784 msgid "Max age (seconds):" msgstr "" -#: src/auth_playground/forms.py:763 +#: src/auth_playground/forms.py:787 msgid "" "Maximum authentication age. 0 forces re-authentication and refreshes " "auth_time." msgstr "" -#: src/auth_playground/forms.py:768 +#: src/auth_playground/forms.py:792 msgid "ACR values:" msgstr "" -#: src/auth_playground/forms.py:770 +#: src/auth_playground/forms.py:794 msgid "" "Requested authentication context classes, space-separated (step-up " "authentication)." msgstr "" -#: src/auth_playground/forms.py:774 +#: src/auth_playground/forms.py:798 msgid "Login hint:" msgstr "" -#: src/auth_playground/forms.py:775 +#: src/auth_playground/forms.py:799 msgid "Identifier to pre-fill on the provider's login screen." msgstr "" -#: src/auth_playground/forms.py:778 +#: src/auth_playground/forms.py:802 msgid "Claims (JSON):" msgstr "" -#: src/auth_playground/forms.py:780 +#: src/auth_playground/forms.py:804 msgid "Specific claims to request, as an OIDC claims JSON object (advanced)." msgstr "" -#: src/auth_playground/forms.py:784 +#: src/auth_playground/forms.py:808 msgid "Authorization request" msgstr "" -#: src/auth_playground/forms.py:786 +#: src/auth_playground/forms.py:810 msgid "Sign in" msgstr "" -#: src/auth_playground/forms.py:798 +#: src/auth_playground/forms.py:822 msgid "Claims must be a JSON object." msgstr "" -#: src/auth_playground/forms.py:809 src/auth_playground/forms.py:833 +#: src/auth_playground/forms.py:833 src/auth_playground/forms.py:857 +#: src/auth_playground/forms.py:988 msgid "Token request" msgstr "" -#: src/auth_playground/forms.py:811 src/auth_playground/forms.py:835 +#: src/auth_playground/forms.py:835 src/auth_playground/forms.py:859 +#: src/auth_playground/forms.py:993 msgid "Request tokens" msgstr "" -#: src/auth_playground/forms.py:821 +#: src/auth_playground/forms.py:845 msgid "Username:" msgstr "" -#: src/auth_playground/forms.py:826 +#: src/auth_playground/forms.py:850 msgid "Password:" msgstr "" -#: src/auth_playground/forms.py:842 +#: src/auth_playground/forms.py:876 +#, python-brace-format +msgid "Sign with the client key: {alg}" +msgstr "" + +#: src/auth_playground/forms.py:880 +msgid "Sign with the client key: this client has none." +msgstr "" + +#: src/auth_playground/forms.py:882 +#, python-brace-format +msgid "Sign with the client secret: {alg}" +msgstr "" + +#: src/auth_playground/forms.py:886 +msgid "Sign with the client secret: this client has none." +msgstr "" + +#: src/auth_playground/forms.py:898 +msgid "Paste an assertion issued elsewhere" +msgstr "" + +#: src/auth_playground/forms.py:923 +#, python-brace-format +msgid "{url} (issuer)" +msgstr "" + +#: src/auth_playground/forms.py:927 +#, python-brace-format +msgid "{url} (token endpoint)" +msgstr "" + +#: src/auth_playground/forms.py:939 +msgid "Assertion:" +msgstr "" + +#: src/auth_playground/forms.py:944 +msgid "" +"A client gets a key with private_key_jwt, and a secret with the other " +"confidential methods." +msgstr "" + +#: src/auth_playground/forms.py:949 +msgid "Assertion (JWT):" +msgstr "" + +#: src/auth_playground/forms.py:951 +msgid "" +"Sent as is. The playground only decodes it, it does not check the " +"signature." +msgstr "" + +#: src/auth_playground/forms.py:957 +msgid "Subject (sub):" +msgstr "" + +#: src/auth_playground/forms.py:960 +msgid "Who the tokens are for. Filled with the sub of the signed-in user." +msgstr "" + +#: src/auth_playground/forms.py:965 +msgid "Issuer (iss):" +msgstr "" + +#: src/auth_playground/forms.py:967 +msgid "The client ID, unless another party issues the assertion." +msgstr "" + +#: src/auth_playground/forms.py:970 +msgid "Audience (aud):" +msgstr "" + +#: src/auth_playground/forms.py:973 +msgid "Per RFC 10070 §4, both are allowed for a grant." +msgstr "" + +#: src/auth_playground/forms.py:976 +msgid "Lifetime (seconds):" +msgstr "" + +#: src/auth_playground/forms.py:978 +msgid "From now to exp." +msgstr "" + +#: src/auth_playground/forms.py:982 +msgid "Extra claims:" +msgstr "" + +#: src/auth_playground/forms.py:983 +msgid "A JSON object, added to the claims above." +msgstr "" + +#: src/auth_playground/forms.py:991 +#: src/auth_playground/templates/_grant_jwt_bearer.html:5 +msgid "Assertion" +msgstr "" + +#: src/auth_playground/forms.py:1015 +msgid "This client cannot sign the assertion this way." +msgstr "" + +#: src/auth_playground/forms.py:1019 +msgid "Paste the assertion." +msgstr "" + +#: src/auth_playground/forms.py:1023 +msgid "Enter who the tokens are for." +msgstr "" + +#: src/auth_playground/forms.py:1027 +msgid "Enter who issues the assertion." +msgstr "" + +#: src/auth_playground/forms.py:1035 +msgid "Enter a number of seconds, 1 or more." +msgstr "" + +#: src/auth_playground/forms.py:1043 +msgid "The extra claims must be a JSON object." +msgstr "" + +#: src/auth_playground/forms.py:1046 +#, python-brace-format +msgid "The form already sets these claims: {claims}." +msgstr "" + +#: src/auth_playground/forms.py:1056 msgid "deprecated" msgstr "" -#: src/auth_playground/forms.py:844 +#: src/auth_playground/forms.py:1058 msgid "not advertised" msgstr "" -#: src/auth_playground/forms.py:847 +#: src/auth_playground/forms.py:1061 #, python-brace-format msgid "{label} ({marks})" msgstr "" -#: src/auth_playground/forms.py:866 +#: src/auth_playground/forms.py:1080 #: src/auth_playground/templates/_tokens.html:6 msgid "Grant type:" msgstr "" -#: src/auth_playground/forms.py:867 +#: src/auth_playground/forms.py:1081 msgid "Choose" msgstr "" -#: src/auth_playground/forms.py:874 +#: src/auth_playground/forms.py:1088 msgid "ID Token Hint:" msgstr "" -#: src/auth_playground/forms.py:875 +#: src/auth_playground/forms.py:1089 msgid "ID Token previously issued, used to identify the user session" msgstr "" -#: src/auth_playground/forms.py:879 +#: src/auth_playground/forms.py:1093 msgid "OAuth client identifier" msgstr "" -#: src/auth_playground/forms.py:882 +#: src/auth_playground/forms.py:1096 msgid "Post-Logout Redirect URI:" msgstr "" -#: src/auth_playground/forms.py:883 +#: src/auth_playground/forms.py:1097 msgid "URI to redirect to after logout" msgstr "" -#: src/auth_playground/forms.py:886 +#: src/auth_playground/forms.py:1100 msgid "Logout Hint:" msgstr "" -#: src/auth_playground/forms.py:887 +#: src/auth_playground/forms.py:1101 msgid "Hint about the user to log out" msgstr "" -#: src/auth_playground/forms.py:892 +#: src/auth_playground/forms.py:1106 msgid "Preferred language for the logout UI" msgstr "" -#: src/auth_playground/forms.py:894 +#: src/auth_playground/forms.py:1108 msgid "Server log out" msgstr "" -#: src/auth_playground/grants.py:44 +#: src/auth_playground/grants.py:54 msgid "Authorization code" msgstr "" -#: src/auth_playground/grants.py:45 +#: src/auth_playground/grants.py:55 msgid "Redirect" msgstr "" -#: src/auth_playground/grants.py:47 +#: src/auth_playground/grants.py:57 msgid "" "The user signs in at the provider, which redirects back with a code. The " "playground then exchanges the code for tokens at the token endpoint. " "Signing in again updates auth_time, acr and amr." msgstr "" -#: src/auth_playground/grants.py:62 +#: src/auth_playground/grants.py:72 msgid "Client credentials" msgstr "" -#: src/auth_playground/grants.py:63 src/auth_playground/grants.py:75 +#: src/auth_playground/grants.py:73 src/auth_playground/grants.py:85 +#: src/auth_playground/grants.py:99 msgid "Direct" msgstr "" -#: src/auth_playground/grants.py:65 +#: src/auth_playground/grants.py:75 msgid "" "The client gets tokens for itself, without any user. The playground sends" " its credentials to the token endpoint." msgstr "" -#: src/auth_playground/grants.py:74 +#: src/auth_playground/grants.py:84 msgid "Password (ROPC)" msgstr "" -#: src/auth_playground/grants.py:77 +#: src/auth_playground/grants.py:87 msgid "" "The client asks the user for their username and password, and sends them " "to the token endpoint. The provider never sees the user sign in." msgstr "" -#: src/auth_playground/oauth.py:141 +#: src/auth_playground/grants.py:98 +msgid "JWT bearer" +msgstr "" + +#: src/auth_playground/grants.py:101 +msgid "" +"The client sends a signed JWT that says who the tokens are for. The " +"provider checks the signature and the claims, then issues tokens for the " +"subject." +msgstr "" + +#: src/auth_playground/jwt_bearer.py:175 +msgid "This client cannot sign the assertion." +msgstr "" + +#: src/auth_playground/jwt_bearer.py:187 +#, python-brace-format +msgid "Signed with {alg} when the request is sent" +msgstr "" + +#: src/auth_playground/jwt_bearer.py:195 +msgid "Decoded, the signature is not checked" +msgstr "" + +#: src/auth_playground/jwt_bearer.py:206 +msgid "This is not a JWT the playground can decode. It is sent as is." +msgstr "" + +#: src/auth_playground/jwt_bearer.py:242 +#, python-brace-format +msgid "The assertion expired on {date}. The provider will refuse it." +msgstr "" + +#: src/auth_playground/jwt_bearer.py:261 +msgid "" +"The audience is neither the issuer nor the token endpoint. The provider " +"will likely refuse the assertion." +msgstr "" + +#: src/auth_playground/oauth.py:146 msgid "Dynamic client registration not supported" msgstr "" -#: src/auth_playground/oauth.py:197 +#: src/auth_playground/oauth.py:202 msgid "Invalid JSON response from registration endpoint" msgstr "" -#: src/auth_playground/oauth.py:203 +#: src/auth_playground/oauth.py:208 #, python-brace-format msgid "Dynamic client registration failed: {error}" msgstr "" -#: src/auth_playground/oauth.py:207 +#: src/auth_playground/oauth.py:212 msgid "Dynamic client registration failed" msgstr "" -#: src/auth_playground/oauth.py:211 +#: src/auth_playground/oauth.py:216 msgid "Invalid response from registration endpoint" msgstr "" -#: src/auth_playground/oauth.py:218 +#: src/auth_playground/oauth.py:223 #, python-brace-format msgid "" "The server registered the client with the {auth_method} authentication " @@ -572,7 +751,7 @@ msgid "" "registered on the server." msgstr "" -#: src/auth_playground/oauth.py:230 +#: src/auth_playground/oauth.py:235 #, python-brace-format msgid "" "The server registered the client without a client secret, but its " @@ -580,145 +759,160 @@ msgid "" "registered on the server." msgstr "" -#: src/auth_playground/oauth.py:241 +#: src/auth_playground/oauth.py:246 msgid "" "The server registered the client with the private_key_jwt authentication " "method, but the playground has no key for it. The client is still " "registered on the server." msgstr "" -#: src/auth_playground/oauth.py:256 +#: src/auth_playground/oauth.py:261 #, python-brace-format msgid "" "The server registered the client with the {alg} signing algorithm, which " "its key cannot use. The client is still registered on the server." msgstr "" -#: src/auth_playground/oauth.py:282 +#: src/auth_playground/oauth.py:287 msgid "Client successfully registered!" msgstr "" -#: src/auth_playground/oauth.py:302 +#: src/auth_playground/oauth.py:307 msgid "Client registration management credentials not found" msgstr "" -#: src/auth_playground/oauth.py:316 +#: src/auth_playground/oauth.py:321 #, python-brace-format msgid "Client unregistration failed: {error}" msgstr "" -#: src/auth_playground/oauth.py:320 +#: src/auth_playground/oauth.py:325 msgid "Client unregistration failed" msgstr "" -#: src/auth_playground/oauth.py:328 +#: src/auth_playground/oauth.py:333 msgid "Client successfully unregistered" msgstr "" -#: src/auth_playground/oauth.py:450 +#: src/auth_playground/oauth.py:455 msgid "The provider has no token endpoint." msgstr "" -#: src/auth_playground/oauth.py:461 +#: src/auth_playground/oauth.py:466 #, python-brace-format msgid "The token request failed: {error}" msgstr "" -#: src/auth_playground/oauth.py:492 +#: src/auth_playground/oauth.py:497 msgid "The client obtained tokens." msgstr "" -#: src/auth_playground/oauth.py:517 src/auth_playground/oauth.py:591 +#: src/auth_playground/oauth.py:522 src/auth_playground/oauth.py:558 +#: src/auth_playground/oauth.py:636 #, python-brace-format msgid "The tokens are not kept. {reason}" msgstr "" -#: src/auth_playground/oauth.py:524 src/auth_playground/oauth.py:602 +#: src/auth_playground/oauth.py:546 +#, python-brace-format +msgid "The assertion could not be signed: {error}" +msgstr "" + +#: src/auth_playground/oauth.py:571 src/auth_playground/oauth.py:647 msgid "You have been successfully logged in." msgstr "" -#: src/auth_playground/oauth.py:527 +#: src/auth_playground/oauth.py:573 #, python-brace-format -msgid "Tokens obtained for {username}." +msgid "Tokens obtained for {subject}." msgstr "" -#: src/auth_playground/oauth.py:547 +#: src/auth_playground/oauth.py:575 +msgid "Tokens obtained." +msgstr "" + +#: src/auth_playground/oauth.py:592 #, python-brace-format msgid "The signing keys of the provider could not be fetched: {error}" msgstr "" -#: src/auth_playground/oauth.py:550 src/auth_playground/oauth.py:564 +#: src/auth_playground/oauth.py:595 src/auth_playground/oauth.py:609 #, python-brace-format msgid "The ID token is not valid: {error}" msgstr "" -#: src/auth_playground/oauth.py:577 +#: src/auth_playground/oauth.py:622 #, python-brace-format msgid "An error happened during login: {error}" msgstr "" -#: src/auth_playground/oauth.py:615 +#: src/auth_playground/oauth.py:660 msgid "The tokens were forgotten" msgstr "" -#: src/auth_playground/oauth.py:617 +#: src/auth_playground/oauth.py:662 msgid "You have been logged out" msgstr "" -#: src/auth_playground/oauth.py:671 +#: src/auth_playground/oauth.py:716 #, python-brace-format msgid "The logout response is not valid: {error}." msgstr "" -#: src/auth_playground/oauth.py:678 +#: src/auth_playground/oauth.py:723 #, python-brace-format msgid "The logout response is not valid: {error}. You are still logged in here." msgstr "" -#: src/auth_playground/oauth.py:686 +#: src/auth_playground/oauth.py:731 msgid "You have been logged out from the server" msgstr "" -#: src/auth_playground/oauth.py:701 +#: src/auth_playground/oauth.py:746 msgid "No refresh token available" msgstr "" -#: src/auth_playground/oauth.py:715 +#: src/auth_playground/oauth.py:760 #, python-brace-format msgid "" "The refresh response is rejected and the previous tokens are kept. If the" " provider rotates refresh tokens, sign in again. {reason}" msgstr "" -#: src/auth_playground/oauth.py:725 +#: src/auth_playground/oauth.py:770 msgid "Token successfully refreshed" msgstr "" -#: src/auth_playground/oauth.py:749 +#: src/auth_playground/oauth.py:800 msgid "No access token available" msgstr "" -#: src/auth_playground/oauth.py:753 +#: src/auth_playground/oauth.py:804 msgid "These tokens are not tied to a user." msgstr "" -#: src/auth_playground/oauth.py:758 +#: src/auth_playground/oauth.py:809 msgid "The provider has no UserInfo endpoint." msgstr "" -#: src/auth_playground/oauth.py:766 +#: src/auth_playground/oauth.py:817 msgid "The response is not JSON." msgstr "" -#: src/auth_playground/oauth.py:770 +#: src/auth_playground/oauth.py:821 +#, python-brace-format +msgid "The signed response is not valid: {error}" +msgstr "" + +#: src/auth_playground/oauth.py:823 msgid "The response is not a JSON object." msgstr "" -#: src/auth_playground/oauth.py:777 +#: src/auth_playground/oauth.py:830 msgid "User info received" msgstr "" -#: src/auth_playground/oauth.py:781 +#: src/auth_playground/oauth.py:834 #, python-brace-format msgid "An error happened during the UserInfo request: {error}" msgstr "" @@ -803,6 +997,20 @@ msgstr "" msgid "Tokens obtained" msgstr "" +#: src/auth_playground/templates/_assertion_preview.html:7 +#: src/auth_playground/templates/_request_preview.html:6 +msgid "Header" +msgstr "" + +#: src/auth_playground/templates/_assertion_preview.html:10 +#: src/auth_playground/templates/_request_preview.html:9 +msgid "Claims" +msgstr "" + +#: src/auth_playground/templates/_assertion_preview.html:14 +msgid "Dates" +msgstr "" + #: src/auth_playground/templates/_client_key_preview.html:4 msgid "Sent in the registration request" msgstr "" @@ -840,6 +1048,7 @@ msgstr "" #: src/auth_playground/templates/_grant_authorization_code.html:5 #: src/auth_playground/templates/_grant_client_credentials.html:5 +#: src/auth_playground/templates/_grant_jwt_bearer.html:15 #: src/auth_playground/templates/_grant_password.html:10 #: src/auth_playground/templates/tokens.html:8 msgid "Request" @@ -851,6 +1060,7 @@ msgstr "" #: src/auth_playground/templates/_grant_authorization_code.html:23 #: src/auth_playground/templates/_grant_client_credentials.html:12 +#: src/auth_playground/templates/_grant_jwt_bearer.html:22 #: src/auth_playground/templates/_grant_password.html:17 msgid "Advanced" msgstr "" @@ -891,14 +1101,6 @@ msgstr "" msgid "Signed when the request is sent" msgstr "" -#: src/auth_playground/templates/_request_preview.html:6 -msgid "Header" -msgstr "" - -#: src/auth_playground/templates/_request_preview.html:9 -msgid "Claims" -msgstr "" - #: src/auth_playground/templates/_server_tabs.html:4 msgid "Specifications" msgstr "" diff --git a/tests/test_authentication.py b/tests/test_authentication.py index e80af71..6f8215b 100644 --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -41,7 +41,7 @@ def test_login_flow_fast(iam_server, iam_client, user, test_client): assert res.status_code == 302 res = iam_server.test_client.get(res.location) - assert res.status_code == 302 + assert res.status_code == 303 res = test_client.get(res.location) assert res.status_code == 302 diff --git a/tests/test_client_auth_and_pkce.py b/tests/test_client_auth_and_pkce.py index aee7e1f..914bc33 100644 --- a/tests/test_client_auth_and_pkce.py +++ b/tests/test_client_auth_and_pkce.py @@ -402,6 +402,7 @@ def test_invalid_manual_form_keeps_the_registration_form(unconfigured_testapp): True, False, False, + False, ] diff --git a/tests/test_client_credentials.py b/tests/test_client_credentials.py index 2390601..1799387 100644 --- a/tests/test_client_credentials.py +++ b/tests/test_client_credentials.py @@ -273,8 +273,8 @@ def test_grant_defaults_to_the_grant_of_the_last_tokens(unconfigured_testapp): def test_every_grant_has_a_form_and_a_template(app): """Test each grant type of the selector can be rendered.""" for grant in GRANTS: - assert grant.value in GRANT_FORMS - app.jinja_env.get_template(f"_grant_{grant.value}.html") + assert grant.name in GRANT_FORMS + app.jinja_env.get_template(f"_grant_{grant.name}.html") @pytest.mark.usefixtures("provider_metadata") diff --git a/tests/test_configuration.py b/tests/test_configuration.py index a672a69..5d9a145 100644 --- a/tests/test_configuration.py +++ b/tests/test_configuration.py @@ -429,6 +429,28 @@ def test_reloading_the_same_provider_keeps_the_client(unconfigured_test_client): assert sess["oauth_config"]["client_id"] == "c" +def test_provider_with_another_issuer(unconfigured_test_client): + """Test a provider whose metadata gives another issuer is refused.""" + with patch("requests.get") as mock_get: + mock_get.return_value.json.return_value = { + "issuer": "https://other.example.com" + } + res = unconfigured_test_client.get("/en/server/test.example.com") + + assert "The issuer of the server metadata is https://other.example.com" in res.text + with unconfigured_test_client.session_transaction() as sess: + assert "server_metadata" not in sess + + +def test_provider_without_issuer(unconfigured_test_client): + """Test a provider whose metadata has no issuer is refused.""" + with patch("requests.get") as mock_get: + mock_get.return_value.json.return_value = {} + res = unconfigured_test_client.get("/en/server/test.example.com") + + assert "The server metadata has no issuer." in res.text + + def test_failed_provider_load_keeps_the_page(unconfigured_test_client): """Test the provider page renders when loading another issuer fails.""" with unconfigured_test_client.session_transaction() as sess: diff --git a/tests/test_endpoints_errors.py b/tests/test_endpoints_errors.py index 274bae9..6d7ef89 100644 --- a/tests/test_endpoints_errors.py +++ b/tests/test_endpoints_errors.py @@ -4,6 +4,7 @@ import pytest import requests +from auth_playground.endpoints import IssuerMismatchError from auth_playground.endpoints import fetch_server_metadata @@ -38,6 +39,30 @@ def test_fetch_server_metadata_rejects_non_object_documents(document): fetch_server_metadata("https://test.example.com") +@pytest.mark.parametrize( + "issuer", ["https://other.example.com", "https://test.example.com/tenant", None] +) +def test_fetch_server_metadata_rejects_another_issuer(issuer): + """Test the issuer of the metadata must be the URL it was fetched from.""" + with patch("requests.get") as mock_get: + mock_get.return_value.json.return_value = {"issuer": issuer} + + with pytest.raises(IssuerMismatchError): + fetch_server_metadata("https://test.example.com") + + +def test_fetch_server_metadata_accepts_a_trailing_slash(): + """Test an issuer with a trailing slash matches the URL without one.""" + with patch("requests.get") as mock_get: + mock_get.return_value.json.return_value = { + "issuer": "https://test.example.com/" + } + + metadata, _ = fetch_server_metadata("https://test.example.com") + + assert metadata["issuer"] == "https://test.example.com/" + + def test_fetch_server_metadata_raises_non_404_errors(): """Test fetch_server_metadata raises non-404 HTTP errors.""" with patch("requests.get") as mock_get: diff --git a/tests/test_jwt_bearer.py b/tests/test_jwt_bearer.py new file mode 100644 index 0000000..6f7e51f --- /dev/null +++ b/tests/test_jwt_bearer.py @@ -0,0 +1,504 @@ +import base64 +import json +import time +from unittest.mock import patch + +import pytest +import requests +from joserfc import jwt +from joserfc.errors import InvalidClaimError +from joserfc.errors import JoseError +from joserfc.jwk import OctKey + +from auth_playground.client_key import generate_key +from auth_playground.client_key import load_key +from auth_playground.grants import JWT_BEARER +from tests.fake_provider import server_session + +SECRET = "a client secret that is long enough" + +FETCH = "auth_playground.oauth_client.PlaygroundOAuth2App.fetch_access_token" +TOKEN = {"access_token": "a", "token_type": "Bearer"} + + +def unsigned_jwt(claims, header=None): + """Return a JWT with the claims, signed with a throwaway key.""" + return jwt.encode( + header or {"alg": "HS256"}, claims, OctKey.import_key("throwaway key " * 4) + ) + + +@pytest.fixture +def secret_client(unconfigured_testapp, provider_metadata): + """Configure a client that has a secret.""" + server_session( + unconfigured_testapp, {"client_id": "client", "client_secret": SECRET} + ) + return unconfigured_testapp + + +@pytest.fixture +def client_key(): + """Return a generated client key.""" + return generate_key("ES256") + + +@pytest.fixture +def key_client(unconfigured_testapp, provider_metadata, client_key): + """Configure a private_key_jwt client.""" + server_session( + unconfigured_testapp, + { + "client_id": "client", + "token_endpoint_auth_method": "private_key_jwt", + "client_key": client_key, + "token_endpoint_auth_signing_alg": "ES256", + }, + ) + return unconfigured_testapp + + +def jwt_bearer_form(testapp): + """Return the JWT bearer form of the tokens page.""" + return testapp.get("/en/tokens/request?grant=jwt_bearer").forms["jwt-bearer-form"] + + +def request_tokens(testapp, token=None, **fields): + """Fill the JWT bearer form, submit it, and return the response and the call.""" + form = jwt_bearer_form(testapp) + for name, value in fields.items(): + form[name] = value + with patch(FETCH, return_value=token or TOKEN) as fetch: + res = form.submit("request_tokens") + return res, fetch + + +def test_secret_client_signs_the_assertion_with_its_secret(secret_client): + """Test the assertion is a JWT signed with the client secret.""" + res, fetch = request_tokens( + secret_client, + subject="jane", + lifetime="120", + extra_claims='{"act": {"sub": "admin"}}', + other_scopes="api:read", + ) + + kwargs = fetch.call_args.kwargs + assert kwargs["grant_type"] == JWT_BEARER + assert kwargs["scope"].endswith("api:read") + token = jwt.decode(kwargs["assertion"], OctKey.import_key(SECRET)) + assert token.header == {"typ": "JWT", "alg": "HS256"} + assert token.claims["iss"] == "client" + assert token.claims["sub"] == "jane" + assert token.claims["aud"] == "https://test.example.com" + assert token.claims["exp"] - token.claims["iat"] == 120 + assert token.claims["act"] == {"sub": "admin"} + assert token.claims["jti"] + + res = res.follow() + assert "Tokens obtained for jane." in res.text + assert "forget-tokens-form" in res.forms + with secret_client.session_transaction() as sess: + assert sess["token_info"]["grant"] == JWT_BEARER + + +def test_key_client_signs_the_assertion_with_its_key(key_client, client_key): + """Test the assertion is signed with the client key, and carries its kid.""" + _res, fetch = request_tokens(key_client, subject="jane", audience="token_endpoint") + + assertion = fetch.call_args.kwargs["assertion"] + token = jwt.decode(assertion, load_key(client_key)) + assert token.header == {"typ": "JWT", "alg": "ES256", "kid": client_key["kid"]} + assert token.claims["aud"] == "https://test.example.com/oauth/token" + + +def test_the_key_is_the_default_source(key_client, client_key): + """Test a client with a key signs with it, and cannot use a secret.""" + form = jwt_bearer_form(key_client) + + assert form["source"].value == "key" + res = key_client.get("/en/tokens/request?grant=jwt_bearer") + assert "Sign with the client key: ES256" in res.text + assert "Sign with the client secret: this client has none." in res.text + assert '"kid": "' + client_key["kid"] in res.text.replace(""", '"') + + +def test_a_public_client_pastes_the_assertion(unconfigured_testapp, provider_metadata): + """Test a client without a secret or a key can only paste an assertion.""" + server_session(unconfigured_testapp, {"client_id": "client"}) + res = unconfigured_testapp.get("/en/tokens/request?grant=jwt_bearer") + + assert res.forms["jwt-bearer-form"]["source"].value == "paste" + assert 'disabled id="source-0"' in res.text + assert 'disabled id="source-1"' in res.text + assert 'id="wrap-subject" hidden' in res.text + assert 'id="wrap-assertion" hidden' not in res.text + + +def test_the_subject_is_the_signed_in_user(secret_client): + """Test the subject is filled with the sub of the signed-in user.""" + with secret_client.session_transaction() as sess: + sess["user"] = {"sub": "jane"} + + assert jwt_bearer_form(secret_client)["subject"].value == "jane" + + +def test_the_subject_is_required(secret_client): + """Test the playground does not sign an assertion for nobody.""" + res, fetch = request_tokens(secret_client, subject="") + + assert "Enter who the tokens are for." in res.text + fetch.assert_not_called() + + +@pytest.mark.parametrize("extra_claims", ["[1]", "{", '{"exp": NaN}']) +def test_the_extra_claims_must_be_an_object(secret_client, extra_claims): + """Test the extra claims are a JSON object.""" + res, fetch = request_tokens( + secret_client, subject="jane", extra_claims=extra_claims + ) + + assert "The extra claims must be a JSON object." in res.text + fetch.assert_not_called() + + +def test_the_extra_claims_cannot_replace_the_form_claims(secret_client): + """Test the extra claims cannot replace the claims the form sets.""" + res, fetch = request_tokens( + secret_client, + subject="jane", + extra_claims='{"sub": "bob", "exp": 1, "jti": "j"}', + ) + + assert "The form already sets these claims: sub, exp." in res.text + fetch.assert_not_called() + + +def test_the_assertion_cannot_be_an_extra_param(secret_client): + """Test the extra parameters cannot override the assertion.""" + res, fetch = request_tokens( + secret_client, subject="jane", extra_params="assertion=x" + ) + + assert "does not set itself: assertion" in res.text + fetch.assert_not_called() + + +def test_a_client_without_a_key_cannot_sign_with_it(secret_client): + """Test the source of the assertion must be one the client has.""" + res = secret_client.post( + "/token/jwt-bearer", + { + "csrf_token": jwt_bearer_form(secret_client)["csrf_token"].value, + "source": "key", + "subject": "jane", + "issuer": "client", + "audience": "issuer", + "lifetime": "300", + }, + ) + + assert "This client cannot sign the assertion this way." in res.text + + +def test_the_pasted_assertion_is_sent_as_is(secret_client): + """Test the pasted assertion is sent without the spaces of the copy.""" + assertion = unsigned_jwt({"sub": "jane", "aud": "https://test.example.com"}) + res, fetch = request_tokens( + secret_client, source="paste", assertion=f" {assertion[:20]}\n{assertion[20:]}" + ) + + assert fetch.call_args.kwargs["assertion"] == assertion + assert "Tokens obtained for jane." in res.follow().text + + +@pytest.mark.parametrize("assertion", ["", " \n "]) +def test_a_pasted_assertion_must_be_given(secret_client, assertion): + """Test the pasted assertion is required.""" + res, fetch = request_tokens( + secret_client, source="paste", subject="", assertion=assertion + ) + + assert "Paste the assertion." in res.text + fetch.assert_not_called() + + +def test_tokens_for_an_unknown_subject(secret_client): + """Test the tokens are kept when the assertion does not say who they are for.""" + res, _fetch = request_tokens(secret_client, source="paste", assertion="opaque") + + assert "Tokens obtained." in res.follow().text + + +def test_the_id_token_signs_the_user_in(secret_client): + """Test the user of the ID token is signed in.""" + with patch( + "auth_playground.oauth_client.PlaygroundOAuth2App.parse_id_token", + return_value={"sub": "jane"}, + ): + res, _fetch = request_tokens( + secret_client, token={**TOKEN, "id_token": "i"}, subject="jane" + ) + + res = res.follow() + assert "You have been successfully logged in." in res.text + assert "Signed in as jane" in res.text + + +def test_an_invalid_id_token_rejects_the_tokens(secret_client): + """Test the tokens are not kept when the ID token is not valid.""" + with patch( + "auth_playground.oauth_client.PlaygroundOAuth2App.parse_id_token", + side_effect=InvalidClaimError("iss"), + ): + res, _fetch = request_tokens( + secret_client, token={**TOKEN, "id_token": "i"}, subject="jane" + ) + + assert "The tokens are not kept. The ID token is not valid:" in res.text + assert "jwt-bearer-form" in res.forms + with secret_client.session_transaction() as sess: + assert "token" not in sess + + +def test_a_signing_failure_is_shown(secret_client): + """Test the form is shown again when the assertion cannot be signed.""" + with patch( + "auth_playground.oauth.sign_assertion", side_effect=JoseError("bad key") + ): + res, fetch = request_tokens(secret_client, subject="jane") + + assert "The assertion could not be signed:" in res.text + assert "bad key" in res.text + fetch.assert_not_called() + + +def test_a_refused_request_is_shown(secret_client): + """Test the form is shown again when the token request fails.""" + form = jwt_bearer_form(secret_client) + form["subject"] = "jane" + with patch(FETCH, side_effect=requests.ConnectionError("Connection refused")): + res = form.submit("request_tokens") + + assert "The token request failed: Connection refused" in res.text + assert res.forms["jwt-bearer-form"]["subject"].value == "jane" + + +def preview(testapp, **data): + """Return the assertion preview rendered by htmx for the form data.""" + form = jwt_bearer_form(testapp) + res = testapp.post( + "/token/jwt-bearer", + { + "csrf_token": form["csrf_token"].value, + "issuer": "client", + "audience": "issuer", + "lifetime": "300", + **data, + }, + headers={ + "HX-Request": "true", + "HX-Source": "article#assertion_preview", + "HX-Target": "article#assertion_preview", + }, + ) + assert "