diff --git a/changelog.md b/changelog.md index c53dced9b..85ff22c81 100644 --- a/changelog.md +++ b/changelog.md @@ -39,6 +39,7 @@ Use `load_configuration_from_env(os.environ)` to expand environment-style names ## Major Features & Enhancements +- **Application Options Configuration**: Added `ApplicationOptions.from_config()` to bind scoped settings or the application-root `AgentApplication` section. Pass the resulting options to `AgentApplication(options=...)` to use nested settings; constructor keyword arguments continue to read only top-level options for backward compatibility (#656). - **Teams API Dependency**: Updated `microsoft-agents-hosting-msteams` to use `microsoft-teams-api` 2.2.0, including HTTPX2 transport, nullable meeting join URLs, and typed chat, reply-chain, and source channel data. - **JWT Authorization Configuration**: Added `ConnectionSettingsBase`, `JwtConnectionSettings`, and `TokenValidationConfig` to bind inbound JWT policies from application configuration, including explicit audiences, tenant and anonymous-access overrides, and per-connection issuer settings. Retained legacy `AgentAuthConfiguration` support and added application-scoped validator caching without changing `Connections` or `ConnectionManager` (#638). - **Explicit JWT Audience Lists**: Scalar and delimited audience strings now bind as explicit allow-lists instead of falling back to all configured connection client IDs. Missing or empty audiences continue to use connection defaults (#638). diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/config/_metadata.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/config/_metadata.py index 7c4d9d5ef..894b238c3 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/config/_metadata.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/config/_metadata.py @@ -40,4 +40,8 @@ def get(mapping: Mapping) -> bool: @staticmethod def set(mapping: MutableMapping, value: bool) -> None: - mapping[_RootConfigMetadata._KEY] = value + if value is False: + if _RootConfigMetadata._KEY in mapping: + del mapping[_RootConfigMetadata._KEY] + else: + mapping[_RootConfigMetadata._KEY] = value diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/agent_application.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/agent_application.py index 49aa83b38..cbe61ca40 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/agent_application.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/agent_application.py @@ -35,6 +35,8 @@ InvokeResponse, ) +from microsoft_agents.activity.config._metadata import _RootConfigMetadata + from microsoft_agents.hosting.core.turn_context import TurnContext from ..agent import Agent @@ -133,18 +135,26 @@ def __init__( ).strip() self._agent_name = sanitized_agent_name or type(self).__name__ - configuration = kwargs + _RootConfigMetadata.set(kwargs, False) # required for back-compat if not options: - # TODO: consolidate configuration story - # Take the options from the kwargs and create an ApplicationOptions instance - option_kwargs = dict( - filter( - lambda x: x[0] in ApplicationOptions.__dataclass_fields__, - kwargs.items(), - ) + options = ApplicationOptions.from_config(kwargs) + else: + alt_options = ApplicationOptions.from_config(kwargs) + options = copy(options) + options.storage = options.storage or alt_options.storage + options.proactive = options.proactive or alt_options.proactive + options.turn_state_factory = ( + options.turn_state_factory or alt_options.turn_state_factory + ) + options.file_downloaders = ( + options.file_downloaders or alt_options.file_downloaders + ) + options.adapter = options.adapter or alt_options.adapter + options.authorization_handlers = ( + options.authorization_handlers or alt_options.authorization_handlers ) - options = ApplicationOptions(**option_kwargs) + options.typing = options.typing or alt_options.typing self._options = options @@ -166,7 +176,7 @@ def __init__( """) self._storage = self._options.storage - if options.long_running_messages and not options.bot_app_id: + if self._options.long_running_messages and not self._options.bot_app_id: logger.error( "ApplicationOptions.long_running_messages requires an adapter and bot_app_id.", stack_info=True, @@ -176,14 +186,12 @@ def __init__( no adapter or `bot_app_id` was configured. """) - self._turn_state_factory = ( - options.turn_state_factory - or kwargs.get("turn_state_factory", None) - or partial(TurnState.with_storage, self._storage) + self._turn_state_factory = self._options.turn_state_factory or partial( + TurnState.with_storage, self._storage ) - if options.proactive: - proactive_opts = copy(options.proactive) + if self._options.proactive: + proactive_opts = copy(self._options.proactive) if not proactive_opts.storage: proactive_opts.storage = self._storage self._proactive = Proactive(self, proactive_opts) @@ -211,7 +219,7 @@ def __init__( auth_options = { key: value - for key, value in configuration.items() + for key, value in kwargs.items() if key not in ["storage", "connection_manager", "handlers", "agent_name"] } diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/app_options.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/app_options.py index cdcbf3a12..3d840f610 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/app_options.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/app_options.py @@ -8,6 +8,13 @@ from dataclasses import dataclass, field from typing import Callable +from microsoft_agents.activity.config import ( + Configuration, + _RootConfigurable, + ignore_case, + _legpath as legpath, +) + from microsoft_agents.hosting.core.app.oauth import AuthHandlerConfig from microsoft_agents.hosting.core.storage import Storage @@ -21,7 +28,7 @@ @dataclass -class ApplicationOptions: +class ApplicationOptions(_RootConfigurable): adapter: ChannelServiceAdapter | None = None """ Optional. Options used to initialize your `BotAdapter` @@ -95,3 +102,67 @@ class ApplicationOptions: When set, :attr:`microsoft_agents.hosting.core.AgentApplication.proactive` is available for storing conversations and initiating proactive turns. """ + + @classmethod + def _from_scoped_configuration(cls, config: Configuration) -> ApplicationOptions: + auth_handlers = config.get(legpath("authorization_handlers"), None) + if auth_handlers is not None and not isinstance(auth_handlers, dict): + raise TypeError("authorization_handlers must be a mapping") + + typing = config.get("typing") + if typing is not None and not isinstance(typing, TypingOptions): + raise TypeError("typing must be an instance of TypingOptions or None") + + storage = config.get("storage") + if storage is not None and not isinstance(storage, Storage): + raise TypeError("storage must be an instance of Storage or None") + + proactive_options = config.get("proactive") + if proactive_options is not None and not isinstance( + proactive_options, ProactiveOptions + ): + raise TypeError("proactive must be an instance of ProactiveOptions or None") + + turn_state_factory = config.get("turn_state_factory") + + file_downloaders = config.get("file_downloaders") + if file_downloaders is not None and isinstance(file_downloaders, list): + if file_downloaders: + for downloader in file_downloaders: + if not isinstance(downloader, InputFileDownloader): + raise TypeError( + "each item in file_downloaders must be an instance of FileDownloader" + ) + elif file_downloaders is not None and not isinstance(file_downloaders, list): + raise TypeError("file_downloaders must be a list or None") + file_downloaders = file_downloaders or [] + + adapter = config.get("adapter") + if adapter is not None and not isinstance(adapter, ChannelServiceAdapter): + raise TypeError( + "adapter must be an instance of ChannelServiceAdapter or None" + ) + + return ApplicationOptions( + typing=typing, + bot_app_id=config.get_str(legpath("bot_app_id"), ""), + start_typing_timer=config.get_bool(legpath("start_typing_timer"), True), + remove_recipient_mention=config.get_bool( + legpath("remove_recipient_mention"), True + ), + long_running_messages=config.get_bool( + legpath("long_running_messages"), False + ), + authorization_handlers=auth_handlers, + storage=storage, + proactive=proactive_options, + turn_state_factory=turn_state_factory, + file_downloaders=file_downloaders, + adapter=adapter, + ) + + @classmethod + def _from_root_configuration(cls, config: Configuration) -> ApplicationOptions: + return cls._from_scoped_configuration( + config.get_section(legpath("AgentApplication"), default=Configuration()) + ) diff --git a/tests/hosting_core/app/test_app_options.py b/tests/hosting_core/app/test_app_options.py new file mode 100644 index 000000000..22f28bb5c --- /dev/null +++ b/tests/hosting_core/app/test_app_options.py @@ -0,0 +1,205 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from unittest.mock import Mock + +import pytest + +from microsoft_agents.activity.config import load_configuration_from_env +from microsoft_agents.hosting.core import MemoryStorage +from microsoft_agents.hosting.core.app import ( + AgentApplication, + ApplicationOptions, + InputFileDownloader, + TurnState, +) +from microsoft_agents.hosting.core.app.oauth import Authorization, AuthHandlerConfig +from microsoft_agents.hosting.core.app.proactive import ProactiveOptions +from microsoft_agents.hosting.core.app.typing_indicator import TypingOptions +from microsoft_agents.hosting.core.channel_service_adapter import ChannelServiceAdapter +from tests._common import create_configuration +from tests._common.testing_objects import TestingConnectionManager as _ConnectionManager + + +def _key(name, style): + if style == "pascal": + return "".join(part.capitalize() for part in name.split("_")) + if style == "upper": + return name.upper() + return name + + +def _configuration(values, is_root): + return create_configuration( + {"AgentApplication": values} if is_root else values, + is_root=is_root, + ) + + +@pytest.mark.parametrize("is_root", [False, True], ids=["scoped", "root"]) +@pytest.mark.parametrize("style", ["snake", "pascal", "upper"]) +def test_binds_scalar_settings_with_configuration_aliases(is_root, style): + values = { + "bot_app_id": "test-agent", + "start_typing_timer": "false", + "remove_recipient_mention": "0", + "long_running_messages": "true", + } + config = _configuration( + {_key(name, style): value for name, value in values.items()}, is_root + ) + + options = ApplicationOptions.from_config(config) + + assert options.bot_app_id == "test-agent" + assert options.start_typing_timer is False + assert options.remove_recipient_mention is False + assert options.long_running_messages is True + + +@pytest.fixture +def runtime_dependencies(): + return { + "storage": MemoryStorage(), + "typing": TypingOptions(initial_delay_ms=100, interval_ms=2000), + "proactive": ProactiveOptions(fail_on_unsigned_in_connections=False), + "turn_state_factory": TurnState, + "file_downloaders": [Mock(spec=InputFileDownloader)], + "adapter": Mock(spec=ChannelServiceAdapter), + "authorization_handlers": {"graph": AuthHandlerConfig(name="graph")}, + } + + +@pytest.mark.parametrize("is_root", [False, True], ids=["scoped", "root"]) +def test_preserves_runtime_dependencies(runtime_dependencies, is_root): + config = _configuration(runtime_dependencies, is_root) + + options = ApplicationOptions.from_config(config) + + for name in ("storage", "typing", "proactive", "turn_state_factory", "adapter"): + assert getattr(options, name) is runtime_dependencies[name], name + assert options.file_downloaders[0] is runtime_dependencies["file_downloaders"][0] + assert ( + options.authorization_handlers["graph"] + is runtime_dependencies["authorization_handlers"]["graph"] + ) + + +@pytest.mark.parametrize( + "name, value, message", + [ + ("storage", object(), "storage must be an instance of Storage"), + ("typing", {}, "typing must be an instance of TypingOptions"), + ("proactive", {}, "proactive must be an instance of ProactiveOptions"), + ("adapter", object(), "adapter must be an instance of ChannelServiceAdapter"), + ("authorization_handlers", [], "authorization_handlers must be a mapping"), + ("file_downloaders", object(), "file_downloaders must be a list"), + ("file_downloaders", [object()], "each item in file_downloaders"), + ], +) +def test_rejects_invalid_runtime_dependencies(name, value, message): + with pytest.raises(TypeError, match=message): + ApplicationOptions.from_config({name: value}) + + +def test_invalid_scalar_reports_root_configuration_path_without_value(): + config = _configuration({"StartTypingTimer": "invalid-setting-value"}, True) + + with pytest.raises(ValueError, match="AgentApplication::StartTypingTimer") as error: + ApplicationOptions.from_config(config) + + assert "invalid-setting-value" not in str(error.value) + + +@pytest.mark.parametrize("bind_options", [False, True], ids=["legacy-kwargs", "bound"]) +def test_application_preserves_legacy_scope_and_forwards_authorization(bind_options): + config = load_configuration_from_env( + { + "AGENTAPPLICATION__STARTTYPINGTIMER": "false", + "AGENTAPPLICATION__REMOVERECIPIENTMENTION": "false", + "AGENTAPPLICATION__USERAUTHORIZATION__AUTO_SIGN_IN": "true", + } + ) + original_config = dict(config) + storage = MemoryStorage() + kwargs = ( + {"options": ApplicationOptions.from_config(config), "config": config} + if bind_options + else dict(config) + ) + + app = AgentApplication( + storage=storage, + connection_manager=_ConnectionManager(), + **kwargs, + ) + + assert app.options.start_typing_timer is not bind_options + assert app.options.remove_recipient_mention is not bind_options + assert app.options.storage is storage + assert app.auth._auto_sign_in is True + assert isinstance(app._turn_state_factory(), TurnState) + assert config == original_config + + +@pytest.mark.parametrize( + "kwargs, error_type, message", + [ + ( + {"start_typing_timer": "invalid-setting"}, + ValueError, + "Invalid boolean for start_typing_timer", + ), + ( + {"typing": {"invalid": True}}, + TypeError, + "typing must be an instance of TypingOptions", + ), + ], +) +def test_explicit_options_still_validate_kwargs(kwargs, error_type, message): + storage = MemoryStorage() + + with pytest.raises(error_type, match=message): + AgentApplication( + options=ApplicationOptions(storage=storage, start_typing_timer=False), + authorization=Authorization(storage, _ConnectionManager()), + **kwargs, + ) + + +def test_explicit_options_override_valid_kwargs(): + storage = MemoryStorage() + app = AgentApplication( + options=ApplicationOptions(storage=storage, start_typing_timer=False), + authorization=Authorization(storage, _ConnectionManager()), + storage=MemoryStorage(), + start_typing_timer=True, + ) + + assert app.options.storage is storage + assert app.options.start_typing_timer is False + + +@pytest.mark.parametrize("has_explicit_downloaders", [False, True]) +def test_downloaders_use_kwargs_when_explicit_options_are_empty( + has_explicit_downloaders, +): + storage = MemoryStorage() + explicit_downloaders = ( + [Mock(spec=InputFileDownloader)] if has_explicit_downloaders else [] + ) + fallback_downloader = Mock(spec=InputFileDownloader) + app = AgentApplication( + options=ApplicationOptions( + storage=storage, file_downloaders=explicit_downloaders + ), + authorization=Authorization(storage, _ConnectionManager()), + file_downloaders=[fallback_downloader], + ) + + expected = ( + explicit_downloaders[0] if has_explicit_downloaders else fallback_downloader + ) + assert len(app.options.file_downloaders) == 1 + assert app.options.file_downloaders[0] is expected