async def test_claims_validation(self):
        claims: List[Dict] = []
        default_auth_config = AuthenticationConfiguration()

        # No validator should pass.
        await JwtTokenValidation.validate_claims(default_auth_config, claims)

        mock_validator = Mock()
        auth_with_validator = AuthenticationConfiguration(
            claims_validator=mock_validator)

        # Configure IClaimsValidator to fail
        mock_validator.side_effect = PermissionError("Invalid claims.")
        with pytest.raises(PermissionError) as excinfo:
            await JwtTokenValidation.validate_claims(auth_with_validator,
                                                     claims)

        assert "Invalid claims." in str(excinfo.value)

        # No validator with not skill cliams should pass.
        default_auth_config.claims_validator = None
        claims: List[Dict] = {
            AuthenticationConstants.VERSION_CLAIM: "1.0",
            AuthenticationConstants.AUDIENCE_CLAIM: "this_bot_id",
            AuthenticationConstants.APP_ID_CLAIM:
            "this_bot_id",  # Skill claims aud!=azp
        }

        await JwtTokenValidation.validate_claims(default_auth_config, claims)

        # No validator with skill cliams should fail.
        claims: List[Dict] = {
            AuthenticationConstants.VERSION_CLAIM: "1.0",
            AuthenticationConstants.AUDIENCE_CLAIM: "this_bot_id",
            AuthenticationConstants.APP_ID_CLAIM:
            "not_this_bot_id",  # Skill claims aud!=azp
        }

        mock_validator.side_effect = PermissionError(
            "Unauthorized Access. Request is not authorized. Skill Claims require validation."
        )
        with pytest.raises(PermissionError) as excinfo_skill:
            await JwtTokenValidation.validate_claims(auth_with_validator,
                                                     claims)

        assert (
            "Unauthorized Access. Request is not authorized. Skill Claims require validation."
            in str(excinfo_skill.value))
Ejemplo n.º 2
0
 def __init__(self,
              configuration: Any,
              *,
              credentials_factory: ServiceClientCredentialsFactory = None,
              auth_configuration: AuthenticationConfiguration = None,
              http_client_factory: HttpClientFactory = None,
              logger: Logger = None):
     self._inner: BotFrameworkAuthentication = BotFrameworkAuthenticationFactory.create(
         channel_service=getattr(configuration, "CHANNEL_SERVICE", None),
         validate_authority=getattr(configuration, "VALIDATE_AUTHORITY",
                                    True),
         to_channel_from_bot_login_url=getattr(
             configuration, "TO_CHANNEL_FROM_BOT_LOGIN_URL", None),
         to_channel_from_bot_oauth_scope=getattr(
             configuration, "TO_CHANNEL_FROM_BOT_OAUTH_SCOPE", None),
         to_bot_from_channel_token_issuer=getattr(
             configuration, "TO_BOT_FROM_CHANNEL_TOKEN_ISSUER", None),
         oauth_url=getattr(configuration, "OAUTH_URL", None),
         to_bot_from_channel_open_id_metadata_url=getattr(
             configuration, "TO_BOT_FROM_CHANNEL_OPENID_METADATA_URL",
             None),
         to_bot_from_emulator_open_id_metadata_url=getattr(
             configuration, "TO_BOT_FROM_EMULATOR_OPENID_METADATA_URL",
             None),
         caller_id=getattr(configuration, "CALLER_ID", None),
         credential_factory=(
             credentials_factory if credentials_factory else
             ConfigurationServiceClientCredentialFactory(configuration)),
         auth_configuration=(auth_configuration if auth_configuration else
                             AuthenticationConfiguration()),
         http_client_factory=http_client_factory,
         logger=logger,
     )
Ejemplo n.º 3
0
 def create_skill_handler_for_testing(
         self, adapter) -> SkillHandlerInstanceForTests:
     return SkillHandlerInstanceForTests(
         adapter,
         Mock(),
         self._test_id_factory,
         Mock(),
         AuthenticationConfiguration(),
     )
Ejemplo n.º 4
0
    async def test_claims_validation(self):
        claims: List[Dict] = []
        default_auth_config = AuthenticationConfiguration()

        # No validator should pass.
        await JwtTokenValidation.validate_claims(default_auth_config, claims)

        # ClaimsValidator configured but no exception should pass.
        mock_validator = Mock()
        auth_with_validator = AuthenticationConfiguration(
            claims_validator=mock_validator
        )

        # Configure IClaimsValidator to fail
        mock_validator.side_effect = PermissionError("Invalid claims.")
        with pytest.raises(PermissionError) as excinfo:
            await JwtTokenValidation.validate_claims(auth_with_validator, claims)

        assert "Invalid claims." in str(excinfo.value)
Ejemplo n.º 5
0
    def __init__(
        self,
        app_id: str,
        app_password: str = None,
        channel_auth_tenant: str = None,
        oauth_endpoint: str = None,
        open_id_metadata: str = None,
        channel_service: str = None,
        channel_provider: ChannelProvider = None,
        auth_configuration: AuthenticationConfiguration = None,
        certificate_thumbprint: str = None,
        certificate_private_key: str = None,
    ):
        """
        Contains the settings used to initialize a :class:`BotFrameworkAdapter` instance.

        :param app_id: The bot application ID.
        :type app_id: str
        :param app_password: The bot application password.
        the value os the `MicrosoftAppPassword` parameter in the `config.py` file.
        :type app_password: str
        :param channel_auth_tenant: The channel tenant to use in conversation
        :type channel_auth_tenant: str
        :param oauth_endpoint:
        :type oauth_endpoint: str
        :param open_id_metadata:
        :type open_id_metadata: str
        :param channel_service:
        :type channel_service: str
        :param channel_provider: The channel provider
        :type channel_provider: :class:`botframework.connector.auth.ChannelProvider`
        :param auth_configuration:
        :type auth_configuration: :class:`botframework.connector.auth.AuthenticationConfiguration`
        :param certificate_thumbprint: X509 thumbprint
        :type certificate_thumbprint: str
        :param certificate_private_key: X509 private key
        :type certificate_private_key: str

        .. remarks::
            For credentials authorization, both app_id and app_password are required.
            For certificate authorization, app_id, certificate_thumbprint, and certificate_private_key are required.

        """
        self.app_id = app_id
        self.app_password = app_password
        self.channel_auth_tenant = channel_auth_tenant
        self.oauth_endpoint = oauth_endpoint
        self.open_id_metadata = open_id_metadata
        self.channel_service = channel_service
        self.channel_provider = channel_provider
        self.auth_configuration = auth_configuration or AuthenticationConfiguration(
        )
        self.certificate_thumbprint = certificate_thumbprint
        self.certificate_private_key = certificate_private_key
Ejemplo n.º 6
0
    def __init__(
        self,
        app_id: str,
        app_password: str = None,
        channel_auth_tenant: str = None,
        oauth_endpoint: str = None,
        open_id_metadata: str = None,
        channel_provider: ChannelProvider = None,
        auth_configuration: AuthenticationConfiguration = None,
        app_credentials: AppCredentials = None,
        credential_provider: CredentialProvider = None,
    ):
        """
        Contains the settings used to initialize a :class:`BotFrameworkAdapter` instance.

        :param app_id: The bot application ID.
        :type app_id: str
        :param app_password: The bot application password.
        the value os the `MicrosoftAppPassword` parameter in the `config.py` file.
        :type app_password: str
        :param channel_auth_tenant: The channel tenant to use in conversation
        :type channel_auth_tenant: str
        :param oauth_endpoint:
        :type oauth_endpoint: str
        :param open_id_metadata:
        :type open_id_metadata: str
        :param channel_provider: The channel provider
        :type channel_provider: :class:`botframework.connector.auth.ChannelProvider`.  Defaults to SimpleChannelProvider
        if one isn't specified.
        :param auth_configuration:
        :type auth_configuration: :class:`botframework.connector.auth.AuthenticationConfiguration`
        :param credential_provider: Defaults to SimpleCredentialProvider if one isn't specified.
        :param app_credentials: Allows for a custom AppCredentials.  Used, for example, for CertificateAppCredentials.
        """

        self.app_id = app_id
        self.app_password = app_password
        self.app_credentials = app_credentials
        self.channel_auth_tenant = channel_auth_tenant
        self.oauth_endpoint = oauth_endpoint
        self.channel_provider = (channel_provider if channel_provider else
                                 SimpleChannelProvider())
        self.credential_provider = (credential_provider if credential_provider
                                    else SimpleCredentialProvider(
                                        self.app_id, self.app_password))
        self.auth_configuration = auth_configuration or AuthenticationConfiguration(
        )

        # If no open_id_metadata values were passed in the settings, check the
        # process' Environment Variable.
        self.open_id_metadata = (
            open_id_metadata if open_id_metadata else os.environ.get(
                AuthenticationConstants.BOT_OPEN_ID_METADATA_KEY))
    def create_skill_handler_for_testing(
            self, adapter) -> SkillHandlerInstanceForTests:
        mock_bot = Mock()
        mock_bot.on_turn = MagicMock(return_value=Future())
        mock_bot.on_turn.return_value.set_result(Mock())

        return SkillHandlerInstanceForTests(
            adapter,
            mock_bot,
            self._test_id_factory,
            Mock(),
            AuthenticationConfiguration(),
        )
Ejemplo n.º 8
0
 def __init__(
     self,
     app_id: str,
     app_password: str,
     channel_auth_tenant: str = None,
     oauth_endpoint: str = None,
     open_id_metadata: str = None,
     channel_service: str = None,
     channel_provider: ChannelProvider = None,
     auth_configuration: AuthenticationConfiguration = None,
 ):
     self.app_id = app_id
     self.app_password = app_password
     self.channel_auth_tenant = channel_auth_tenant
     self.oauth_endpoint = oauth_endpoint
     self.open_id_metadata = open_id_metadata
     self.channel_service = channel_service
     self.channel_provider = channel_provider
     self.auth_configuration = auth_configuration or AuthenticationConfiguration()
Ejemplo n.º 9
0
    def __init__(
        self,
        app_id: str,
        app_password: str,
        channel_auth_tenant: str = None,
        oauth_endpoint: str = None,
        open_id_metadata: str = None,
        channel_service: str = None,
        channel_provider: ChannelProvider = None,
        auth_configuration: AuthenticationConfiguration = None,
    ):
        """
        Contains the settings used to initialize a :class:`BotFrameworkAdapter` instance.

        :param app_id: The bot application ID. This is the appId returned by the Azure portal registration, and is
        the value of the `MicrosoftAppId` parameter in the `config.py` file.
        :type app_id: str
        :param app_password: The bot application password. This is the password returned by the Azure portal
        registration, and is
        the value os the `MicrosoftAppPassword` parameter in the `config.py` file.
        :type app_password: str
        :param channel_auth_tenant: The channel tenant to use in conversation
        :type channel_auth_tenant: str
        :param oauth_endpoint:
        :type oauth_endpoint: str
        :param open_id_metadata:
        :type open_id_metadata: str
        :param channel_service:
        :type channel_service: str
        :param channel_provider: The channel provider
        :type channel_provider: :class:`botframework.connector.auth.ChannelProvider`
        :param auth_configuration:
        :type auth_configuration: :class:`botframework.connector.auth.AuthenticationConfiguration`
        """
        self.app_id = app_id
        self.app_password = app_password
        self.channel_auth_tenant = channel_auth_tenant
        self.oauth_endpoint = oauth_endpoint
        self.open_id_metadata = open_id_metadata
        self.channel_service = channel_service
        self.channel_provider = channel_provider
        self.auth_configuration = auth_configuration or AuthenticationConfiguration()
Ejemplo n.º 10
0
    AuthenticationConfiguration,
    SimpleCredentialProvider,
)

from skill_conversation_id_factory import SkillConversationIdFactory
from authentication import AllowedSkillsClaimsValidator
from bots import HostBot
from config import DefaultConfig, SkillConfiguration
from adapter_with_error_handler import AdapterWithErrorHandler

CONFIG = DefaultConfig()
SKILL_CONFIG = SkillConfiguration()

# Whitelist skills from SKILL_CONFIG
AUTH_CONFIG = AuthenticationConfiguration(
    claims_validator=AllowedSkillsClaimsValidator(CONFIG).claims_validator
)
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(
    app_id=CONFIG.APP_ID,
    app_password=CONFIG.APP_PASSWORD,
    auth_configuration=AUTH_CONFIG,
)

STORAGE = MemoryStorage()
CONVERSATION_STATE = ConversationState(STORAGE)

ID_FACTORY = SkillConversationIdFactory(STORAGE)
CREDENTIAL_PROVIDER = SimpleCredentialProvider(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
CLIENT = SkillHttpClient(CREDENTIAL_PROVIDER, ID_FACTORY)
Ejemplo n.º 11
0
CLIENT = SkillHttpClient(CREDENTIAL_PROVIDER, ID_FACTORY)

# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
ADAPTER = AdapterWithErrorHandler(SETTINGS, CONFIG, CONVERSATION_STATE, CLIENT,
                                  SKILL_CONFIG)

DIALOG = MainDialog(CONVERSATION_STATE, ID_FACTORY, CLIENT, SKILL_CONFIG,
                    CONFIG)

# Create the Bot
BOT = RootBot(CONVERSATION_STATE,
              DIALOG)  # , SKILL_CONFIG, ID_FACTORY, CLIENT, CONFIG)

AUTH_CONFIG = AuthenticationConfiguration(
    claims_validator=AllowedSkillsClaimsValidator(CONFIG).claims_validator)

SKILL_HANDLER = SkillHandler(ADAPTER, BOT, ID_FACTORY, CREDENTIAL_PROVIDER,
                             AUTH_CONFIG)


# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=HTTPStatus.UNSUPPORTED_MEDIA_TYPE)

    activity = Activity().deserialize(body)
    auth_header = req.headers[
Ejemplo n.º 12
0
    SimpleCredentialProvider,
)

from skill_http_client import SkillHttpClient
from skill_conversation_id_factory import SkillConversationIdFactory
from authentication import AllowedSkillsClaimsValidator
from bots import RootBot
from config import DefaultConfig, SkillConfiguration

CONFIG = DefaultConfig()
SKILL_CONFIG = SkillConfiguration()

# Whitelist skills from SKILL_CONFIG
ALLOWED_CALLER_IDS = {s.app_id for s in [*SKILL_CONFIG.SKILLS.values()]}
CLAIMS_VALIDATOR = AllowedSkillsClaimsValidator(ALLOWED_CALLER_IDS)
AUTH_CONFIG = AuthenticationConfiguration(
    claims_validator=CLAIMS_VALIDATOR.validate_claims)
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(
    app_id=CONFIG.APP_ID,
    app_password=CONFIG.APP_PASSWORD,
    auth_configuration=AUTH_CONFIG,
)
ADAPTER = BotFrameworkAdapter(SETTINGS)

STORAGE = MemoryStorage()

CONVERSATION_STATE = ConversationState(STORAGE)
ID_FACTORY = SkillConversationIdFactory(STORAGE)
CREDENTIAL_PROVIDER = SimpleCredentialProvider(CONFIG.APP_ID,
                                               CONFIG.APP_PASSWORD)
Ejemplo n.º 13
0
            timestamp=datetime.utcnow(),
            type=ActivityTypes.trace,
            value=f"{error}",
            value_type="https://www.botframework.com/schemas/error",
        )
        # Send a trace activity, which will be displayed in Bot Framework Emulator
        await context.send_activity(trace_activity)


ADAPTER.on_turn_error = on_error

# Create the Bot
BOT = RootBot(CONVERSATION_STATE, SKILL_CONFIG, ID_FACTORY, CLIENT, CONFIG)

SKILL_HANDLER = SkillHandler(
    ADAPTER, BOT, ID_FACTORY, CREDENTIAL_PROVIDER, AuthenticationConfiguration()
)


# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    try:
Ejemplo n.º 14
0
from skill_adapter_with_error_handler import AdapterWithErrorHandler

CONFIG = DefaultConfig()

# Create MemoryStorage, UserState and ConversationState
MEMORY = MemoryStorage()
USER_STATE = UserState(MEMORY)
CONVERSATION_STATE = ConversationState(MEMORY)

# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
VALIDATOR = AllowedCallersClaimsValidator(CONFIG).claims_validator
SETTINGS = BotFrameworkAdapterSettings(
    CONFIG.APP_ID,
    CONFIG.APP_PASSWORD,
    auth_configuration=AuthenticationConfiguration(claims_validator=VALIDATOR),
)
ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE)

# Create the Bot
RECOGNIZER = DialogSkillBotRecognizer(CONFIG)
ROUTER = ActivityRouterDialog(RECOGNIZER)
BOT = SkillBot(CONVERSATION_STATE, ROUTER)


# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
Ejemplo n.º 15
0
 def __init__(self):
     self.claims_identity = None
     ChannelServiceHandler.__init__(self, SimpleCredentialProvider("", ""),
                                    AuthenticationConfiguration())
Ejemplo n.º 16
0
CONFIG = DefaultConfig()

# Create MemoryStorage and ConversationState.
MEMORY = MemoryStorage()
CONVERSATION_STATE = ConversationState(MEMORY)

# Create the conversationIdFactory.
CONVERSATION_ID_FACTORY = SkillConversationIdFactory(MEMORY)

# Create the credential provider.
CREDENTIAL_PROVIDER = SimpleCredentialProvider(CONFIG.APP_ID,
                                               CONFIG.APP_PASSWORD)

VALIDATOR = AllowedCallersClaimsValidator(CONFIG).claims_validator
AUTH_CONFIG = AuthenticationConfiguration(claims_validator=VALIDATOR)

# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(
    app_id=CONFIG.APP_ID,
    app_password=CONFIG.APP_PASSWORD,
    auth_configuration=AUTH_CONFIG,
)
ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE)

ADAPTER.use(SsoSaveStateMiddleware(CONVERSATION_STATE))

# Create the skill client.
SKILL_CLIENT = SkillHttpClient(CREDENTIAL_PROVIDER, CONVERSATION_ID_FACTORY)
Ejemplo n.º 17
0
from aiohttp import web
from aiohttp.web import Request, Response

from botframework.connector.auth import AuthenticationConfiguration, SimpleCredentialProvider
from botbuilder.core.integration import aiohttp_channel_service_routes, BotFrameworkHttpClient
from botbuilder.schema import Activity

from config import DefaultConfig
from routing_id_factory import RoutingIdFactory
from routing_handler import RoutingHandler

CONFIG = DefaultConfig()
CREDENTIAL_PROVIDER = SimpleCredentialProvider(CONFIG.APP_ID,
                                               CONFIG.APP_PASSWORD)
CLIENT = BotFrameworkHttpClient(CREDENTIAL_PROVIDER)
AUTH_CONFIG = AuthenticationConfiguration()

TO_URI = CONFIG.NEXT
SERVICE_URL = CONFIG.SERVICE_URL

FACTORY = RoutingIdFactory()

ROUTING_HANDLER = RoutingHandler(FACTORY, CREDENTIAL_PROVIDER, AUTH_CONFIG)


async def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)
Ejemplo n.º 18
0
            timestamp=datetime.utcnow(),
            type=ActivityTypes.trace,
            value=f"{error}",
            value_type="https://www.botframework.com/schemas/error",
        )
        # Send a trace activity, which will be displayed in Bot Framework Emulator
        await context.send_activity(trace_activity)


ADAPTER.on_turn_error = on_error

# Create the Bot
BOT = RootBot(CONVERSATION_STATE, SKILL_CONFIG, ID_FACTORY, CLIENT, CONFIG)

SKILL_HANDLER = SkillHandler(ADAPTER, BOT, ID_FACTORY, CREDENTIAL_PROVIDER,
                             AuthenticationConfiguration())


# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers[
        "Authorization"] if "Authorization" in req.headers else ""

    try: