diff --git a/charmcraft.yaml b/charmcraft.yaml index dd810f38..eeddf800 100644 --- a/charmcraft.yaml +++ b/charmcraft.yaml @@ -135,6 +135,7 @@ config: description: | Enforce users to set up and use multi factor authentication. Disabling this option will allow users to log in with password or webauthn without completing 2fa. + This option is ignored when multitenancy is enabled in the login UI (`byosso_enabled`). type: boolean default: True enable_verification: @@ -142,6 +143,7 @@ config: Enable and enforce users to verify their accounts. Enabling this option will make users verify their accounts after registration or on the next login. This option requires an SMTP server integration. + This option must be enabled when multitenancy is enabled in the login UI (`byosso_enabled`). type: boolean default: False sender_email: @@ -163,6 +165,7 @@ config: description: | Enforce setting up a WebAuthn key (e.g. with YubiKey or Google Password Manager on Android) after signing in with an external identity provider. Requires `enable_passwordless_login_method=False`. + This option must be disabled when multitenancy is enabled in the login UI (`byosso_enabled`). WARNING: Do not enable this option unless you are sure that this feature applies to your deployment. type: boolean default: False diff --git a/lib/charms/identity_platform_login_ui_operator/v0/login_ui_endpoints.py b/lib/charms/identity_platform_login_ui_operator/v0/login_ui_endpoints.py index ab3371c7..1cc5849d 100644 --- a/lib/charms/identity_platform_login_ui_operator/v0/login_ui_endpoints.py +++ b/lib/charms/identity_platform_login_ui_operator/v0/login_ui_endpoints.py @@ -54,7 +54,7 @@ def some_event_function(): # Increment this PATCH version before using `charmcraft publish-lib` or reset # to 0 if you are raising the major API version -LIBPATCH = 5 +LIBPATCH = 6 RELATION_NAME = "ui-endpoint-info" INTERFACE_NAME = "login_ui_endpoints" @@ -74,6 +74,8 @@ class LoginUIProviderData(BaseModel): webauthn_settings_url: Optional[str] = None account_linking_settings_url: Optional[str] = None verification_url: Optional[str] = None + # "true" when the login UI runs "Bring Your Own SSO" and decides itself when MFA is required. + byosso_enabled: Optional[str] = None class LoginUIEndpointsRelationReadyEvent(EventBase): diff --git a/lib/charms/kratos/v0/kratos_info.py b/lib/charms/kratos/v0/kratos_info.py index 384fe531..125973ff 100644 --- a/lib/charms/kratos/v0/kratos_info.py +++ b/lib/charms/kratos/v0/kratos_info.py @@ -54,7 +54,7 @@ def some_event_function(): # Increment this PATCH version before using `charmcraft publish-lib` or reset # to 0 if you are raising the major API version -LIBPATCH = 6 +LIBPATCH = 7 RELATION_NAME = "kratos-info" INTERFACE_NAME = "kratos_info" @@ -100,6 +100,7 @@ def send_info_relation_data( oidc_webauthn_sequencing_enabled: bool, verification_enabled: bool, feature_flags: Optional[list[str]] = None, + privileged_session_max_age: Optional[str] = None, ) -> None: """Updates relation with endpoints, config and configmaps info.""" if not self._charm.unit.is_leader(): @@ -123,6 +124,8 @@ def send_info_relation_data( if feature_flags: info_databag["feature_flags"] = ",".join(feature_flags) + if privileged_session_max_age: + info_databag["privileged_session_max_age"] = privileged_session_max_age for relation in relations: relation.data[self._charm.app].update(info_databag) diff --git a/src/charm.py b/src/charm.py index f55dab6b..fe082979 100755 --- a/src/charm.py +++ b/src/charm.py @@ -127,6 +127,7 @@ LOGIN_WEBHOOK_INTEGRATION_NAME, PEBBLE_READY_CHECK_NAME, PEER_INTEGRATION_NAME, + PRIVILEGED_SESSION_MAX_AGE, PROMETHEUS_SCRAPE_INTEGRATION_NAME, PUBLIC_ROUTE_INTEGRATION_NAME, REGISTRATION_WEBHOOK_INTEGRATION_NAME, @@ -169,6 +170,7 @@ dict_to_action_output, external_hostname_is_ready, migration_is_ready, + multitenancy_config_is_valid, passwordless_config_is_valid, peer_integration_exists, public_route_is_ready, @@ -422,6 +424,7 @@ def __init__(self, *args: Any) -> None: @property def _pebble_layer(self) -> Layer: return self._pebble_service.render_pebble_layer( + LoginUIEndpointData.load(self.login_ui_requirer), self.charm_config, self.secrets, DatabaseConfig.load(self.database_requirer), @@ -568,6 +571,14 @@ def _on_collect_status(self, event: CollectStatusEvent) -> None: ) ) + if not multitenancy_config_is_valid(self): + event.add_status( + BlockedStatus( + "Multitenancy requires `enable_verification=True` and " + "`enable_oidc_webauthn_sequencing=False`" + ) + ) + event.add_status(self.resources_patch.get_status()) if can_connect and self._workload_service.is_failing(): @@ -670,6 +681,10 @@ def _on_resource_patch_failed(self, event: K8sResourcePatchFailedEvent) -> None: logger.error("Failed to patch resource constraints: %s", event.message) def _on_kratos_info_provider_ready(self, event: RelationEvent) -> None: + # Blocked on this, the charm plans nothing and Kratos runs what was published before. + if not multitenancy_config_is_valid(self): + return + internal_endpoints = InternalRouteData.load(self.internal_route) providers_configmap_name = self.providers_configmap.name schemas_configmap_name = self.schemas_configmap.name @@ -693,6 +708,7 @@ def _on_kratos_info_provider_ready(self, event: RelationEvent) -> None: oidc_webauthn_sequencing_enabled, verification_enabled, active_flags, + privileged_session_max_age=PRIVILEGED_SESSION_MAX_AGE, ) def _on_database_created(self, event: DatabaseCreatedEvent) -> None: diff --git a/src/configs.py b/src/configs.py index 8effef09..fb2be649 100644 --- a/src/configs.py +++ b/src/configs.py @@ -29,6 +29,7 @@ EMAIL_TEMPLATE_FILE_PATH, IDENTITY_SCHEMAS_LOCAL_DIR_PATH, MAPPERS_LOCAL_DIR_PATH, + PRIVILEGED_SESSION_MAX_AGE, PROVIDERS_CONFIGMAP_FILE_NAME, VERIFICATION_EMAIL_TEMPLATE_RESOURCE_NAME, ) @@ -134,6 +135,7 @@ def to_service_configs(self) -> ServiceConfigs: "enable_passwordless_login_method": self._config["enable_passwordless_login_method"], "enable_oidc_webauthn_sequencing": self._config["enable_oidc_webauthn_sequencing"], "enable_verification": self._config["enable_verification"], + "privileged_session_max_age": PRIVILEGED_SESSION_MAX_AGE, } diff --git a/src/constants.py b/src/constants.py index b53098c1..2313f558 100644 --- a/src/constants.py +++ b/src/constants.py @@ -51,6 +51,9 @@ # Action constants ALLOWED_MFA_CREDENTIAL_TYPES = ("totp", "lookup_secret", "webauthn") +# Kratos's own default, set explicitly so that kratos-info can publish it +PRIVILEGED_SESSION_MAX_AGE = "1h" + # Secret constants COOKIE_SECRET_LABEL = "cookie_secret" COOKIE_SECRET_CONTENT_KEY = "cookiesecret" diff --git a/src/integrations.py b/src/integrations.py index 4d486587..2987a73c 100644 --- a/src/integrations.py +++ b/src/integrations.py @@ -179,12 +179,23 @@ class LoginUIEndpointData: account_linking_settings_url: str = "" registration_url: str = "" consent_url: str = "" + byosso_enabled: str = "" + + @property + def multitenancy(self) -> bool: + """Whether the login UI runs multitenancy and decides itself when MFA is required.""" + return self.byosso_enabled == "true" def is_ready(self) -> bool: - return all(v for _, v in self.to_service_configs().items()) + return all(v for k, v in self.to_service_configs().items() if k != "multitenancy") + + def to_env_vars(self) -> EnvVars: + # Sessions that have not completed a second factor have to reach whoami. + return {"SESSION_WHOAMI_REQUIRED_AAL": "aal1"} if self.multitenancy else {} def to_service_configs(self) -> ServiceConfigs: return { + "multitenancy": self.multitenancy, "default_browser_return_url": self.settings_url, "login_ui_url": self.login_url, "error_ui_url": self.error_url, diff --git a/src/utils.py b/src/utils.py index 404359c6..9988c2b5 100644 --- a/src/utils.py +++ b/src/utils.py @@ -14,7 +14,7 @@ PUBLIC_ROUTE_INTEGRATION_NAME, WORKLOAD_CONTAINER, ) -from integrations import PublicRouteData +from integrations import LoginUIEndpointData, PublicRouteData if TYPE_CHECKING: from charm import KratosCharm @@ -124,6 +124,21 @@ def passwordless_config_is_valid(charm: "KratosCharm") -> bool: ) +def multitenancy_config_is_valid(charm: "KratosCharm") -> bool: + """Checks the config against the login UI's multitenancy, when it runs it. + + The login UI then decides when MFA is required, which OIDC-WebAuthn sequencing would + decide too, and relies on Kratos's verification of the addresses an external identity + provider did not confirm. + """ + if not LoginUIEndpointData.load(charm.login_ui_requirer).multitenancy: + return True + + return bool(charm.charm_config["enable_verification"]) and not bool( + charm.charm_config["enable_oidc_webauthn_sequencing"] + ) + + # Condition failure causes early return without doing anything NOOP_CONDITIONS: tuple[Condition, ...] = ( peer_integration_exists, @@ -134,6 +149,7 @@ def passwordless_config_is_valid(charm: "KratosCharm") -> bool: external_hostname_is_ready, public_route_is_ready, passwordless_config_is_valid, + multitenancy_config_is_valid, ) # Condition failure causes early return with corresponding event deferred diff --git a/templates/kratos.yaml.j2 b/templates/kratos.yaml.j2 index 24ba0d6b..0f3398da 100644 --- a/templates/kratos.yaml.j2 +++ b/templates/kratos.yaml.j2 @@ -59,6 +59,9 @@ selfservice: {%- set _empty_flow = {"before": {"hooks": []}, "after": {"hooks": []}} %} {%- set registration_flow = registration_flow | d(_empty_flow) %} {%- set login_flow = login_flow | d(_empty_flow) %} + {#- With multitenancy the login UI decides when MFA is required, so TOTP and + recovery codes stay available whatever enforce_mfa and enable_local_idp say. -#} + {%- set _multitenancy = multitenancy | d(False) %} {%- if error_ui_url or login_ui_url or oidc_providers or _has_reg_hooks or _has_login_hooks %} flows: {%- if error_ui_url %} @@ -87,8 +90,8 @@ selfservice: {%- set _need_login_oidc = oidc_providers and (_login_all or _login_after.oidc | d([])) %} {%- set _need_login_code = enable_local_idp and (_login_all or _login_after.code | d([])) %} {%- set _need_login_webauthn = (enable_passwordless_login_method or enable_oidc_webauthn_sequencing) and (_login_all or _login_after.webauthn | d([])) %} - {%- set _need_login_totp = (enforce_mfa and enable_local_idp) and (_login_all or _login_after.totp | d([])) %} - {%- set _need_login_lookup = (enable_oidc_webauthn_sequencing or (enforce_mfa and enable_local_idp)) and (_login_all or _login_after.lookup_secret | d([])) %} + {%- set _need_login_totp = (enforce_mfa and enable_local_idp or _multitenancy) and (_login_all or _login_after.totp | d([])) %} + {%- set _need_login_lookup = (enable_oidc_webauthn_sequencing or (enforce_mfa and enable_local_idp) or _multitenancy) and (_login_all or _login_after.lookup_secret | d([])) %} {%- if _need_login_password or _need_login_oidc or _need_login_code or _need_login_webauthn or _need_login_totp or _need_login_lookup %} after: {%- if _need_login_password %} @@ -133,6 +136,7 @@ selfservice: settings: ui_url: {{ settings_ui_url }} required_aal: highest_available + privileged_session_max_age: {{ privileged_session_max_age }} after: oidc: default_browser_return_url: {{ account_linking_settings_url }} @@ -165,6 +169,9 @@ selfservice: enabled: True ui_url: {{ registration_ui_url }} {%- endif %} + {%- if _multitenancy %} + login_hints: True + {%- endif %} {%- if _has_reg_hooks and registration_flow.before.hooks %} before: hooks: @@ -194,6 +201,9 @@ selfservice: hooks: {{- render_web_hooks(registration_flow.after.hooks | d([]), " ") }} {{- render_web_hooks(registration_flow.after.oidc | d([]), " ") }} + {%- if enable_verification and _multitenancy %} + - hook: show_verification_ui + {%- endif %} - hook: session {%- endif %} {%- if _need_reg_webauthn %} @@ -216,7 +226,7 @@ selfservice: {%- endif %} {%- endif %} {%- endif %} - {%- if oidc_providers or recovery_ui_url or enable_local_idp and login_ui_url %} + {%- if oidc_providers or recovery_ui_url or enable_local_idp and login_ui_url or _multitenancy %} methods: {%- if enable_local_idp %} profile: @@ -243,14 +253,14 @@ selfservice: enabled: True config: haveibeenpwned_enabled: False - {%- if enforce_mfa %} + {%- endif %} + {%- if enforce_mfa and enable_local_idp and login_ui_url or _multitenancy %} totp: enabled: True config: issuer: Identity Platform {%- endif %} - {%- endif %} - {%- if enable_oidc_webauthn_sequencing or (enforce_mfa and enable_local_idp) %} + {%- if enable_oidc_webauthn_sequencing or (enforce_mfa and enable_local_idp) or _multitenancy %} lookup_secret: enabled: True {%- endif %} diff --git a/tests/unit/test_charm.py b/tests/unit/test_charm.py index dd1b0b7c..76182b60 100644 --- a/tests/unit/test_charm.py +++ b/tests/unit/test_charm.py @@ -15,6 +15,7 @@ KRATOS_PUBLIC_PORT, PEER_INTEGRATION_NAME, WORKLOAD_CONTAINER, + WORKLOAD_SERVICE, ) @@ -146,6 +147,64 @@ def test_when_event_emitted(self, mocked_charm_holistic_handler: MagicMock) -> N mocked_charm_holistic_handler.assert_called_once() +class TestMultitenancy: + @pytest.mark.parametrize( + "enable_verification, status, whoami_required_aal", + [ + pytest.param( + True, + testing.ActiveStatus(), + {WORKLOAD_SERVICE: "aal1", COURIER_SERVICE: "aal1"}, + id="the login UI's AAL is planned, not the one enforce_mfa sets", + ), + pytest.param( + False, + testing.BlockedStatus( + "Multitenancy requires `enable_verification=True` and " + "`enable_oidc_webauthn_sequencing=False`" + ), + {}, + id="an invalid config blocks and plans nothing", + ), + ], + ) + @patch("charm.KratosCharm._push_verification_email_template") + def test_plan( + self, + mocked_push_verification_email_template: MagicMock, + enable_verification: bool, + status: testing.ActiveStatus | testing.BlockedStatus, + whoami_required_aal: dict[str, str], + charm_secret: testing.Secret, + database_integration: testing.Relation, + peer_integration: testing.PeerRelation, + mocked_migration_needed: MagicMock, + ) -> None: + mocked_migration_needed.return_value = False + ctx = testing.Context(KratosCharm) + container = testing.Container(WORKLOAD_CONTAINER, can_connect=True) + login_ui_integration = testing.Relation( + "ui-endpoint-info", + interface="login_ui_endpoints", + remote_app_data={"byosso_enabled": "true"}, + ) + state_in = testing.State( + containers={container}, + secrets=[charm_secret], + relations=[database_integration, peer_integration, login_ui_integration], + config={"enable_verification": enable_verification}, + ) + + state_out = ctx.run(ctx.on.update_status(), state_in) + + assert state_out.unit_status == status + services = state_out.get_container(WORKLOAD_CONTAINER).plan.services + assert { + name: service.environment["SESSION_WHOAMI_REQUIRED_AAL"] + for name, service in services.items() + } == whoami_required_aal + + class TestDatabaseCreatedEvent: def test_when_container_not_connected( self, @@ -602,6 +661,56 @@ def test_when_event_emitted( ctx.run(ctx.on.relation_created(kratos_info_integration), state_in) mocked_send_info_relation_data.assert_called_once() + kwargs = mocked_send_info_relation_data.call_args.kwargs + assert kwargs["privileged_session_max_age"] == "1h" + + @patch("charm.KratosInfoProvider.send_info_relation_data") + def test_when_multitenancy_config_invalid( + self, + mocked_send_info_relation_data: MagicMock, + kratos_info_integration: testing.Relation, + public_route_integration: testing.Relation, + ) -> None: + ctx = testing.Context(KratosCharm) + container = testing.Container(WORKLOAD_CONTAINER, can_connect=True) + login_ui_integration = testing.Relation( + "ui-endpoint-info", + interface="login_ui_endpoints", + remote_app_data={"byosso_enabled": "true"}, + ) + state_in = testing.State( + containers={container}, + relations=[kratos_info_integration, public_route_integration, login_ui_integration], + config={"enable_verification": False}, + ) + + ctx.run(ctx.on.config_changed(), state_in) + + mocked_send_info_relation_data.assert_not_called() + + @patch("charm.KratosInfoProvider.send_info_relation_data") + def test_when_blocking_login_ui_integration_removed( + self, + mocked_send_info_relation_data: MagicMock, + kratos_info_integration: testing.Relation, + public_route_integration: testing.Relation, + ) -> None: + ctx = testing.Context(KratosCharm) + container = testing.Container(WORKLOAD_CONTAINER, can_connect=True) + login_ui_integration = testing.Relation( + "ui-endpoint-info", + interface="login_ui_endpoints", + remote_app_data={"byosso_enabled": "true"}, + ) + state_in = testing.State( + containers={container}, + relations=[kratos_info_integration, public_route_integration, login_ui_integration], + config={"enable_verification": False}, + ) + + ctx.run(ctx.on.relation_broken(login_ui_integration), state_in) + + mocked_send_info_relation_data.assert_called_once() class TestHydraEndpointInfoRelationChangedEvent: diff --git a/tests/unit/test_configs.py b/tests/unit/test_configs.py index d41f000e..ac83463b 100644 --- a/tests/unit/test_configs.py +++ b/tests/unit/test_configs.py @@ -109,6 +109,7 @@ def test_to_service_configs(self, mocked_config: dict) -> None: "enable_passwordless_login_method": True, "enable_oidc_webauthn_sequencing": False, "enable_verification": False, + "privileged_session_max_age": "1h", } @@ -688,3 +689,48 @@ def test_registration_weight_ordering(self) -> None: oidc_hooks = [h for h in reg["after"]["oidc"]["hooks"] if h["hook"] == "web_hook"] urls = [h["config"]["url"] for h in oidc_hooks] assert urls == ["http://example.com/low", "http://example.com/high"] + + def _multitenancy_sources(self, multitenancy: bool) -> tuple: + charm_config = CharmConfig({ + "enable_local_idp": True, + "enforce_mfa": False, + "enable_passwordless_login_method": False, + "enable_oidc_webauthn_sequencing": False, + "enable_verification": True, + }) + login_ui = MagicMock() + login_ui.to_service_configs.return_value = { + "login_ui_url": "http://example.com/login", + "settings_ui_url": "http://example.com/settings", + "multitenancy": multitenancy, + } + hooks = RegistrationWebhookData(configs=[self._make_reg_hook_config("after")]) + return self._identity_source(), charm_config, login_ui, hooks + + def test_multitenancy(self) -> None: + cfg = ConfigFile.from_sources(*self._multitenancy_sources(True)) + + selfservice = cfg.yaml_content["selfservice"] + assert selfservice["methods"]["totp"]["enabled"] is True + assert selfservice["methods"]["lookup_secret"]["enabled"] is True + registration = selfservice["flows"]["registration"] + assert registration["login_hints"] is True + oidc_hooks = [h["hook"] for h in registration["after"]["oidc"]["hooks"]] + assert oidc_hooks == ["web_hook", "show_verification_ui", "session"] + + def test_without_multitenancy(self) -> None: + cfg = ConfigFile.from_sources(*self._multitenancy_sources(False)) + + selfservice = cfg.yaml_content["selfservice"] + assert "totp" not in selfservice["methods"] + assert "lookup_secret" not in selfservice["methods"] + registration = selfservice["flows"]["registration"] + assert "login_hints" not in registration + oidc_hooks = [h["hook"] for h in registration["after"]["oidc"]["hooks"]] + assert oidc_hooks == ["web_hook", "session"] + + def test_privileged_session_max_age(self) -> None: + cfg = ConfigFile.from_sources(*self._multitenancy_sources(False)) + + settings = cfg.yaml_content["selfservice"]["flows"]["settings"] + assert settings["privileged_session_max_age"] == "1h" diff --git a/tests/unit/test_integrations.py b/tests/unit/test_integrations.py index a4d29b0a..4b0c9e41 100644 --- a/tests/unit/test_integrations.py +++ b/tests/unit/test_integrations.py @@ -257,6 +257,7 @@ def mocked_requirer(self) -> MagicMock: def test_to_service_configs(self, endpoint_data: LoginUIEndpointData) -> None: expected = { + "multitenancy": False, "default_browser_return_url": "settings_url", "login_ui_url": "login_url", "error_ui_url": "error_url", @@ -295,6 +296,28 @@ def test_load_with_failure(self, mocked_requirer: MagicMock) -> None: actual = LoginUIEndpointData.load(mocked_requirer) assert actual == LoginUIEndpointData() + @pytest.mark.parametrize( + "byosso_enabled, expected_env_vars", + [ + ("true", {"SESSION_WHOAMI_REQUIRED_AAL": "aal1"}), + ("false", {}), + ("", {}), + ], + ) + def test_multitenancy( + self, mocked_requirer: MagicMock, byosso_enabled: str, expected_env_vars: dict + ) -> None: + mocked_requirer.get_login_ui_endpoints.return_value = { + "login_url": "login_url", + "byosso_enabled": byosso_enabled, + } + + actual = LoginUIEndpointData.load(mocked_requirer) + + assert actual.multitenancy is (byosso_enabled == "true") + assert actual.to_service_configs()["multitenancy"] is (byosso_enabled == "true") + assert actual.to_env_vars() == expected_env_vars + class TestHydraEndpointData: @pytest.fixture diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 7d11ff8b..a10abd86 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -1,7 +1,11 @@ # Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. -from utils import dict_to_action_output +from unittest.mock import MagicMock, patch + +import pytest + +from utils import dict_to_action_output, multitenancy_config_is_valid def test_dict_to_action_output() -> None: @@ -34,3 +38,27 @@ def test_dict_to_action_output_with_empty_dict() -> None: actual = dict_to_action_output({}) assert actual == {} + + +@pytest.mark.parametrize( + "multitenancy, enable_verification, sequencing, expected", + [ + (False, False, True, True), + (True, True, False, True), + (True, False, False, False), + (True, True, True, False), + ], +) +def test_multitenancy_config_is_valid( + multitenancy: bool, enable_verification: bool, sequencing: bool, expected: bool +) -> None: + charm = MagicMock() + charm.charm_config = { + "enable_verification": enable_verification, + "enable_oidc_webauthn_sequencing": sequencing, + } + + with patch("utils.LoginUIEndpointData.load") as mocked_load: + mocked_load.return_value.multitenancy = multitenancy + + assert multitenancy_config_is_valid(charm) is expected