You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "KristiDodaj (via GitHub)" <gi...@apache.org> on 2026/10/20 02:36:38 UTC
[PR] feat(reports): add native Microsoft Teams alert notifications [superset]
KristiDodaj opened a new pull request, #45508:
URL: https://github.com/apache/superset/pull/45508
### SUMMARY
Add Microsoft Teams as an optional notification destination for attachment-free alerts.
Administrators configure a single tenant, bot credentials, and approved standard channels. Users select a destination in the alert editor. Each notification creates a new channel post containing the alert name, optional description, and optional link to Superset.
The integration is disabled by default behind `ALERT_REPORT_TEAMS` and uses the optional `teams` dependency extra. Authenticated installation callbacks maintain routing information. Removing the bot disables delivery until it is reinstalled.
Includes recipient validation, bounded retries, delivery error handling, setup documentation, and automated tests.
Initial scope excludes scheduled reports, private/shared channels, direct messages, file attachments, and interactive cards.
Related discussion: https://github.com/apache/superset/discussions/45307
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Before: Microsoft Teams is not available as a notification destination.
After: Users can select an administrator-approved Teams destination and receive alert cards in its channel.
**Teams destination selection**
<img width="1000" alt="Selecting an approved Microsoft Teams destination in the Superset alert editor" src="https://github.com/user-attachments/assets/b0c02bb8-7604-4453-aa35-eed7a61c4bcd" />
**Delivered alerts, including successful delivery after bot reinstallation**
<img width="1000" alt="Separate alert posts delivered by Superset to the test Microsoft Teams channel" src="https://github.com/user-attachments/assets/dcb381c2-0005-42b6-be7f-246be843fe32" />
Credentials are configured server-side, not through an administrator UI.
### TESTING INSTRUCTIONS
1. Install the `teams` extra on the web server and Celery worker.
2. Enable `ALERT_REPORT_TEAMS` and configure the tenant, bot credentials, and approved destinations.
3. Apply the migration and configure the bot's HTTPS callback.
4. Install the bot in an approved team.
5. Create an alert with attachments disabled and select a Teams destination.
6. Trigger two deliveries and confirm they appear as separate channel posts.
7. Remove the bot and confirm delivery fails clearly. Reinstall it and confirm delivery recovers.
Validation completed locally:
- 308 focused backend tests passed after test cleanup.
- Frontend component tests and TypeScript checks passed during feature validation. The browser create/edit flow passed with local selector fixes that are not included in this draft yet.
- Migration upgrade, downgrade, and re-upgrade passed.
- Live Celery delivery to a non-default standard channel passed.
- Delivery after web and worker restarts passed.
- Fresh removal and reinstallation callbacks passed, including delivery failure and recovery.
- Pre-commit was run across all branch-changed files. Mypy, frontend type checking, formatting, linting, feature-flag documentation sync, and workflow security checks passed. The custom Pylint hook could not load `superset.extensions.pylint` in the local hook environment, so that check remains unverified.
### ADDITIONAL INFORMATION
- [ ] Has associated issue:
Related discussion: https://github.com/apache/superset/discussions/45307
- [x] Required feature flags: `ALERT_REPORTS`, `ALERT_REPORT_TEAMS`
- [x] Changes UI
- [x] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
- [ ] Migration is atomic, supports rollback & is backwards-compatible
- [x] Confirm DB migration upgrade and downgrade tested
- [ ] Runtime estimates and downtime expectations provided
- [x] Introduces new feature or API
- [ ] Removes existing feature or API
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4372250567
##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -1906,6 +1890,20 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
return false;
}
+ const hasTeamsRecipients = notificationSettings.some(
+ setting => setting.method === NotificationMethodOption.Teams,
+ );
+ const invalidTeamsRecipients =
+ hasTeamsRecipients &&
+ (!teamsSupported ||
+ !teamsIntegrationAvailable ||
Review Comment:
Once an existing Teams alert has been saved, turning off `ALERT_REPORT_TEAMS`, removing the Teams config, or running without the optional SDK makes `teamsIntegrationAvailable` false, so `checkNotificationSettings` returns false and Save stays disabled for that alert. The backend deliberately allows unchanged-delivery edits and deactivation in that state (`_teams_delivery_changed` in `update.py`), but the modal blocks them, so an operator can't pause the alert or fix its description from the UI. Should the availability check only reject Teams recipients that were added or changed, so pausing and metadata edits still save?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4372175533
##########
superset/commands/report/update.py:
##########
@@ -131,7 +131,7 @@ def _normalize_recipients(recipients: Any) -> list[tuple[str, str]]:
config = json.loads(config)
except json.JSONDecodeError:
pass
- if isinstance(config, dict):
+ if recipient_type == ReportRecipientType.EMAIL and isinstance(config, dict):
Review Comment:
Figured those fields were irrelevant for Slack/Webhook, but missed that the modal still sends them as empty values. Fixed so only Teams is excluded from normalization, preserving the existing behaviour for the other methods
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4378399916
##########
superset-frontend/src/features/alerts/AlertReportModal.test.tsx:
##########
@@ -4662,3 +4665,429 @@ test('global attachment policy hides both the alert toggle and attachment contro
);
}
});
+
+test('Changing the first Teams method preserves the following destination', async () => {
+ mockNotificationMethods = ['Email', 'Teams'];
+ fetchMock.get('glob:*/api/v1/report/92', {
+ result: {
+ ...generateMockPayload(true),
+ id: 92,
+ report_format: 'NONE',
+ recipients: [
+ { id: 1, type: 'Teams', recipient_config_json: '{"target":"ops"}' },
+ { id: 2, type: 'Teams', recipient_config_json: '{"target":"finance"}' },
+ ],
+ },
+ });
+ fetchMock.get(
+ 'glob:*/api/v1/report/teams_destinations/',
+ {
+ result: [
+ { key: 'ops', label: 'Operations', available: true },
+ { key: 'finance', label: 'Finance', available: false },
+ ],
+ },
+ { name: 'teams-destinations' },
+ );
+ fetchMock.put(
+ 'glob:*/api/v1/report/92',
+ { id: 92, result: {} },
+ { name: 'save-teams' },
+ );
+ try {
+ render(
+ <AlertReportModal
+ {...generateMockedProps(false, true)}
+ alert={{ ...validAlert, id: 92 }}
+ />,
+ {
+ useRedux: true,
+ initialState: { user: adminUser },
+ },
+ );
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /save/i })).toBeEnabled(),
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(
+ await screen.findByText('Finance (Bot installation required)'),
+ ).toBeInTheDocument();
+ expect(
+ screen.getAllByRole('combobox', { name: 'Teams destination' }),
+ ).toHaveLength(2);
+ expect(
+ screen.getByText(/Add another notification method/i),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByTestId('contents-panel'));
+ const attachmentToggle = screen.getByRole('switch', {
+ name: 'Include attachment',
+ });
+ await userEvent.click(attachmentToggle);
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /save/i })).toBeDisabled(),
+ );
+ await userEvent.click(attachmentToggle);
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /save/i })).toBeEnabled(),
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(
+ screen.getByText('Finance (Bot installation required)'),
+ ).toBeInTheDocument();
+ await userEvent.click(
+ screen.getAllByRole('combobox', { name: /^Delivery method/ })[0],
+ );
+ await userEvent.click(await screen.findByText('Email'));
+ await addAsyncSelectValue(
+ /email recipients/i,
+ 'owner@example.com',
+ reportUsersEndpoint,
+ );
+ await userEvent.click(screen.getByRole('button', { name: /save/i }));
+ await waitFor(() =>
+ expect(fetchMock.callHistory.calls('save-teams')).toHaveLength(1),
+ );
+ const [call] = fetchMock.callHistory.calls('save-teams');
+ expect(JSON.parse(call.options.body as string)).toMatchObject({
+ report_format: 'NONE',
+ recipients: [
+ {
+ type: 'Email',
+ recipient_config_json: {
+ target: 'owner@example.com',
+ ccTarget: '',
+ bccTarget: '',
+ },
+ },
+ { type: 'Teams', recipient_config_json: { target: 'finance' } },
+ ],
+ });
+ expect(JSON.parse(call.options.body as string).recipients).toEqual([
+ {
+ type: 'Email',
+ recipient_config_json: {
+ target: 'owner@example.com',
+ ccTarget: '',
+ bccTarget: '',
+ },
+ },
+ { type: 'Teams', recipient_config_json: { target: 'finance' } },
+ ]);
+ } finally {
+ fetchMock.removeRoute('teams-destinations');
+ fetchMock.removeRoute('save-teams');
+ }
+});
+
+test.each([
+ ['an active alert', true, false],
+ ['an inactive alert', false, false],
+ ['pausing an alert', true, true],
+])('Teams unavailable integration allows %s', async (_, active, pause) => {
+ const id = pause ? 193 : active ? 194 : 195;
+ mockNotificationMethods = ['Email', 'Slack'];
+ fetchMock.get(`glob:*/api/v1/report/${id}`, {
+ result: {
+ ...generateMockPayload(true),
+ id,
+ active,
+ report_format: 'NONE',
+ recipients: [
+ {
+ id: 1,
+ type: 'Teams',
+ recipient_config_json: '{"target":"removed-key"}',
+ },
+ { id: 2, type: 'Slack', recipient_config_json: { target: 'C123' } },
+ ],
+ },
+ });
+ fetchMock.get(
+ 'glob:*/api/v1/report/teams_destinations/',
+ { result: [] },
+ { name: 'teams-unavailable' },
+ );
+ fetchMock.put(
+ `glob:*/api/v1/report/${id}`,
+ { id, result: {} },
+ {
+ name: 'teams-unavailable-save',
+ },
+ );
+ try {
+ render(
+ <AlertReportModal
+ {...generateMockedProps(false, true)}
+ alert={{ ...validAlert, id }}
+ />,
+ { useRedux: true, initialState: { user: adminUser } },
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(
+ await screen.findByText('removed-key (Unavailable)'),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByText(/Teams delivery is unavailable/),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByTestId('general-information-panel'));
+ const description = screen.getByPlaceholderText(
+ /include description to be sent with alert/i,
+ );
+ await userEvent.clear(description);
+ await userEvent.type(description, 'Updated description');
+ if (pause) await userEvent.click(screen.getByRole('switch'));
+ const save = screen.getByRole('button', { name: /save/i });
+ await waitFor(() => expect(save).toBeEnabled());
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ const slackTarget = screen.getByTestId('recipients');
+ fireEvent.change(slackTarget, { target: { value: 'C456' } });
+ await waitFor(() => expect(save).toBeDisabled());
+ fireEvent.change(slackTarget, { target: { value: 'C123' } });
+ await waitFor(() => expect(save).toBeEnabled());
+ await userEvent.click(save);
+ await waitFor(() =>
+ expect(
+ fetchMock.callHistory.calls('teams-unavailable-save'),
+ ).toHaveLength(1),
+ );
+ const [call] = fetchMock.callHistory.calls('teams-unavailable-save');
+ expect(JSON.parse(call.options.body as string)).toMatchObject({
+ active: pause ? false : active,
+ description: 'Updated description',
+ report_format: 'NONE',
+ recipients: [
+ { type: 'Teams', recipient_config_json: { target: 'removed-key' } },
+ {
+ type: 'Slack',
+ recipient_config_json: {
+ target: 'C123',
+ ccTarget: '',
+ bccTarget: '',
+ },
+ },
+ ],
+ });
+ } finally {
+ fetchMock.removeRoute(`glob:*/api/v1/report/${id}`);
+ fetchMock.removeRoute('teams-unavailable');
+ fetchMock.removeRoute('teams-unavailable-save');
+ }
+});
+
+test('Teams unavailable saved keys can be replaced without losing inactive state', async () => {
+ mockNotificationMethods = ['Email', 'Teams'];
+ fetchMock.get('glob:*/api/v1/report/94', {
+ result: {
+ ...generateMockPayload(true),
+ id: 94,
+ active: false,
+ report_format: 'NONE',
+ recipients: [
+ {
+ id: 1,
+ type: 'Teams',
+ recipient_config_json: { target: 'removed-key' },
+ },
+ ],
+ },
+ });
+ fetchMock.get(
+ 'glob:*/api/v1/report/teams_destinations/',
+ {
+ result: [{ key: 'ops', label: 'Operations', available: false }],
+ },
+ { name: 'teams-replacement' },
+ );
+ fetchMock.put(
+ 'glob:*/api/v1/report/94',
+ { id: 94, result: {} },
+ { name: 'teams-replacement-save' },
+ );
+ try {
+ render(
+ <AlertReportModal
+ {...generateMockedProps(false, true)}
+ alert={{ ...validAlert, id: 94 }}
+ />,
+ {
+ useRedux: true,
+ initialState: { user: adminUser },
+ },
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(
+ await screen.findByText('removed-key (Unavailable)'),
+ ).toBeInTheDocument();
+ await userEvent.click(
+ screen.getByRole('combobox', { name: 'Teams destination' }),
+ );
+ await userEvent.click(
+ await screen.findByText('Operations (Bot installation required)'),
+ );
+ expect(
+ screen.queryByText(/This saved Teams destination is unavailable/),
+ ).not.toBeInTheDocument();
+ await userEvent.click(screen.getByRole('button', { name: /save/i }));
+ await waitFor(() =>
+ expect(
+ fetchMock.callHistory.calls('teams-replacement-save'),
+ ).toHaveLength(1),
+ );
+ const [call] = fetchMock.callHistory.calls('teams-replacement-save');
+ const payload = JSON.parse(call.options.body as string);
+ expect(payload.active).toBe(false);
+ expect(payload.report_format).toBe('NONE');
+ expect(payload.recipients).toEqual([
+ { type: 'Teams', recipient_config_json: { target: 'ops' } },
+ ]);
+ } finally {
+ fetchMock.removeRoute('teams-replacement');
+ fetchMock.removeRoute('teams-replacement-save');
+ }
+});
+
+test('Teams saved recipients stay visible and replaceable when the optional SDK is unavailable', async () => {
+ mockNotificationMethods = ['Email'];
+ fetchMock.get('glob:*/api/v1/report/95', {
+ result: {
+ ...generateMockPayload(true),
+ id: 95,
+ report_format: 'NONE',
+ recipients: [
+ { id: 1, type: 'Teams', recipient_config_json: '{"target":"ops"}' },
+ ],
+ },
+ });
+ fetchMock.get(
+ 'glob:*/api/v1/report/teams_destinations/',
+ { result: [] },
+ { name: 'teams-sdk-missing' },
+ );
+ try {
+ render(
+ <AlertReportModal
+ {...generateMockedProps(false, true)}
+ alert={{ ...validAlert, id: 95 }}
+ />,
+ {
+ useRedux: true,
+ initialState: { user: adminUser },
+ },
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(await screen.findByText('ops (Unavailable)')).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ /Teams delivery is unavailable.*optional Teams dependency/,
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('combobox', { name: 'Teams destination' }),
+ ).toBeDisabled();
+ const save = screen.getByRole('button', { name: /save/i });
+ await waitFor(() => expect(save).toBeEnabled());
+ await userEvent.click(screen.getByTestId('general-information-panel'));
+ await userEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(save).toBeDisabled());
+ await userEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(save).toBeEnabled());
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ await userEvent.click(
+ screen.getByRole('combobox', { name: /^Delivery method/ }),
+ );
+ await userEvent.click(await screen.findByText('Email'));
+ expect(
+ screen.queryByRole('combobox', { name: 'Teams destination' }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('ops (Unavailable)')).not.toBeInTheDocument();
+ } finally {
+ fetchMock.removeRoute('teams-sdk-missing');
+ }
+});
+
+test.each(['PNG', 'CSV'])(
+ 'Teams edits normalize saved %s format when attachments are globally disabled',
+ async reportFormat => {
+ mockNotificationMethods = ['Email', 'Teams'];
+ fetchMock.removeRoute(configurationEndpoint);
+ fetchMock.get(
+ configurationEndpoint,
+ {
+ result: { ...mockReportConfiguration, alerts_attach_reports: false },
+ },
+ { name: configurationEndpoint },
+ );
+ fetchMock.get('glob:*/api/v1/report/96', {
Review Comment:
Both parameterized cases register `GET glob:*/api/v1/report/96` without a name, and nothing removes it: the `finally` only removes the Teams routes and the `afterEach` list doesn't include it. fetch-mock serves the first matching route, so the CSV case loads the PNG payload from the PNG case, and a regression that normalizes a saved PNG format but leaves CSV unchanged would still pass both. Could each case use a distinct report id or a named route removed in `finally`, so the CSV case really loads `report_format: 'CSV'`?
##########
.github/workflows/superset-python-unittest.yml:
##########
@@ -65,6 +65,10 @@ jobs:
uses: $/.github/actions/setup-backend/
with:
python-version: ${{ matrix.python-version }}
+ - name: Install optional Teams SDK for authentication and delivery tests
+ run: |
+ uv pip install --system -e '.[teams]'
Review Comment:
This installs `.[teams]` without the `requirements/development.txt` constraint, and `teams` isn't in `requirements/development.in`. `microsoft-teams-apps==2.1.1` requires `opentelemetry-api>=1.41.0` and `pydantic-settings>=2.11.0`, while the lock pins `1.39.1` and `2.10.1`, and `fastapi`/`msal` aren't locked at all. So this step upgrades locked packages and resolves new ones at whatever is latest before the whole unit suite runs, which means CI passes or fails against an environment no locked install uses, and `check-python-deps` can't see the drift. Would adding `teams` to `development.in` and regenerating the lock (instead of this ad hoc install) work here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4373127845
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,545 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask registers its route once at startup. Each request creates a fresh SDK
+ authentication server; its handler runs to completion in an operation-scoped
+ event loop. No SDK App, outbound clients, tasks, or separate server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
+ or not isinstance(action, str)
+ or action not in actions
+ ):
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ The SDK's HttpServer uses PyJWKClient, whose network responses close within
+ its scoped fetch. It creates no persistent HTTP clients. Keep construction,
+ authentication, and adapter cleanup within the same event loop; asyncio.run
+ closes that loop on success and failure. SDK response bodies are never exposed.
+ """
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = _FlaskServerAdapter()
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server = HttpServer(adapter, messaging_endpoint=EVENTS_PATH)
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ if adapter.handler is None:
+ return TeamsEventResult(500)
+ response: HttpResponse = await adapter.handler(
+ HttpRequest(body=body, headers=headers)
+ )
+ if response["status"] != 200:
+ return TeamsEventResult(response["status"])
+ return result
+ finally:
+ await adapter.stop()
+
+ return asyncio.run(process())
+
+
+# Count every send, including the single 401 replay, against the same retry bound.
+_DELIVERY_ATTEMPTS = 4
+_DELIVERY_TIMEOUT = 60.0
+_DELIVERY_REQUEST_TIMEOUT = 10.0
+
+
+class TeamsDeliveryError(Exception):
+ """Sanitized delivery outcome for mapping to existing notification exceptions."""
+
+ def __init__(
+ self, category: Literal["authorization", "transient", "parameter"]
+ ) -> None:
+ """Expose a stable message without response bodies, SQL, tokens, or URLs."""
+ self.category = category
+ messages = {
+ "authorization": "Teams bot authorization failed",
+ "transient": "Teams alert delivery temporarily unavailable",
+ "parameter": "Teams alert delivery was rejected",
+ }
+ super().__init__(messages[category])
+
+
+class TeamsTransportError(Exception):
+ """An HTTP failure carrying only the status and Microsoft's retry metadata."""
+
+ def __init__(
+ self,
+ status: int | None = None,
+ headers: httpx.Headers
+ | requests.structures.CaseInsensitiveDict[str]
+ | None = None,
+ ) -> None:
+ """Retain only retry headers; never retain a response body or request token."""
+ super().__init__("Teams transport request failed")
+ self.status = status
+ self.retry_after = headers.get("Retry-After") if headers is not None else None
+ self.retry_after_ms = (
+ headers.get("x-ms-retry-after-ms") if headers is not None else None
+ )
+
+
+class TeamsTransport(Protocol):
+ """Replaceable operation-scoped transport; retries live outside SDK calls."""
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new channel root post containing the card."""
+ ...
+
+ async def refresh_auth(self) -> None:
+ """Invalidate cached authentication before a single 401 replay."""
+ ...
+
+
+def _remaining(deadline: float) -> float:
+ """Bound each request by its timeout and remaining delivery budget."""
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise TeamsTransportError()
+ return min(_DELIVERY_REQUEST_TIMEOUT, remaining)
+
+
+class _AuthHttpClient:
+ """MSAL HTTP interface backed by a caller-owned, timeout-bounded session."""
+
+ def __init__(self, session: requests.Session, deadline: float) -> None:
+ """Keep OAuth traffic within the same operation as the channel post."""
+ self.session = session
+ self.deadline = deadline
+
+ def get(self, url: str, **kwargs: Any) -> requests.Response:
+ """Fetch MSAL metadata without leaving a response open."""
+ return self._request("GET", url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> requests.Response:
+ """Acquire tokens without leaving a response open."""
+ return self._request("POST", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
+ """Use normal serialization, explicit timeouts, and sanitized retry errors."""
+ kwargs["timeout"] = _remaining(self.deadline)
+ response = self.session.request(method, url, **kwargs)
+ try:
+ _remaining(self.deadline)
+ # requests eagerly reads responses; MSAL can still read cached JSON
+ # after close. Closing here also covers retryable OAuth errors.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise TeamsTransportError(response.status_code, response.headers)
+ return response
+ finally:
+ response.close()
+
+
+class _ChannelConversationParams(CreateConversationParams):
+ """Include the connector's group flag, absent from the SDK base parameter model."""
+
+ is_group: Literal[True] = True
+
+
+class _SDKTeamsTransport:
+ """Use the SDK create-conversation API with shared, explicitly owned resources."""
+
+ def __init__(
+ self,
+ config: TeamsConfig,
+ service_url: str,
+ http: Client,
+ auth_http: _AuthHttpClient,
+ deadline: float,
+ ) -> None:
+ """Prepare the SDK without constructing a full App or starting a server."""
+ self.config = config
+ self.http = http
+ self.auth_http = auth_http
+ self.deadline = deadline
+ self.auth: ConfidentialClientApplication | None = None
+ self.api = ApiClient(service_url, http)
+
+ def _authenticate(self) -> None:
+ """Acquire a bot token without exposing identity-provider errors."""
+ if self.http.token:
+ return
+ if self.auth is None:
+ self.auth = ConfidentialClientApplication(
+ self.config.application_id,
+ client_credential=self.config.credential,
+ authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
+ http_client=self.auth_http,
+ instance_discovery=False,
+ )
+ result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
+ token = result.get("access_token")
+ if not isinstance(token, str) or not token:
+ status = (
+ 503
+ if result.get("error") in {"temporarily_unavailable", "server_error"}
+ else 401
+ )
+ raise TeamsTransportError(status)
+ self.http.token = token
+
+ async def refresh_auth(self) -> None:
+ """Invalidate MSAL app tokens so the next request acquires a fresh token."""
+ if self.auth is not None:
+ self.auth.remove_tokens_for_client()
+ self.http.token = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new conversation with an initial card, never reply to a thread."""
+ try:
+ self._authenticate()
+ self.http.http.timeout = httpx.Timeout(_remaining(self.deadline))
+ await self.api.conversations.create(
+ _ChannelConversationParams(
+ tenant_id=self.config.tenant_id,
+ channel_data={
+ "tenant": {"id": self.config.tenant_id},
+ "team": {"id": destination.team_id},
+ "channel": {"id": destination.channel_id},
+ },
+ activity=MessageActivityInput(
+ attachments=[
+ Attachment(
+ content_type="application/vnd.microsoft.card.adaptive",
+ content=card,
+ )
+ ]
+ ),
+ )
+ )
+ except httpx.HTTPStatusError as ex:
+ error = TeamsTransportError(ex.response.status_code, ex.response.headers)
+ await ex.response.aclose()
+ raise error from None
+ except (httpx.RequestError, requests.RequestException):
Review Comment:
Every `httpx.RequestError` becomes a status-less `TeamsTransportError`, and `_deliver_with_retries` treats that as retryable. That includes `ReadTimeout`/`ReadError`/`RemoteProtocolError`, which fire after the conversation-create POST was already sent. That call has no idempotency key, so if Teams accepts the post but responds slower than the 10s request timeout, the loop reposts and the channel can get up to four identical alert cards (`delivery_test.py` asserts four posts for status `None`). The Slack write path only retries errors that cannot duplicate an accepted write (`superset/utils/slack.py`, `is_retryable_slack_transport_error`). Should only pre-send failures (e.g. connect errors) be retried here, with read/protocol errors raised as a non-retried delivery failure?
##########
tests/unit_tests/integrations/teams/teams_api_test.py:
##########
@@ -0,0 +1,832 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Exercise the real Teams SDK authentication boundary and Flask persistence."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import importlib.util
+from collections.abc import Callable
+from copy import deepcopy
+from datetime import datetime, timedelta, timezone
+from io import BytesIO
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import patch
+
+import jwt
+import pytest
+from cryptography.hazmat.primitives.asymmetric import rsa
+from flask import current_app, Flask, Response
+from flask.testing import FlaskClient
+from sqlalchemy.engine import Engine
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import api as teams_api
+from superset.integrations.teams.config import parse_teams_config
+from superset.integrations.teams.models import TeamsInstallation
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.utils import json
+
+if importlib.util.find_spec("microsoft_teams") is None:
+ pytest.skip("Optional Teams SDK is not installed", allow_module_level=True)
+
+teams_adapter = importlib.import_module("superset.integrations.teams.adapter")
+PATH = "/api/v1/teams/events/"
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+OTHER = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+SERVICE_URL = "https://smba.trafficmanager.net/amer/"
+
+
+@pytest.fixture(scope="module")
+def signing_key() -> rsa.RSAPrivateKey:
+ """Sign real SDK-validated tokens without contacting Microsoft's JWKS service."""
+ return rsa.generate_private_key(public_exponent=65537, key_size=2048)
+
+
+@pytest.fixture(autouse=True)
+def trusted_signing_key(
+ monkeypatch: pytest.MonkeyPatch, signing_key: rsa.RSAPrivateKey
+) -> None:
+ """Replace only key discovery; the SDK verifies signature and claims itself."""
+ monkeypatch.setattr(
+ jwt.PyJWKClient,
+ "get_signing_key_from_jwt",
+ lambda self, token: SimpleNamespace(key=signing_key.public_key()),
+ )
+
+
+@pytest.fixture
+def auth_headers(signing_key: rsa.RSAPrivateKey) -> Callable[..., dict[str, str]]:
+ """Build connector JWTs with optional invalid claims or signing key."""
+
+ def sign(
+ claims: dict[str, Any] | None = None,
+ key: rsa.RSAPrivateKey | None = None,
+ ) -> dict[str, str]:
+ """Sign a token so failures exercise the SDK's real validator."""
+ now = datetime.now(timezone.utc)
+ payload = {
+ "aud": APPLICATION,
+ "iss": "https://api.botframework.com",
+ "iat": int(now.timestamp()),
+ "nbf": int(now.timestamp()),
+ "exp": int((now + timedelta(hours=1)).timestamp()),
+ "serviceurl": SERVICE_URL,
+ }
+ payload.update(claims or {})
+ return {
+ "Authorization": "Bearer "
+ + jwt.encode(payload, key or signing_key, algorithm="RS256")
+ }
+
+ return sign
+
+
+@pytest.fixture
+def installation() -> dict[str, Any]:
+ """An installationUpdate event from a standard team channel."""
+ return {
+ "type": "installationUpdate",
+ "action": "add",
+ "id": "event-1",
+ "timestamp": "2026-10-01T12:00:00Z",
+ "serviceUrl": SERVICE_URL,
+ "channelId": "msteams",
+ "from": {"id": "29:installer"},
+ "recipient": {"id": f"28:{APPLICATION}"},
+ "conversation": {
+ "id": "channel-1",
+ "conversationType": "channel",
+ "tenantId": TENANT,
+ },
+ "channelData": {
+ "tenant": {"id": TENANT},
+ "team": {"id": "team-1"},
+ "channel": {"id": "channel-1", "type": "standard"},
+ },
+ }
+
+
+@pytest.fixture
+def teams_client(
+ teams_config: dict[str, Any],
+ teams_engine: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+) -> FlaskClient:
+ """Mount the callback in Flask with real CSRF enforcement and SQLAlchemy."""
+ app = Flask(__name__)
+ app.config.update(
+ TESTING=True,
+ SECRET_KEY="test-callback-key", # noqa: S106
+ WTF_CSRF_ENABLED=True,
+ FEATURE_FLAGS={"ALERT_REPORT_TEAMS": True},
+ ALERT_REPORTS_TEAMS=teams_config,
+ )
+ monkeypatch.setattr(teams_api, "db", SimpleNamespace(engine=teams_engine))
+ monkeypatch.setattr(
+ teams_api.feature_flag_manager,
+ "is_feature_enabled",
+ lambda name: current_app.config["FEATURE_FLAGS"].get(name, False),
+ )
+ teams_api.csrf.init_app(app)
+ teams_api.register_teams_api(app)
+
+ @app.post("/csrf-control")
+ def csrf_control() -> Response:
+ """An unrelated route must remain CSRF protected."""
+ return Response(status=200)
+
+ return app.test_client()
+
+
+def test_callback_persists_only_approved_metadata(
+ teams_client: FlaskClient,
+ teams_engine: Engine,
+ teams_config: dict[str, Any],
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+) -> None:
+ before = deepcopy(teams_config)
+ response = teams_client.post(PATH, json=installation, headers=auth_headers())
+ assert response.status_code == 200
+ assert response.data == b""
+ with Session(teams_engine) as session:
+ persisted = session.query(TeamsInstallation).one()
+ assert persisted.service_url == SERVICE_URL
+ assert persisted.active
+ assert str(persisted.tenant_id) == TENANT
+ assert str(persisted.application_id) == APPLICATION
+ assert persisted.team_id == "team-1"
+ assert teams_config == before
+ assert b"deployment-secret" not in response.data
+
+
+@pytest.mark.parametrize(
+ "authentication",
+ [
+ "missing",
+ "malformed",
+ "bad-signature",
+ "wrong-audience",
+ "expired",
+ "wrong-issuer",
+ "missing-serviceurl",
+ "mismatched-serviceurl",
+ ],
+)
+def test_invalid_authentication_never_opens_database_session(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ authentication: str,
+) -> None:
+ if authentication == "missing":
+ headers = {}
+ elif authentication == "malformed":
+ headers = {"Authorization": "Bearer not-a-jwt"}
+ elif authentication == "bad-signature":
+ headers = auth_headers(
+ key=rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ )
+ else:
+ claims = {
+ "wrong-audience": {"aud": OTHER},
+ "expired": {"exp": 1},
+ "wrong-issuer": {"iss": "https://untrusted.example"},
+ "missing-serviceurl": {"serviceurl": None},
+ "mismatched-serviceurl": {
+ "serviceurl": "https://smba.trafficmanager.net/other/"
+ },
+ }
+ headers = auth_headers(claims[authentication])
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(PATH, json=installation, headers=headers)
+ assert response.status_code == 401
+ assert response.data == b""
+ session.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "mismatch",
+ [
+ "tenant",
+ "conversation-tenant",
+ "token-tenant",
+ "recipient",
+ "team",
+ "personal",
+ "groupChat",
+ "private",
+ "shared",
+ "private-team",
+ "shared-team",
+ ],
+)
+def test_authenticated_events_must_match_deployment_scope(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ mismatch: str,
+) -> None:
+ claims = {}
+ if mismatch == "tenant":
+ installation["channelData"]["tenant"]["id"] = OTHER
+ elif mismatch == "conversation-tenant":
+ installation["conversation"]["tenantId"] = OTHER
+ elif mismatch == "token-tenant":
+ claims = {"tid": OTHER}
+ elif mismatch == "recipient":
+ installation["recipient"]["id"] = f"28:{OTHER}"
+ elif mismatch == "team":
+ installation["channelData"]["team"]["id"] = "unapproved-team"
+ elif mismatch in {"personal", "groupChat"}:
+ installation["conversation"]["conversationType"] = mismatch
+ elif mismatch in {"private", "shared"}:
+ installation["channelData"]["channel"]["type"] = mismatch
+ else:
+ installation["channelData"]["team"]["teamType"] = (
+ "privateChannel" if mismatch == "private-team" else "sharedChannel"
+ )
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(
+ PATH, json=installation, headers=auth_headers(claims)
+ )
+ assert response.status_code == 403
+ session.assert_not_called()
+
+
+def test_entra_tokens_cannot_bypass_signed_service_url_binding(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+) -> None:
+ # The SDK also supports Agent 365 tokens; this notification bot accepts only
+ # connector tokens whose signed serviceurl claim binds the installation URL.
+ headers = auth_headers(
+ {
+ "iss": f"https://login.microsoftonline.com/{TENANT}/v2.0",
+ "tid": TENANT,
+ "azp": "5a807f24-c9de-44ee-a3a7-329e88a00ffc",
+ "serviceurl": None,
+ }
+ )
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(PATH, json=installation, headers=headers)
+ assert response.status_code == 403
+ session.assert_not_called()
+
+
+def test_tokens_without_expiration_are_rejected(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+) -> None:
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(
+ PATH, json=installation, headers=auth_headers({"exp": None})
+ )
+ assert response.status_code in (401, 403)
+ session.assert_not_called()
+
+
+@pytest.mark.parametrize("add_action", ["add", "add-upgrade"])
+@pytest.mark.parametrize("remove_action", ["remove", "remove-upgrade"])
+def test_repeated_events_removal_and_reinstallation(
+ teams_client: FlaskClient,
+ teams_engine: Engine,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ add_action: str,
+ remove_action: str,
+) -> None:
+ installation["action"] = add_action
+ headers = auth_headers()
+ for _ in range(2):
+ assert (
+ teams_client.post(PATH, json=installation, headers=headers).status_code
+ == 200
+ )
+ with Session(teams_engine) as session:
+ original = session.query(TeamsInstallation).one()
+ identity, created_on = original.id, original.created_on
+ installation["action"] = remove_action
+ for _ in range(2):
+ assert (
+ teams_client.post(PATH, json=installation, headers=headers).status_code
+ == 200
+ )
+ with Session(teams_engine) as session:
+ removed = session.query(TeamsInstallation).one()
+ assert removed.id == identity
+ assert not removed.active
+ installation["action"] = add_action
+ installation["timestamp"] = "2026-10-01T12:01:00Z"
+ refreshed = "https://smba.trafficmanager.net/emea/"
+ installation["serviceUrl"] = refreshed
+ for _ in range(2):
+ response = teams_client.post(
+ PATH, json=installation, headers=auth_headers({"serviceurl": refreshed})
+ )
+ assert response.status_code == 200
+ with Session(teams_engine) as session:
+ reinstalled = session.query(TeamsInstallation).one()
+ assert reinstalled.id == identity
+ assert reinstalled.created_on == created_on
+ assert reinstalled.active
+ assert reinstalled.service_url == refreshed
+
+
+def test_removal_retains_unknown_installation_tombstone(
+ teams_client: FlaskClient,
+ teams_engine: Engine,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+) -> None:
+ installation["action"] = "remove"
+ assert (
+ teams_client.post(PATH, json=installation, headers=auth_headers()).status_code
+ == 200
+ )
+ with Session(teams_engine) as session:
+ assert not session.query(TeamsInstallation).one().active
+
+
+@pytest.mark.parametrize(
+ "change",
+ [
+ "type",
+ "action",
+ "malformed-action",
+ "missing-service",
+ "missing-channel",
+ "missing-recipient",
+ "attachment",
+ ],
+)
+def test_unsupported_or_incomplete_events_do_not_persist(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ change: str,
+) -> None:
+ if change == "type":
+ installation["type"] = "message"
+ elif change == "action":
+ installation["action"] = "unknown"
+ elif change == "malformed-action":
+ installation["action"] = []
+ elif change == "missing-service":
+ installation.pop("serviceUrl")
+ elif change == "missing-channel":
+ installation.pop("channelId")
+ elif change == "missing-recipient":
+ installation.pop("recipient")
+ else:
+ installation["attachments"] = [{"contentType": "image/png"}]
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(PATH, json=installation, headers=auth_headers())
+ assert response.status_code == 400
+ session.assert_not_called()
+
+
+def test_session_cookie_does_not_authenticate_callback(
+ teams_client: FlaskClient, installation: dict[str, Any]
+) -> None:
+ with teams_client.session_transaction() as browser_session:
+ browser_session["_user_id"] = "1"
+ browser_session["_fresh"] = True
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(PATH, json=installation)
+ assert response.status_code == 401
+ session.assert_not_called()
+
+
+def test_csrf_exemption_is_only_for_callback(teams_client: FlaskClient) -> None:
+ # Without a CSRF exemption this would be 400 before SDK authentication.
+ assert teams_client.post(PATH, json={}).status_code == 401
+ assert teams_client.post("/csrf-control").status_code == 400
+ assert teams_client.get(PATH).status_code == 405
+
+
+@pytest.mark.parametrize(
+ "mode", ["disabled", "unconfigured", "invalid-config", "missing-sdk"]
+)
+def test_callback_fails_closed_without_sdk_or_configuration(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ mode: str,
+) -> None:
+ expected = 503
+ if mode == "disabled":
+ teams_client.application.config["FEATURE_FLAGS"]["ALERT_REPORT_TEAMS"] = False
+ expected = 404
+ elif mode == "unconfigured":
+ teams_client.application.config["ALERT_REPORTS_TEAMS"] = {}
+ elif mode == "invalid-config":
+ teams_client.application.config["ALERT_REPORTS_TEAMS"] = {
+ "credential": "deployment-secret"
+ }
+ with patch.dict("sys.modules", {"superset.integrations.teams.adapter": None}):
Review Comment:
The `sys.modules` patch applies to every parametrized mode, including `unconfigured`, so that case returns 503 from the SDK import failure even without the `config is None` guard in `teams_events`. If that guard were dropped, this test would still pass, while a deployment with the SDK installed and `ALERT_REPORTS_TEAMS = {}` would call `process_teams_event(None, ...)` and fail. Could the import-failure patch be limited to `missing-sdk`, so `unconfigured` runs with the SDK present and asserts 503 without invoking event processing?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4426551024
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,556 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask registers its route once at startup. Each request creates a fresh SDK
+ authentication server; its handler runs to completion in an operation-scoped
+ event loop. No SDK App, outbound clients, tasks, or separate server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
+ or not isinstance(action, str)
+ or action not in actions
+ ):
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ The SDK's HttpServer uses PyJWKClient, whose network responses close within
+ its scoped fetch. It creates no persistent HTTP clients. Keep construction,
+ authentication, and adapter cleanup within the same event loop; asyncio.run
+ closes that loop on success and failure. SDK response bodies are never exposed.
+ """
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = _FlaskServerAdapter()
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server = HttpServer(adapter, messaging_endpoint=EVENTS_PATH)
Review Comment:
I confirmed the SDK creates a JWKS client per server. Added server reuse per process with serialized callbacks and request cleanup
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4379234250
##########
.github/workflows/superset-python-unittest.yml:
##########
@@ -65,6 +65,10 @@ jobs:
uses: $/.github/actions/setup-backend/
with:
python-version: ${{ matrix.python-version }}
+ - name: Install optional Teams SDK for authentication and delivery tests
+ run: |
+ uv pip install --system -e '.[teams]'
Review Comment:
Agreed. Added teams to development.in, regenerated the lock, and removed the separate CI install
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-6461085103
### ⚠️ Possible DB migration conflict
@KristiDodaj the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4426546112
##########
superset/integrations/teams/validation.py:
##########
@@ -0,0 +1,95 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Shared Teams recipient rules for schedule saves and notification delivery."""
+
+from flask import current_app
+
+from superset.extensions import feature_flag_manager
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.reports.models import ReportDataFormat, ReportScheduleType
+from superset.utils import json
+
+
+class TeamsRecipientValidationError(ValueError):
+ """A field-specific error that never includes credentials or supplied values."""
+
+ def __init__(self, message: str, field: str = "recipients") -> None:
+ """Identify the schedule field that must be corrected."""
+ super().__init__(message)
+ self.field = field
+
+
+def validate_teams_recipient(
+ recipient_config: object,
+ schedule_type: str | None,
+ report_format: str | None,
+) -> tuple[TeamsConfig, TeamsDestination]:
+ """Require an enabled, configured, attachment-free alert and an approved key.
+
+ Accept deserialized command input or persisted recipient JSON. Installation
+ availability is deliberately checked only at delivery, so schedules may be
+ saved before a bot is installed. No SDK dependency or database access is needed.
+ """
+ if not feature_flag_manager.is_feature_enabled("ALERT_REPORT_TEAMS"):
+ raise TeamsRecipientValidationError("Teams alert delivery is disabled")
+ try:
+ config = parse_teams_config(current_app.config.get("ALERT_REPORTS_TEAMS", {}))
+ except ValueError:
+ raise TeamsRecipientValidationError(
+ "Invalid Teams deployment configuration"
+ ) from None
+ if config is None:
+ raise TeamsRecipientValidationError("Teams deployment is not configured")
+ if schedule_type != ReportScheduleType.ALERT:
+ raise TeamsRecipientValidationError(
+ "Teams recipients require an alert schedule", "type"
+ )
+ if report_format != ReportDataFormat.NONE:
+ raise TeamsRecipientValidationError(
+ "Teams recipients require disabled attachments (NONE format)",
+ "report_format",
+ )
+ try:
+ recipient = (
+ json.loads(recipient_config)
+ if isinstance(recipient_config, str)
+ else recipient_config
+ )
+ except (ValueError, TypeError):
+ raise TeamsRecipientValidationError(
+ "Invalid Teams recipient configuration"
+ ) from None
+ if (
+ not isinstance(recipient, dict)
+ or set(recipient) != {"target"}
+ or not isinstance(recipient["target"], str)
+ or not recipient["target"]
+ ):
+ raise TeamsRecipientValidationError(
+ "A configured Teams destination key is required"
+ )
+ try:
+ destination = config.get_destination(recipient["target"])
+ except ValueError:
+ raise TeamsRecipientValidationError(
Review Comment:
Wrapped the Teams validation messages and duplicate-key error in gettext, added them to the catalog, and added translation coverage
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4638106958
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,578 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from functools import lru_cache
+from threading import Lock
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask owns the listening server. SDK authentication is reused, while each
+ callback runs to completion in an operation-scoped event loop. No SDK App,
+ outbound clients, tasks, or separate listening server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if not isinstance(action, str) or action not in actions:
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+@lru_cache(maxsize=8)
+def _callback_server(
+ process_id: int, application_id: str, tenant_id: str
+) -> tuple[HttpServer, Lock]:
+ """Retain SDK signing-key caches per process and configured identity.
+
+ The process ID avoids inheriting a locked server when a worker forks.
+ The lock serializes use of the SDK's mutable on_request callback.
+ """
+ return HttpServer(_FlaskServerAdapter(), messaging_endpoint=EVENTS_PATH), Lock()
+
+
+_CALLBACK_LOCK_TIMEOUT = 1.0
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ Only the SDK server and its signing-key cache survive requests. Request
+ handlers and event loops are released after every callback, and no outbound
+ SDK client is created. Credentials and event bodies are not cache keys.
+ """
+ server, lock = _callback_server(
+ os.getpid(), config.application_id, config.tenant_id
+ )
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = server.adapter
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ if not _allowed_token(config, event):
+ result = TeamsEventResult(403)
+ elif body.get("type") != "installationUpdate":
+ result = TeamsEventResult(200)
+ else:
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ response: HttpResponse = await server.handle_request(
+ HttpRequest(body=body, headers=headers)
+ )
+ if response["status"] != 200:
+ return TeamsEventResult(response["status"])
+ return result
+ finally:
+ server.on_request = None
+ await adapter.stop()
+
+ if not lock.acquire(timeout=_CALLBACK_LOCK_TIMEOUT):
+ return TeamsEventResult(503)
+ try:
+ return asyncio.run(process())
+ finally:
+ lock.release()
+
+
+# Count every send, including the single 401 replay, against the same retry bound.
+_DELIVERY_ATTEMPTS = 4
+_DELIVERY_TIMEOUT = 60.0
+_DELIVERY_REQUEST_TIMEOUT = 10.0
+
+
+class TeamsDeliveryError(Exception):
+ """Sanitized delivery outcome for mapping to existing notification exceptions."""
+
+ def __init__(
+ self, category: Literal["authorization", "transient", "parameter", "unknown"]
+ ) -> None:
+ """Expose a stable message without response bodies, SQL, tokens, or URLs."""
+ self.category = category
+ messages = {
+ "authorization": "Teams bot authorization failed",
+ "transient": "Teams alert delivery temporarily unavailable",
+ "parameter": "Teams alert delivery was rejected",
+ "unknown": (
+ "Teams alert delivery could not be confirmed. "
+ "It may have been delivered"
+ ),
+ }
+ super().__init__(messages[category])
+
+
+class TeamsTransportError(Exception):
+ """Sanitized HTTP failure with explicit retry safety for status-less errors."""
+
+ def __init__(
+ self,
+ status: int | None = None,
+ headers: httpx.Headers
+ | requests.structures.CaseInsensitiveDict[str]
+ | None = None,
+ *,
+ retryable: bool = False,
+ ) -> None:
+ """Retain only retry headers; never retain a response body or request token."""
+ super().__init__("Teams transport request failed")
+ self.status = status
+ self.retryable = retryable
+ self.retry_after = headers.get("Retry-After") if headers is not None else None
+ self.retry_after_ms = (
+ headers.get("x-ms-retry-after-ms") if headers is not None else None
+ )
+
+
+class TeamsTransport(Protocol):
+ """Replaceable operation-scoped transport; retries live outside SDK calls."""
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new channel root post containing the card."""
+ ...
+
+ async def refresh_auth(self) -> None:
+ """Invalidate cached authentication before a single 401 replay."""
+ ...
+
+
+def _remaining(deadline: float) -> float:
+ """Bound each request by its timeout and remaining delivery budget."""
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise TeamsTransportError(retryable=True)
+ return min(_DELIVERY_REQUEST_TIMEOUT, remaining)
+
+
+class _AuthHttpClient:
+ """MSAL HTTP interface backed by a caller-owned, timeout-bounded session."""
+
+ def __init__(self, session: requests.Session, deadline: float) -> None:
+ """Keep OAuth traffic within the same operation as the channel post."""
+ self.session = session
+ self.deadline = deadline
+
+ def get(self, url: str, **kwargs: Any) -> requests.Response:
+ """Fetch MSAL metadata without leaving a response open."""
+ return self._request("GET", url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> requests.Response:
+ """Acquire tokens without leaving a response open."""
+ return self._request("POST", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
+ """Use normal serialization, explicit timeouts, and sanitized retry errors."""
+ kwargs["timeout"] = _remaining(self.deadline)
+ response = self.session.request(method, url, **kwargs)
+ try:
+ _remaining(self.deadline)
+ # requests eagerly reads responses; MSAL can still read cached JSON
+ # after close. Closing here also covers retryable OAuth errors.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise TeamsTransportError(response.status_code, response.headers)
+ return response
+ finally:
+ response.close()
+
+
+class _ChannelConversationParams(CreateConversationParams):
+ """Include the connector's group flag, absent from the SDK base parameter model."""
+
+ is_group: Literal[True] = True
+
+
+class _SDKTeamsTransport:
+ """Use the SDK create-conversation API with shared, explicitly owned resources."""
+
+ def __init__(
+ self,
+ config: TeamsConfig,
+ service_url: str,
+ http: Client,
+ auth_http: _AuthHttpClient,
+ deadline: float,
+ ) -> None:
+ """Prepare the SDK without constructing a full App or starting a server."""
+ self.config = config
+ self.http = http
+ self.auth_http = auth_http
+ self.deadline = deadline
+ self.auth: ConfidentialClientApplication | None = None
+ self.api = ApiClient(service_url, http)
+
+ def _authenticate(self) -> None:
+ """Acquire a bot token without exposing identity-provider errors."""
+ if self.http.token:
+ return
+ if self.auth is None:
+ self.auth = ConfidentialClientApplication(
+ self.config.application_id,
+ client_credential=self.config.credential,
+ authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
+ http_client=self.auth_http,
+ instance_discovery=False,
+ )
+ result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
Review Comment:
Addressed. MSAL discovery failures now report an authorization error
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-6292957525
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/45508?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 83.57%. Comparing base ([`99ecfe5`](https://app.codecov.io/gh/apache/superset/commit/99ecfe5801c4cbb79eedd475003b134b6ba7ff28?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`e48ef27`](https://app.codecov.io/gh/apache/superset/commit/e48ef27574d1eef6bc3a6b83123c398f5436579f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 16 commits behind head on master.
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #45508 +/- ##
==========================================
+ Coverage 83.56% 83.57% +0.01%
==========================================
Files 3048 3050 +2
Lines 199836 199896 +60
Branches 46613 46658 +45
==========================================
+ Hits 166984 167058 +74
+ Misses 29610 29597 -13
+ Partials 3242 3241 -1
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/45508/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [javascript](https://app.codecov.io/gh/apache/superset/pull/45508/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `79.28% <100.00%> (+0.02%)` | :arrow_up: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/45508?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4558246204
##########
superset/migrations/versions/2026-11-02_00-00_7b9d2f8a6c31_add_teams_installations.py:
##########
@@ -0,0 +1,65 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add Teams bot installation persistence.
+
+Revision ID: 7b9d2f8a6c31
+Revises: b8f3a2c91d64
+"""
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects import mysql
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import create_table
+
+revision: str = "7b9d2f8a6c31"
+down_revision: str = "b8f3a2c91d64"
+
+
+def upgrade() -> None:
+ """Add installation metadata without changing alerts or destinations."""
+ create_table(
+ "teams_installations",
+ sa.Column("id", UUIDType(binary=True), nullable=False),
+ sa.Column("tenant_id", UUIDType(binary=True), nullable=False),
+ sa.Column("application_id", UUIDType(binary=True), nullable=False),
+ sa.Column("team_id", sa.String(255), nullable=False),
+ sa.Column("service_url", sa.String(2048), nullable=False),
+ sa.Column("active", sa.Boolean(), nullable=False),
+ sa.Column(
+ "event_at",
+ sa.DateTime()
+ .with_variant(mysql.DATETIME(fsp=6), "mysql")
+ .with_variant(mysql.DATETIME(fsp=6), "mariadb"),
+ nullable=False,
+ ),
+ sa.Column("created_on", sa.DateTime(), nullable=False),
+ sa.Column("changed_on", sa.DateTime(), nullable=False),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint(
+ "tenant_id",
+ "application_id",
+ "team_id",
+ name="uq_teams_installation_identity",
+ ),
+ )
+
+
+def downgrade() -> None:
+ """Remove only the installation metadata table."""
+ op.drop_table("teams_installations")
Review Comment:
Thanks for the callout, switched the downgrade to the shared `drop_table` helper!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4420122642
##########
tests/unit_tests/integrations/teams/destinations_test.py:
##########
@@ -0,0 +1,255 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Browser discovery only projects approved keys and active-installation status."""
+
+from collections.abc import Iterator
+from datetime import datetime, timezone
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from flask import current_app, Flask
+from sqlalchemy import event
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import destinations
+from superset.integrations.teams.store import TeamsInstallationStore
+
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+OTHER = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+
+
+@pytest.fixture
+def configured_app(
+ teams_config: dict[str, Any], teams_engine: Engine, monkeypatch: pytest.MonkeyPatch
+) -> Iterator[Flask]:
+ app = Flask(__name__)
+ teams_config["destinations"].extend(
+ [
+ {
+ "key": "finance",
+ "label": "Finance",
+ "team_id": "team-1",
+ "channel_id": "channel-2",
+ },
+ {
+ "key": "support",
+ "label": "Support",
+ "team_id": "team-2",
+ "channel_id": "channel-3",
+ },
+ ]
+ )
+ app.config["ALERT_REPORTS_TEAMS"] = teams_config
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda name: True
+ )
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", lambda: True)
+ engine = teams_engine
+ monkeypatch.setattr(destinations, "db", MagicMock(engine=engine))
+ with app.app_context():
+ yield app
+
+
+def test_only_approved_public_fields_and_missing_installations(
+ configured_app: Flask,
+) -> None:
+ assert destinations.list_teams_destinations() == [
+ {"key": "ops", "label": "Operations", "available": False},
+ {"key": "finance", "label": "Finance", "available": False},
+ {"key": "support", "label": "Support", "available": False},
+ ]
+
+
+def test_removal_and_reinstallation_update_availability(configured_app: Flask) -> None:
+ with Session(destinations.db.engine) as session:
+ store = TeamsInstallationStore(session)
+ store.install(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ store.install(
+ TENANT,
+ APPLICATION,
+ "unapproved-team",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert [
+ item["available"] for item in destinations.list_teams_destinations()
+ ] == [True, True, False]
+ store.remove(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert not any(
+ item["available"] for item in destinations.list_teams_destinations()
+ )
+ store.install(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/emea/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert [
+ item["available"] for item in destinations.list_teams_destinations()
+ ] == [True, True, False]
+ assert len(destinations.list_teams_destinations()) == 3
+
+
+@pytest.mark.parametrize("tenant,application", [(OTHER, APPLICATION), (TENANT, OTHER)])
+def test_other_identity_cannot_make_destination_available(
+ configured_app: Flask, tenant: str, application: str
+) -> None:
+ with Session(destinations.db.engine) as session:
+ TeamsInstallationStore(session).install(
+ tenant,
+ application,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert not any(item["available"] for item in destinations.list_teams_destinations())
+
+
+@pytest.mark.parametrize("configuration", [{}, {"credential": "invalid-secret"}])
+def test_unconfigured_or_invalid_integration_is_hidden(
+ configured_app: Flask, configuration: dict[str, Any]
+) -> None:
+ current_app.config["ALERT_REPORTS_TEAMS"] = configuration
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+
+
+def test_disabled_integration_does_not_query_installations(
+ configured_app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda name: False
+ )
+ monkeypatch.setattr(
+ destinations, "Session", MagicMock(side_effect=AssertionError("must not query"))
+ )
+ assert destinations.list_teams_destinations() == []
+
+
+@pytest.mark.parametrize("team_id", ["t" * 256, " team-1", "team-1 ", "\tteam-1\n"])
+def test_invalid_team_config_is_hidden_before_installation_lookup(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ team_id: str,
+) -> None:
+ """Discovery handles invalid deployment IDs instead of raising store ValueError."""
+ configured_app.config["ALERT_REPORTS_TEAMS"]["destinations"][0]["team_id"] = team_id
+ lookup = MagicMock(side_effect=AssertionError("must not query installations"))
+ monkeypatch.setattr(destinations, "Session", lookup)
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ lookup.assert_not_called()
+
+
+@pytest.mark.parametrize("installed", [False, True])
+def test_optional_sdk_controls_both_discovery_and_notification_methods(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ installed: bool,
+) -> None:
+ """Bootstrap and destination discovery agree when the optional SDK is missing."""
+ from superset.reports.models import ReportRecipientType
+ from superset.views import base
+
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", lambda: installed)
+ monkeypatch.setattr(base, "app", configured_app)
+ configured_app.config["SLACK_API_TOKEN"] = None
+ if installed:
+ assert destinations.configured_teams() is not None
+ assert len(destinations.list_teams_destinations()) == 3
+ assert ReportRecipientType.TEAMS in base._notification_methods()
+ else:
+ session = MagicMock(side_effect=AssertionError("must not query installations"))
+ monkeypatch.setattr(destinations, "Session", session)
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ assert ReportRecipientType.TEAMS not in base._notification_methods()
+ session.assert_not_called()
+
+
+def test_disabled_integration_registers_and_bootstraps_without_sdk(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The Teams startup paths require neither SDK imports nor a dependency lookup."""
+ import sys
+
+ from superset.integrations.teams.api import register_teams_api
+ from superset.reports.models import ReportRecipientType
+ from superset.views import base
+
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda _: False
+ )
+ missing_sdk = MagicMock(side_effect=AssertionError("must not check SDK"))
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", missing_sdk)
+ monkeypatch.setitem(sys.modules, "superset.integrations.teams.adapter", None)
Review Comment:
`register_teams_api` and `base` are imported at the top of this test, before `sys.modules` is blocked here. If a module-level `import microsoft_teams` were added to `api.py` or `destinations.py`, those modules would already be loaded with the SDK present, so this test would still pass in CI while a deployment without the optional extra fails at startup. Could this run the disabled-Teams startup in a fresh interpreter (or import the modules after the block) and assert the callback still returns 404?
##########
superset/integrations/teams/validation.py:
##########
@@ -0,0 +1,95 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Shared Teams recipient rules for schedule saves and notification delivery."""
+
+from flask import current_app
+
+from superset.extensions import feature_flag_manager
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.reports.models import ReportDataFormat, ReportScheduleType
+from superset.utils import json
+
+
+class TeamsRecipientValidationError(ValueError):
+ """A field-specific error that never includes credentials or supplied values."""
+
+ def __init__(self, message: str, field: str = "recipients") -> None:
+ """Identify the schedule field that must be corrected."""
+ super().__init__(message)
+ self.field = field
+
+
+def validate_teams_recipient(
+ recipient_config: object,
+ schedule_type: str | None,
+ report_format: str | None,
+) -> tuple[TeamsConfig, TeamsDestination]:
+ """Require an enabled, configured, attachment-free alert and an approved key.
+
+ Accept deserialized command input or persisted recipient JSON. Installation
+ availability is deliberately checked only at delivery, so schedules may be
+ saved before a bot is installed. No SDK dependency or database access is needed.
+ """
+ if not feature_flag_manager.is_feature_enabled("ALERT_REPORT_TEAMS"):
+ raise TeamsRecipientValidationError("Teams alert delivery is disabled")
+ try:
+ config = parse_teams_config(current_app.config.get("ALERT_REPORTS_TEAMS", {}))
+ except ValueError:
+ raise TeamsRecipientValidationError(
+ "Invalid Teams deployment configuration"
+ ) from None
+ if config is None:
+ raise TeamsRecipientValidationError("Teams deployment is not configured")
+ if schedule_type != ReportScheduleType.ALERT:
+ raise TeamsRecipientValidationError(
+ "Teams recipients require an alert schedule", "type"
+ )
+ if report_format != ReportDataFormat.NONE:
+ raise TeamsRecipientValidationError(
+ "Teams recipients require disabled attachments (NONE format)",
+ "report_format",
+ )
+ try:
+ recipient = (
+ json.loads(recipient_config)
+ if isinstance(recipient_config, str)
+ else recipient_config
+ )
+ except (ValueError, TypeError):
+ raise TeamsRecipientValidationError(
+ "Invalid Teams recipient configuration"
+ ) from None
+ if (
+ not isinstance(recipient, dict)
+ or set(recipient) != {"target"}
+ or not isinstance(recipient["target"], str)
+ or not recipient["target"]
+ ):
+ raise TeamsRecipientValidationError(
+ "A configured Teams destination key is required"
+ )
+ try:
+ destination = config.get_destination(recipient["target"])
+ except ValueError:
+ raise TeamsRecipientValidationError(
Review Comment:
These Teams validation messages (here, the "A configured Teams destination key is required" and "Invalid Teams recipient configuration" ones above, and the duplicate-key message in `commands/report/base.py`) are plain English and flow straight into the 422 response and the editor's error toast. A non-English user saving an alert whose Teams destination was removed will see "Teams destination is not approved" untranslated, while the neighbouring report validators wrap theirs in `_()`. Should these go through gettext (and into `messages.pot`) like the rest of the report validation errors?
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,556 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask registers its route once at startup. Each request creates a fresh SDK
+ authentication server; its handler runs to completion in an operation-scoped
+ event loop. No SDK App, outbound clients, tasks, or separate server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
+ or not isinstance(action, str)
+ or action not in actions
+ ):
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ The SDK's HttpServer uses PyJWKClient, whose network responses close within
+ its scoped fetch. It creates no persistent HTTP clients. Keep construction,
+ authentication, and adapter cleanup within the same event loop; asyncio.run
+ closes that loop on success and failure. SDK response bodies are never exposed.
+ """
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = _FlaskServerAdapter()
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server = HttpServer(adapter, messaging_endpoint=EVENTS_PATH)
Review Comment:
A new `HttpServer` is built for every callback, so (assuming the SDK's validator builds its JWKS client per instance) none of the signing-key cache or refresh cooldown carries over between requests. An unauthenticated caller who posts a well-formed JWT with any `kid` then triggers a blocking fetch of the Bot Framework key set inside the Flask worker on every request, and if the egress IP gets throttled, legitimate installation events fail key lookup with a 401 and are never recorded (Teams does not redeliver). The tests monkeypatch the signing-key lookup, so this isn't exercised. Does the SDK cache keys across `HttpServer` instances, or should the server/validator be kept per process?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4379516946
##########
superset-frontend/src/features/alerts/AlertReportModal.test.tsx:
##########
@@ -4662,3 +4665,429 @@ test('global attachment policy hides both the alert toggle and attachment contro
);
}
});
+
+test('Changing the first Teams method preserves the following destination', async () => {
+ mockNotificationMethods = ['Email', 'Teams'];
+ fetchMock.get('glob:*/api/v1/report/92', {
+ result: {
+ ...generateMockPayload(true),
+ id: 92,
+ report_format: 'NONE',
+ recipients: [
+ { id: 1, type: 'Teams', recipient_config_json: '{"target":"ops"}' },
+ { id: 2, type: 'Teams', recipient_config_json: '{"target":"finance"}' },
+ ],
+ },
+ });
+ fetchMock.get(
+ 'glob:*/api/v1/report/teams_destinations/',
+ {
+ result: [
+ { key: 'ops', label: 'Operations', available: true },
+ { key: 'finance', label: 'Finance', available: false },
+ ],
+ },
+ { name: 'teams-destinations' },
+ );
+ fetchMock.put(
+ 'glob:*/api/v1/report/92',
+ { id: 92, result: {} },
+ { name: 'save-teams' },
+ );
+ try {
+ render(
+ <AlertReportModal
+ {...generateMockedProps(false, true)}
+ alert={{ ...validAlert, id: 92 }}
+ />,
+ {
+ useRedux: true,
+ initialState: { user: adminUser },
+ },
+ );
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /save/i })).toBeEnabled(),
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(
+ await screen.findByText('Finance (Bot installation required)'),
+ ).toBeInTheDocument();
+ expect(
+ screen.getAllByRole('combobox', { name: 'Teams destination' }),
+ ).toHaveLength(2);
+ expect(
+ screen.getByText(/Add another notification method/i),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByTestId('contents-panel'));
+ const attachmentToggle = screen.getByRole('switch', {
+ name: 'Include attachment',
+ });
+ await userEvent.click(attachmentToggle);
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /save/i })).toBeDisabled(),
+ );
+ await userEvent.click(attachmentToggle);
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /save/i })).toBeEnabled(),
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(
+ screen.getByText('Finance (Bot installation required)'),
+ ).toBeInTheDocument();
+ await userEvent.click(
+ screen.getAllByRole('combobox', { name: /^Delivery method/ })[0],
+ );
+ await userEvent.click(await screen.findByText('Email'));
+ await addAsyncSelectValue(
+ /email recipients/i,
+ 'owner@example.com',
+ reportUsersEndpoint,
+ );
+ await userEvent.click(screen.getByRole('button', { name: /save/i }));
+ await waitFor(() =>
+ expect(fetchMock.callHistory.calls('save-teams')).toHaveLength(1),
+ );
+ const [call] = fetchMock.callHistory.calls('save-teams');
+ expect(JSON.parse(call.options.body as string)).toMatchObject({
+ report_format: 'NONE',
+ recipients: [
+ {
+ type: 'Email',
+ recipient_config_json: {
+ target: 'owner@example.com',
+ ccTarget: '',
+ bccTarget: '',
+ },
+ },
+ { type: 'Teams', recipient_config_json: { target: 'finance' } },
+ ],
+ });
+ expect(JSON.parse(call.options.body as string).recipients).toEqual([
+ {
+ type: 'Email',
+ recipient_config_json: {
+ target: 'owner@example.com',
+ ccTarget: '',
+ bccTarget: '',
+ },
+ },
+ { type: 'Teams', recipient_config_json: { target: 'finance' } },
+ ]);
+ } finally {
+ fetchMock.removeRoute('teams-destinations');
+ fetchMock.removeRoute('save-teams');
+ }
+});
+
+test.each([
+ ['an active alert', true, false],
+ ['an inactive alert', false, false],
+ ['pausing an alert', true, true],
+])('Teams unavailable integration allows %s', async (_, active, pause) => {
+ const id = pause ? 193 : active ? 194 : 195;
+ mockNotificationMethods = ['Email', 'Slack'];
+ fetchMock.get(`glob:*/api/v1/report/${id}`, {
+ result: {
+ ...generateMockPayload(true),
+ id,
+ active,
+ report_format: 'NONE',
+ recipients: [
+ {
+ id: 1,
+ type: 'Teams',
+ recipient_config_json: '{"target":"removed-key"}',
+ },
+ { id: 2, type: 'Slack', recipient_config_json: { target: 'C123' } },
+ ],
+ },
+ });
+ fetchMock.get(
+ 'glob:*/api/v1/report/teams_destinations/',
+ { result: [] },
+ { name: 'teams-unavailable' },
+ );
+ fetchMock.put(
+ `glob:*/api/v1/report/${id}`,
+ { id, result: {} },
+ {
+ name: 'teams-unavailable-save',
+ },
+ );
+ try {
+ render(
+ <AlertReportModal
+ {...generateMockedProps(false, true)}
+ alert={{ ...validAlert, id }}
+ />,
+ { useRedux: true, initialState: { user: adminUser } },
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(
+ await screen.findByText('removed-key (Unavailable)'),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByText(/Teams delivery is unavailable/),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByTestId('general-information-panel'));
+ const description = screen.getByPlaceholderText(
+ /include description to be sent with alert/i,
+ );
+ await userEvent.clear(description);
+ await userEvent.type(description, 'Updated description');
+ if (pause) await userEvent.click(screen.getByRole('switch'));
+ const save = screen.getByRole('button', { name: /save/i });
+ await waitFor(() => expect(save).toBeEnabled());
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ const slackTarget = screen.getByTestId('recipients');
+ fireEvent.change(slackTarget, { target: { value: 'C456' } });
+ await waitFor(() => expect(save).toBeDisabled());
+ fireEvent.change(slackTarget, { target: { value: 'C123' } });
+ await waitFor(() => expect(save).toBeEnabled());
+ await userEvent.click(save);
+ await waitFor(() =>
+ expect(
+ fetchMock.callHistory.calls('teams-unavailable-save'),
+ ).toHaveLength(1),
+ );
+ const [call] = fetchMock.callHistory.calls('teams-unavailable-save');
+ expect(JSON.parse(call.options.body as string)).toMatchObject({
+ active: pause ? false : active,
+ description: 'Updated description',
+ report_format: 'NONE',
+ recipients: [
+ { type: 'Teams', recipient_config_json: { target: 'removed-key' } },
+ {
+ type: 'Slack',
+ recipient_config_json: {
+ target: 'C123',
+ ccTarget: '',
+ bccTarget: '',
+ },
+ },
+ ],
+ });
+ } finally {
+ fetchMock.removeRoute(`glob:*/api/v1/report/${id}`);
+ fetchMock.removeRoute('teams-unavailable');
+ fetchMock.removeRoute('teams-unavailable-save');
+ }
+});
+
+test('Teams unavailable saved keys can be replaced without losing inactive state', async () => {
+ mockNotificationMethods = ['Email', 'Teams'];
+ fetchMock.get('glob:*/api/v1/report/94', {
+ result: {
+ ...generateMockPayload(true),
+ id: 94,
+ active: false,
+ report_format: 'NONE',
+ recipients: [
+ {
+ id: 1,
+ type: 'Teams',
+ recipient_config_json: { target: 'removed-key' },
+ },
+ ],
+ },
+ });
+ fetchMock.get(
+ 'glob:*/api/v1/report/teams_destinations/',
+ {
+ result: [{ key: 'ops', label: 'Operations', available: false }],
+ },
+ { name: 'teams-replacement' },
+ );
+ fetchMock.put(
+ 'glob:*/api/v1/report/94',
+ { id: 94, result: {} },
+ { name: 'teams-replacement-save' },
+ );
+ try {
+ render(
+ <AlertReportModal
+ {...generateMockedProps(false, true)}
+ alert={{ ...validAlert, id: 94 }}
+ />,
+ {
+ useRedux: true,
+ initialState: { user: adminUser },
+ },
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(
+ await screen.findByText('removed-key (Unavailable)'),
+ ).toBeInTheDocument();
+ await userEvent.click(
+ screen.getByRole('combobox', { name: 'Teams destination' }),
+ );
+ await userEvent.click(
+ await screen.findByText('Operations (Bot installation required)'),
+ );
+ expect(
+ screen.queryByText(/This saved Teams destination is unavailable/),
+ ).not.toBeInTheDocument();
+ await userEvent.click(screen.getByRole('button', { name: /save/i }));
+ await waitFor(() =>
+ expect(
+ fetchMock.callHistory.calls('teams-replacement-save'),
+ ).toHaveLength(1),
+ );
+ const [call] = fetchMock.callHistory.calls('teams-replacement-save');
+ const payload = JSON.parse(call.options.body as string);
+ expect(payload.active).toBe(false);
+ expect(payload.report_format).toBe('NONE');
+ expect(payload.recipients).toEqual([
+ { type: 'Teams', recipient_config_json: { target: 'ops' } },
+ ]);
+ } finally {
+ fetchMock.removeRoute('teams-replacement');
+ fetchMock.removeRoute('teams-replacement-save');
+ }
+});
+
+test('Teams saved recipients stay visible and replaceable when the optional SDK is unavailable', async () => {
+ mockNotificationMethods = ['Email'];
+ fetchMock.get('glob:*/api/v1/report/95', {
+ result: {
+ ...generateMockPayload(true),
+ id: 95,
+ report_format: 'NONE',
+ recipients: [
+ { id: 1, type: 'Teams', recipient_config_json: '{"target":"ops"}' },
+ ],
+ },
+ });
+ fetchMock.get(
+ 'glob:*/api/v1/report/teams_destinations/',
+ { result: [] },
+ { name: 'teams-sdk-missing' },
+ );
+ try {
+ render(
+ <AlertReportModal
+ {...generateMockedProps(false, true)}
+ alert={{ ...validAlert, id: 95 }}
+ />,
+ {
+ useRedux: true,
+ initialState: { user: adminUser },
+ },
+ );
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ expect(await screen.findByText('ops (Unavailable)')).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ /Teams delivery is unavailable.*optional Teams dependency/,
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('combobox', { name: 'Teams destination' }),
+ ).toBeDisabled();
+ const save = screen.getByRole('button', { name: /save/i });
+ await waitFor(() => expect(save).toBeEnabled());
+ await userEvent.click(screen.getByTestId('general-information-panel'));
+ await userEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(save).toBeDisabled());
+ await userEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(save).toBeEnabled());
+ await userEvent.click(screen.getByTestId('notification-method-panel'));
+ await userEvent.click(
+ screen.getByRole('combobox', { name: /^Delivery method/ }),
+ );
+ await userEvent.click(await screen.findByText('Email'));
+ expect(
+ screen.queryByRole('combobox', { name: 'Teams destination' }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('ops (Unavailable)')).not.toBeInTheDocument();
+ } finally {
+ fetchMock.removeRoute('teams-sdk-missing');
+ }
+});
+
+test.each(['PNG', 'CSV'])(
+ 'Teams edits normalize saved %s format when attachments are globally disabled',
+ async reportFormat => {
+ mockNotificationMethods = ['Email', 'Teams'];
+ fetchMock.removeRoute(configurationEndpoint);
+ fetchMock.get(
+ configurationEndpoint,
+ {
+ result: { ...mockReportConfiguration, alerts_attach_reports: false },
+ },
+ { name: configurationEndpoint },
+ );
+ fetchMock.get('glob:*/api/v1/report/96', {
Review Comment:
Addressed :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4460334278
##########
superset/reports/notifications/teams.py:
##########
@@ -0,0 +1,163 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Attachment-free alert delivery to configured Teams standard channels."""
+
+from typing import Any
+from urllib.parse import urlsplit
+
+from flask_babel import gettext as __
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.extensions import db
+from superset.integrations.teams.config import (
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.integrations.teams.validation import (
+ TeamsRecipientValidationError,
+ validate_teams_recipient,
+)
+from superset.reports.models import ReportRecipientType
+from superset.reports.notifications.base import BaseNotification, NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+
+
+def build_teams_card(content: NotificationContent) -> dict[str, Any]:
+ """Build a card using structured data, omitting raw execution diagnostics."""
+ body: list[dict[str, Any]] = [
+ {
+ "type": "TextBlock",
+ "text": content.name,
+ "weight": "Bolder",
+ "size": "Medium",
+ "wrap": True,
+ },
+ ]
+ if content.description:
+ body.append({"type": "TextBlock", "text": content.description, "wrap": True})
+ if content.text:
+ body.append(
+ {
+ "type": "TextBlock",
+ "text": __(
+ "Alert execution failed. Contact the alert owner for details."
+ ),
+ "wrap": True,
+ }
+ )
+ card: dict[str, Any] = {
+ "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
+ "type": "AdaptiveCard",
+ "version": "1.2",
+ "body": body,
+ }
+ if content.include_cta and content.url:
+ try:
+ url = urlsplit(content.url)
+ safe_link = url.scheme in {"http", "https"} and bool(url.hostname)
+ except ValueError:
+ safe_link = False
+ if safe_link:
+ card["actions"] = [
+ {
+ "type": "Action.OpenUrl",
+ "title": __("Open in Superset"),
+ "url": content.url,
+ }
+ ]
+ return card
+
+
+def _send_to_teams(
+ config: TeamsConfig,
+ destination: TeamsDestination,
+ service_url: str,
+ card: dict[str, Any],
+ *,
+ retry_deadline: float | None = None,
+) -> None:
+ """Load the optional SDK only for delivery and map sanitized transport errors."""
+ try:
+ from superset.integrations.teams.adapter import (
+ deliver_teams_alert,
+ TeamsDeliveryError,
+ )
+ except ImportError:
+ raise NotificationParamException("Teams SDK is not installed") from None
+ try:
+ deliver_teams_alert(
+ config, destination, service_url, card, retry_deadline=retry_deadline
Review Comment:
Added
##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -1906,6 +1895,59 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
return false;
}
+ const hasTeamsRecipients = notificationSettings.some(
+ setting => setting.method === NotificationMethodOption.Teams,
+ );
+ // Match the backend's delivery-change check so unavailable integrations do
+ // not prevent pausing or editing metadata on an existing alert.
+ const normalizeRecipients = (
+ recipients: {
+ type: string;
+ recipient_config_json: string | Recipient['recipient_config_json'];
+ }[],
+ ) =>
+ JSON.stringify(
+ recipients
+ .map(({ type, recipient_config_json: config }) => {
+ const parsed =
+ typeof config === 'string' ? JSON.parse(config) : config;
+ return JSON.stringify([
+ type,
+ Object.entries(parsed)
+ .filter(
+ ([key, value]) =>
+ value !== undefined &&
+ !(
+ type !== NotificationMethodOption.Teams &&
+ ['ccTarget', 'bccTarget'].includes(key) &&
+ value === ''
+ ),
+ )
+ .sort(([left], [right]) => left.localeCompare(right)),
+ ]);
+ })
+ .sort(),
+ );
+ const deliveryUnchanged =
+ hasTeamsRecipients &&
+ isEditMode &&
+ resource &&
+ !(currentAlert?.active && !resource.active) &&
+ resource.type === (isReport ? 'Report' : 'Alert') &&
+ resource.report_format === effectiveReportFormat &&
+ normalizeRecipients(resource.recipients || []) ===
+ normalizeRecipients(getRecipients());
+ const invalidTeamsRecipients =
+ hasTeamsRecipients &&
+ ((!deliveryUnchanged &&
+ (!teamsSupported || !teamsIntegrationAvailable)) ||
Review Comment:
Added
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4365976549
##########
superset/migrations/versions/2026-10-19_00-00_7b9d2f8a6c31_add_teams_installations.py:
##########
@@ -0,0 +1,58 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add Teams bot installation persistence.
+
+Revision ID: 7b9d2f8a6c31
+Revises: d623a0cb6bb0
+"""
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import create_table
+
+revision: str = "7b9d2f8a6c31"
+down_revision: str = "d623a0cb6bb0"
+
+
+def upgrade() -> None:
+ """Add installation metadata without changing alerts or destinations."""
+ create_table(
+ "teams_installations",
+ sa.Column("id", UUIDType(binary=True), nullable=False),
+ sa.Column("tenant_id", UUIDType(binary=True), nullable=False),
+ sa.Column("application_id", UUIDType(binary=True), nullable=False),
+ sa.Column("team_id", sa.String(255), nullable=False),
+ sa.Column("service_url", sa.String(2048), nullable=False),
+ sa.Column("active", sa.Boolean(), nullable=False),
+ sa.Column("event_at", sa.DateTime(), nullable=False),
Review Comment:
Thanks for the catch on this. Updated `event_at` in both the model and migration to use DATETIME(6) for MySQL and MariaDB. The lifecycle tests now cover sub-second timestamps too
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4377811235
##########
tests/unit_tests/integrations/teams/delivery_test.py:
##########
@@ -0,0 +1,965 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Teams notification formatting, resolution, retry, and SDK delivery tests."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import importlib.util
+import threading
+import time
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager
+from datetime import datetime, timedelta, timezone
+from email.utils import format_datetime
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+import requests
+from billiard.exceptions import SoftTimeLimitExceeded
+from flask import current_app, Flask
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import validation as teams_validation
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.models import TeamsInstallation
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.reports.models import ReportRecipients, ReportRecipientType
+from superset.reports.notifications import create_notification, teams as notifications
+from superset.reports.notifications.base import NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+from superset.utils import json
+
+if importlib.util.find_spec("microsoft_teams") is None:
+ pytest.skip("Optional Teams SDK is not installed", allow_module_level=True)
+
+adapter = importlib.import_module("superset.integrations.teams.adapter")
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+SERVICE_URL = "https://smba.trafficmanager.net/amer/"
+
+
+@pytest.fixture
+def configured(teams_config: dict[str, Any]) -> TeamsConfig:
+ """Parse the same deployment configuration used by real notifications."""
+ config = parse_teams_config(teams_config)
+ assert config is not None
+ return config
+
+
+@pytest.fixture
+def content() -> NotificationContent:
+ """Include difficult text to verify normal structured JSON serialization."""
+ return NotificationContent(
+ name='Alert "Revenue"\nCafé 東京 🚨',
+ description='Description "quoted"\n第二行',
+ header_data={
+ "notification_type": "Alert",
+ "notification_format": "NONE",
+ "editors": [],
+ "notification_source": None,
+ "chart_id": None,
+ "dashboard_id": None,
+ "slack_channels": None,
+ "execution_id": None,
+ },
+ url="https://superset.example/chart/42/",
+ )
+
+
+@pytest.fixture
+def notification_context(
+ teams_config: dict[str, Any],
+ teams_engine: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[SimpleNamespace]:
+ """Use the real installation table and resolve through the notification class."""
+ app = Flask(__name__)
+ app.config.update(
+ ALERT_REPORTS_TEAMS=teams_config, FEATURE_FLAGS={"ALERT_REPORT_TEAMS": True}
+ )
+ engine = teams_engine
+ with Session(engine) as session:
+ TeamsInstallationStore(session).install(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ session.commit()
+ monkeypatch.setattr(notifications, "db", SimpleNamespace(engine=engine))
+ monkeypatch.setattr(
+ teams_validation.feature_flag_manager,
+ "is_feature_enabled",
+ lambda name: current_app.config["FEATURE_FLAGS"].get(name, False),
+ )
+ send = MagicMock()
+ monkeypatch.setattr(notifications, "_send_to_teams", send)
+ with app.app_context():
+ yield SimpleNamespace(app=app, engine=engine, send=send)
+
+
+def recipient(target: str = "ops") -> ReportRecipients:
+ """Recipients store only a configured destination key."""
+ return ReportRecipients(
+ type=ReportRecipientType.TEAMS,
+ recipient_config_json=json.dumps({"target": target}),
+ )
+
+
+def test_factory_resolves_active_installation_and_formats_card(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+) -> None:
+ notification = create_notification(recipient(), content)
+ assert isinstance(notification, notifications.TeamsNotification)
+ notification.send()
+ config, destination, service_url, card = notification_context.send.call_args.args
+ assert config.credential == "deployment-secret"
+ assert destination.key == "ops"
+ assert destination.channel_id == "channel-1"
+ assert service_url == SERVICE_URL
+ assert card["body"][0]["text"] == content.name
+ assert card["body"][1]["text"] == content.description
+ assert card["actions"][0]["url"] == content.url
+ assert "deployment-secret" not in json.dumps(card)
+
+
+@pytest.mark.parametrize(
+ "mode", ["inactive", "missing", "other-tenant", "other-application"]
+)
+def test_installation_must_be_active_for_exact_identity(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+ mode: str,
+) -> None:
+ with Session(notification_context.engine) as session:
+ store = TeamsInstallationStore(session)
+ if mode == "inactive":
+ store.remove(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ else:
+ session.query(TeamsInstallation).delete()
+ other = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+ if mode != "missing":
+ store.install(
+ other if mode == "other-tenant" else TENANT,
+ other if mode == "other-application" else APPLICATION,
+ "team-1",
+ SERVICE_URL,
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ with pytest.raises(NotificationAuthorizationException):
+ notifications.TeamsNotification(recipient(), content).send()
+ notification_context.send.assert_not_called()
+
+
+class FakeTransport:
+ """Deterministic replaceable transport for bounded retry policy tests."""
+
+ def __init__(self, errors: list[Exception | None]) -> None:
+ """Consume one outcome for each root post attempt."""
+ self.errors = iter(errors)
+ self.posts: list[tuple[TeamsDestination, dict[str, Any]]] = []
+ self.refreshes = 0
+ self.closed = False
+ self.loop: asyncio.AbstractEventLoop | None = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Record every fresh root-post attempt."""
+ self.posts.append((destination, card))
+ error = next(self.errors)
+ if error:
+ raise error
+
+ async def refresh_auth(self) -> None:
+ """Record a cache invalidation without contacting Entra."""
+ self.refreshes += 1
+
+ @asynccontextmanager
+ async def factory(
+ self, config: TeamsConfig, service_url: str, deadline: float
+ ) -> AsyncIterator[FakeTransport]:
+ """Track operation cleanup on both successful and failed delivery."""
+ self.loop = asyncio.get_running_loop()
+ try:
+ yield self
+ finally:
+ self.closed = True
+
+
+@pytest.fixture
+def retry_clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
+ """Advance retry time without actually sleeping."""
+ elapsed = [0.0]
+ sleeps: list[float] = []
+ monkeypatch.setattr(adapter, "monotonic", lambda: elapsed[0])
+
+ async def sleep(delay: float) -> None:
+ """Advance the same clock used by the retry budget."""
+ elapsed[0] += delay
+ sleeps.append(delay)
+
+ monkeypatch.setattr(adapter.asyncio, "sleep", sleep)
+ return sleeps
+
+
+@pytest.mark.parametrize(
+ "status,retryable",
+ [
+ (None, False),
+ (None, True),
+ (408, False),
+ (429, False),
+ (500, False),
+ (502, False),
+ (503, False),
+ (504, False),
+ ],
+)
+def test_transport_failures_respect_retry_safety_and_attempt_bound(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ status: int | None,
+ retryable: bool,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status, retryable=retryable)] * 4
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ ambiguous = status is None and not retryable
+ assert exc.value.category == ("unknown" if ambiguous else "transient")
+ assert len(transport.posts) == (1 if ambiguous else 4)
+ assert retry_clock == ([] if ambiguous else [1.0, 2.0, 4.0])
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "headers,expected",
+ [
+ ({"Retry-After": "3"}, 3.0),
+ ({"x-ms-retry-after-ms": "1500"}, 1.5),
+ ({"Retry-After": "2", "x-ms-retry-after-ms": "3000"}, 3.0),
+ ({"Retry-After": "invalid"}, 1.0),
+ ],
+)
+def test_microsoft_retry_delays_are_respected(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ headers: dict[str, str],
+ expected: float,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers(headers)), None]
+ )
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert retry_clock == [expected]
+ assert len(transport.posts) == 2
+ assert transport.closed
+
+
+def test_retry_after_http_date() -> None:
+ retry_at = datetime.now(timezone.utc) + timedelta(seconds=5)
+ error = adapter.TeamsTransportError(
+ 429, httpx.Headers({"Retry-After": format_datetime(retry_at, usegmt=True)})
+ )
+ assert 3.0 <= adapter._retry_delay(error, 0) <= 5.0
+
+
+def test_excessive_server_delay_is_not_shortened(
+ configured: TeamsConfig, retry_clock: list[float]
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers({"Retry-After": "120"}))]
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == "transient"
+ assert len(transport.posts) == 1
+ assert retry_clock == []
+ assert transport.closed
+
+
+@pytest.mark.parametrize(
+ "outcomes,category,posts,refreshes",
+ [
+ ([401, None], None, 2, 1),
+ ([401, 401], "authorization", 2, 1),
+ ([403], "authorization", 1, 0),
+ ([400], "parameter", 1, 0),
+ ([404], "parameter", 1, 0),
+ ([302], "parameter", 1, 0),
+ ([401, 503, 503, None], None, 4, 1),
Review Comment:
Added a `[503, 503, 503, 401]` case
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4368383331
##########
superset/commands/report/update.py:
##########
@@ -496,6 +496,8 @@ def validate(self) -> None: # noqa: C901
self._properties.get("report_format", self._model.report_format),
exceptions,
)
+ # Always validate the effective Teams recipients, even for metadata-only PUTs.
+ self.validate_teams_recipients(exceptions)
Review Comment:
Ah good call. Pausing and metadata edits now work when Teams is unavailable. Activation and delivery changes still validate, with regression tests added
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4403674865
##########
tests/unit_tests/integrations/teams/delivery_test.py:
##########
@@ -0,0 +1,976 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Teams notification formatting, resolution, retry, and SDK delivery tests."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import importlib.util
+import threading
+import time
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager, nullcontext
+from datetime import datetime, timedelta, timezone
+from email.utils import format_datetime
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+import requests
+from billiard.exceptions import SoftTimeLimitExceeded
+from flask import current_app, Flask
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import validation as teams_validation
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.models import TeamsInstallation
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.reports.models import ReportRecipients, ReportRecipientType
+from superset.reports.notifications import create_notification, teams as notifications
+from superset.reports.notifications.base import NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+from superset.utils import json
+
+if importlib.util.find_spec("microsoft_teams") is None:
+ pytest.skip("Optional Teams SDK is not installed", allow_module_level=True)
+
+adapter = importlib.import_module("superset.integrations.teams.adapter")
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+SERVICE_URL = "https://smba.trafficmanager.net/amer/"
+
+
+@pytest.fixture
+def configured(teams_config: dict[str, Any]) -> TeamsConfig:
+ """Parse the same deployment configuration used by real notifications."""
+ config = parse_teams_config(teams_config)
+ assert config is not None
+ return config
+
+
+@pytest.fixture
+def content() -> NotificationContent:
+ """Include difficult text to verify normal structured JSON serialization."""
+ return NotificationContent(
+ name='Alert "Revenue"\nCafé 東京 🚨',
+ description='Description "quoted"\n第二行',
+ header_data={
+ "notification_type": "Alert",
+ "notification_format": "NONE",
+ "editors": [],
+ "notification_source": None,
+ "chart_id": None,
+ "dashboard_id": None,
+ "slack_channels": None,
+ "execution_id": None,
+ },
+ url="https://superset.example/chart/42/",
+ )
+
+
+@pytest.fixture
+def notification_context(
+ teams_config: dict[str, Any],
+ teams_engine: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[SimpleNamespace]:
+ """Use the real installation table and resolve through the notification class."""
+ app = Flask(__name__)
+ app.config.update(
+ ALERT_REPORTS_TEAMS=teams_config, FEATURE_FLAGS={"ALERT_REPORT_TEAMS": True}
+ )
+ engine = teams_engine
+ with Session(engine) as session:
+ TeamsInstallationStore(session).install(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ session.commit()
+ monkeypatch.setattr(notifications, "db", SimpleNamespace(engine=engine))
+ monkeypatch.setattr(
+ teams_validation.feature_flag_manager,
+ "is_feature_enabled",
+ lambda name: current_app.config["FEATURE_FLAGS"].get(name, False),
+ )
+ send = MagicMock()
+ monkeypatch.setattr(notifications, "_send_to_teams", send)
+ with app.app_context():
+ yield SimpleNamespace(app=app, engine=engine, send=send)
+
+
+def recipient(target: str = "ops") -> ReportRecipients:
+ """Recipients store only a configured destination key."""
+ return ReportRecipients(
+ type=ReportRecipientType.TEAMS,
+ recipient_config_json=json.dumps({"target": target}),
+ )
+
+
+def test_factory_resolves_active_installation_and_formats_card(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+) -> None:
+ notification = create_notification(recipient(), content)
+ assert isinstance(notification, notifications.TeamsNotification)
+ notification.send()
+ config, destination, service_url, card = notification_context.send.call_args.args
+ assert config.credential == "deployment-secret"
+ assert destination.key == "ops"
+ assert destination.channel_id == "channel-1"
+ assert service_url == SERVICE_URL
+ assert card["body"][0]["text"] == content.name
+ assert card["body"][1]["text"] == content.description
+ assert card["actions"][0]["url"] == content.url
+ assert "deployment-secret" not in json.dumps(card)
+
+
+@pytest.mark.parametrize(
+ "mode", ["inactive", "missing", "other-tenant", "other-application"]
+)
+def test_installation_must_be_active_for_exact_identity(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+ mode: str,
+) -> None:
+ with Session(notification_context.engine) as session:
+ store = TeamsInstallationStore(session)
+ if mode == "inactive":
+ store.remove(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ else:
+ session.query(TeamsInstallation).delete()
+ other = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+ if mode != "missing":
+ store.install(
+ other if mode == "other-tenant" else TENANT,
+ other if mode == "other-application" else APPLICATION,
+ "team-1",
+ SERVICE_URL,
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ with pytest.raises(NotificationAuthorizationException):
+ notifications.TeamsNotification(recipient(), content).send()
+ notification_context.send.assert_not_called()
+
+
+class FakeTransport:
+ """Deterministic replaceable transport for bounded retry policy tests."""
+
+ def __init__(self, errors: list[Exception | None]) -> None:
+ """Consume one outcome for each root post attempt."""
+ self.errors = iter(errors)
+ self.posts: list[tuple[TeamsDestination, dict[str, Any]]] = []
+ self.refreshes = 0
+ self.closed = False
+ self.loop: asyncio.AbstractEventLoop | None = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Record every fresh root-post attempt."""
+ self.posts.append((destination, card))
+ error = next(self.errors)
+ if error:
+ raise error
+
+ async def refresh_auth(self) -> None:
+ """Record a cache invalidation without contacting Entra."""
+ self.refreshes += 1
+
+ @asynccontextmanager
+ async def factory(
+ self, config: TeamsConfig, service_url: str, deadline: float
+ ) -> AsyncIterator[FakeTransport]:
+ """Track operation cleanup on both successful and failed delivery."""
+ self.loop = asyncio.get_running_loop()
+ try:
+ yield self
+ finally:
+ self.closed = True
+
+
+@pytest.fixture
+def retry_clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
+ """Advance retry time without actually sleeping."""
+ elapsed = [0.0]
+ sleeps: list[float] = []
+ monkeypatch.setattr(adapter, "monotonic", lambda: elapsed[0])
+
+ async def sleep(delay: float) -> None:
+ """Advance the same clock used by the retry budget."""
+ elapsed[0] += delay
+ sleeps.append(delay)
+
+ monkeypatch.setattr(adapter.asyncio, "sleep", sleep)
+ return sleeps
+
+
+@pytest.mark.parametrize(
+ "status,retryable",
+ [
+ (None, False),
+ (None, True),
+ (408, False),
+ (429, False),
+ (500, False),
+ (502, False),
+ (503, False),
+ (504, False),
+ ],
+)
+def test_transport_failures_respect_retry_safety_and_attempt_bound(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ status: int | None,
+ retryable: bool,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status, retryable=retryable)] * 4
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ ambiguous = status is None and not retryable
+ assert exc.value.category == ("unknown" if ambiguous else "transient")
+ assert len(transport.posts) == (1 if ambiguous else 4)
+ assert retry_clock == ([] if ambiguous else [1.0, 2.0, 4.0])
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "headers,expected",
+ [
+ ({"Retry-After": "3"}, 3.0),
+ ({"x-ms-retry-after-ms": "1500"}, 1.5),
+ ({"Retry-After": "2", "x-ms-retry-after-ms": "3000"}, 3.0),
+ ({"Retry-After": "invalid"}, 1.0),
+ ],
+)
+def test_microsoft_retry_delays_are_respected(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ headers: dict[str, str],
+ expected: float,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers(headers)), None]
+ )
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert retry_clock == [expected]
+ assert len(transport.posts) == 2
+ assert transport.closed
+
+
+def test_retry_after_http_date() -> None:
+ retry_at = datetime.now(timezone.utc) + timedelta(seconds=5)
+ error = adapter.TeamsTransportError(
+ 429, httpx.Headers({"Retry-After": format_datetime(retry_at, usegmt=True)})
+ )
+ assert 3.0 <= adapter._retry_delay(error, 0) <= 5.0
+
+
+def test_excessive_server_delay_is_not_shortened(
+ configured: TeamsConfig, retry_clock: list[float]
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers({"Retry-After": "120"}))]
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == "transient"
+ assert len(transport.posts) == 1
+ assert retry_clock == []
+ assert transport.closed
+
+
+@pytest.mark.parametrize(
+ "outcomes,category,posts,refreshes",
+ [
+ ([401, None], None, 2, 1),
+ ([401, 401], "authorization", 2, 1),
+ ([403], "authorization", 1, 0),
+ ([400], "parameter", 1, 0),
+ ([404], "parameter", 1, 0),
+ ([302], "parameter", 1, 0),
+ ([401, 503, 503, None], None, 4, 1),
+ ([503, 503, 503, 401], "authorization", 4, 0),
+ ],
+)
+def test_one_authentication_refresh_and_permanent_errors(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ outcomes: list[int | None],
+ category: str | None,
+ posts: int,
+ refreshes: int,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status) if status else None for status in outcomes]
+ )
+ if category:
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == category
+ else:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert len(transport.posts) == posts
+ assert transport.refreshes == refreshes
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "category,exception",
+ [
+ ("authorization", NotificationAuthorizationException),
+ ("transient", NotificationTransientError),
+ ("parameter", NotificationParamException),
+ ("unknown", NotificationError),
+ ],
+)
+def test_transport_errors_map_to_existing_notification_exceptions(
+ configured: TeamsConfig,
+ monkeypatch: pytest.MonkeyPatch,
+ category: str,
+ exception: type[Exception],
+) -> None:
+ monkeypatch.setattr(
+ adapter,
+ "deliver_teams_alert",
+ MagicMock(side_effect=adapter.TeamsDeliveryError(category)),
+ )
+ with pytest.raises(exception) as exc:
Review Comment:
This parametrized case passes any `NotificationError` subclass, and `NotificationTransientError` subclasses `NotificationError`, so the `"unknown"` row would still pass if `_send_to_teams` mapped an ambiguous outcome (a read timeout after the post was accepted) to the transient type. The report layer retries transient errors, so that regression would re-post the alert to the channel, and the adapter-level tests only assert `category == "unknown"` before this mapping. Could you assert the exact type here (for example `assert type(exc.value) is exception`) so the unknown-versus-transient boundary is pinned?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "rusackas (via GitHub) via notifications" <no...@superset.apache.org>.
rusackas commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4548729371
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,572 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from functools import lru_cache
+from threading import Lock
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask owns the listening server. SDK authentication is reused, while each
+ callback runs to completion in an operation-scoped event loop. No SDK App,
+ outbound clients, tasks, or separate listening server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
Review Comment:
Teams sends `conversationUpdate` and friends to this same endpoint, right? I think those would all get a 400 here, which Azure would probably report as delivery failures. Should we just 200 anything authenticated that isn't an install event?
##########
superset/reports/notifications/teams.py:
##########
@@ -0,0 +1,163 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Attachment-free alert delivery to configured Teams standard channels."""
+
+from typing import Any
+from urllib.parse import urlsplit
+
+from flask_babel import gettext as __
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.extensions import db
+from superset.integrations.teams.config import (
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.integrations.teams.validation import (
+ TeamsRecipientValidationError,
+ validate_teams_recipient,
+)
+from superset.reports.models import ReportRecipientType
+from superset.reports.notifications.base import BaseNotification, NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+
+
+def build_teams_card(content: NotificationContent) -> dict[str, Any]:
+ """Build a card using structured data, omitting raw execution diagnostics."""
+ body: list[dict[str, Any]] = [
+ {
+ "type": "TextBlock",
+ "text": content.name,
+ "weight": "Bolder",
+ "size": "Medium",
+ "wrap": True,
+ },
+ ]
+ if content.description:
+ body.append({"type": "TextBlock", "text": content.description, "wrap": True})
+ if content.text:
+ body.append(
+ {
+ "type": "TextBlock",
+ "text": __(
+ "Alert execution failed. Contact the alert owner for details."
+ ),
+ "wrap": True,
+ }
+ )
+ card: dict[str, Any] = {
+ "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
+ "type": "AdaptiveCard",
+ "version": "1.2",
+ "body": body,
+ }
+ if content.include_cta and content.url:
+ try:
+ url = urlsplit(content.url)
+ safe_link = url.scheme in {"http", "https"} and bool(url.hostname)
+ except ValueError:
+ safe_link = False
+ if safe_link:
+ card["actions"] = [
+ {
+ "type": "Action.OpenUrl",
+ "title": __("Open in Superset"),
+ "url": content.url,
+ }
+ ]
+ return card
+
+
+def _send_to_teams(
+ config: TeamsConfig,
+ destination: TeamsDestination,
+ service_url: str,
+ card: dict[str, Any],
+ *,
+ retry_deadline: float | None = None,
+) -> None:
+ """Load the optional SDK only for delivery and map sanitized transport errors."""
+ try:
+ from superset.integrations.teams.adapter import (
+ deliver_teams_alert,
+ TeamsDeliveryError,
+ )
+ except ImportError:
+ raise NotificationParamException("Teams SDK is not installed") from None
+ try:
+ deliver_teams_alert(
+ config, destination, service_url, card, retry_deadline=retry_deadline
+ )
+ except TeamsDeliveryError as ex:
+ exception = {
+ "authorization": NotificationAuthorizationException,
+ "transient": NotificationTransientError,
+ "parameter": NotificationParamException,
+ "unknown": NotificationError,
+ }[ex.category]
+ raise exception(str(ex)) from None
+
+
+class TeamsNotification(BaseNotification):
+ """Resolve the configured destination and its active installation before send."""
+
+ type = ReportRecipientType.TEAMS
+
+ def send(self) -> None:
Review Comment:
The other notification types have a `@statsd_gauge("reports.<type>.send")` on `send`. Should we add one for Teams so its failures show up in the same metrics?
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,572 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from functools import lru_cache
+from threading import Lock
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask owns the listening server. SDK authentication is reused, while each
+ callback runs to completion in an operation-scoped event loop. No SDK App,
+ outbound clients, tasks, or separate listening server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
+ or not isinstance(action, str)
+ or action not in actions
+ ):
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+@lru_cache(maxsize=8)
+def _callback_server(
+ process_id: int, application_id: str, tenant_id: str
+) -> tuple[HttpServer, Lock]:
+ """Retain SDK signing-key caches per process and configured identity.
+
+ The process ID avoids inheriting a locked server when a worker forks.
+ The lock serializes use of the SDK's mutable on_request callback.
+ """
+ return HttpServer(_FlaskServerAdapter(), messaging_endpoint=EVENTS_PATH), Lock()
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ Only the SDK server and its signing-key cache survive requests. Request
+ handlers and event loops are released after every callback, and no outbound
+ SDK client is created. Credentials and event bodies are not cache keys.
+ """
+ server, lock = _callback_server(
+ os.getpid(), config.application_id, config.tenant_id
+ )
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = server.adapter
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ response: HttpResponse = await server.handle_request(
+ HttpRequest(body=body, headers=headers)
+ )
+ if response["status"] != 200:
+ return TeamsEventResult(response["status"])
+ return result
+ finally:
+ server.on_request = None
+ await adapter.stop()
+
+ with lock:
+ return asyncio.run(process())
+
+
+# Count every send, including the single 401 replay, against the same retry bound.
+_DELIVERY_ATTEMPTS = 4
+_DELIVERY_TIMEOUT = 60.0
+_DELIVERY_REQUEST_TIMEOUT = 10.0
+
+
+class TeamsDeliveryError(Exception):
+ """Sanitized delivery outcome for mapping to existing notification exceptions."""
+
+ def __init__(
+ self, category: Literal["authorization", "transient", "parameter", "unknown"]
+ ) -> None:
+ """Expose a stable message without response bodies, SQL, tokens, or URLs."""
+ self.category = category
+ messages = {
+ "authorization": "Teams bot authorization failed",
+ "transient": "Teams alert delivery temporarily unavailable",
+ "parameter": "Teams alert delivery was rejected",
+ "unknown": (
+ "Teams alert delivery could not be confirmed. "
+ "It may have been delivered"
+ ),
+ }
+ super().__init__(messages[category])
+
+
+class TeamsTransportError(Exception):
+ """Sanitized HTTP failure with explicit retry safety for status-less errors."""
+
+ def __init__(
+ self,
+ status: int | None = None,
+ headers: httpx.Headers
+ | requests.structures.CaseInsensitiveDict[str]
+ | None = None,
+ *,
+ retryable: bool = False,
+ ) -> None:
+ """Retain only retry headers; never retain a response body or request token."""
+ super().__init__("Teams transport request failed")
+ self.status = status
+ self.retryable = retryable
+ self.retry_after = headers.get("Retry-After") if headers is not None else None
+ self.retry_after_ms = (
+ headers.get("x-ms-retry-after-ms") if headers is not None else None
+ )
+
+
+class TeamsTransport(Protocol):
+ """Replaceable operation-scoped transport; retries live outside SDK calls."""
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new channel root post containing the card."""
+ ...
+
+ async def refresh_auth(self) -> None:
+ """Invalidate cached authentication before a single 401 replay."""
+ ...
+
+
+def _remaining(deadline: float) -> float:
+ """Bound each request by its timeout and remaining delivery budget."""
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise TeamsTransportError(retryable=True)
+ return min(_DELIVERY_REQUEST_TIMEOUT, remaining)
+
+
+class _AuthHttpClient:
+ """MSAL HTTP interface backed by a caller-owned, timeout-bounded session."""
+
+ def __init__(self, session: requests.Session, deadline: float) -> None:
+ """Keep OAuth traffic within the same operation as the channel post."""
+ self.session = session
+ self.deadline = deadline
+
+ def get(self, url: str, **kwargs: Any) -> requests.Response:
+ """Fetch MSAL metadata without leaving a response open."""
+ return self._request("GET", url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> requests.Response:
+ """Acquire tokens without leaving a response open."""
+ return self._request("POST", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
+ """Use normal serialization, explicit timeouts, and sanitized retry errors."""
+ kwargs["timeout"] = _remaining(self.deadline)
+ response = self.session.request(method, url, **kwargs)
+ try:
+ _remaining(self.deadline)
+ # requests eagerly reads responses; MSAL can still read cached JSON
+ # after close. Closing here also covers retryable OAuth errors.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise TeamsTransportError(response.status_code, response.headers)
+ return response
+ finally:
+ response.close()
+
+
+class _ChannelConversationParams(CreateConversationParams):
+ """Include the connector's group flag, absent from the SDK base parameter model."""
+
+ is_group: Literal[True] = True
+
+
+class _SDKTeamsTransport:
+ """Use the SDK create-conversation API with shared, explicitly owned resources."""
+
+ def __init__(
+ self,
+ config: TeamsConfig,
+ service_url: str,
+ http: Client,
+ auth_http: _AuthHttpClient,
+ deadline: float,
+ ) -> None:
+ """Prepare the SDK without constructing a full App or starting a server."""
+ self.config = config
+ self.http = http
+ self.auth_http = auth_http
+ self.deadline = deadline
+ self.auth: ConfidentialClientApplication | None = None
+ self.api = ApiClient(service_url, http)
+
+ def _authenticate(self) -> None:
+ """Acquire a bot token without exposing identity-provider errors."""
+ if self.http.token:
+ return
+ if self.auth is None:
+ self.auth = ConfidentialClientApplication(
+ self.config.application_id,
+ client_credential=self.config.credential,
+ authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
+ http_client=self.auth_http,
+ instance_discovery=False,
+ )
+ result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
+ token = result.get("access_token")
+ if not isinstance(token, str) or not token:
+ status = (
+ 503
+ if result.get("error") in {"temporarily_unavailable", "server_error"}
+ else 401
+ )
+ raise TeamsTransportError(status)
+ self.http.token = token
+
+ async def refresh_auth(self) -> None:
+ """Invalidate MSAL app tokens so the next request acquires a fresh token."""
+ if self.auth is not None:
+ self.auth.remove_tokens_for_client()
+ self.http.token = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new conversation with an initial card, never reply to a thread."""
+ try:
+ self._authenticate()
+ self.http.http.timeout = httpx.Timeout(_remaining(self.deadline))
+ await self.api.conversations.create(
+ _ChannelConversationParams(
+ tenant_id=self.config.tenant_id,
+ channel_data={
+ "tenant": {"id": self.config.tenant_id},
+ "team": {"id": destination.team_id},
+ "channel": {"id": destination.channel_id},
+ },
+ activity=MessageActivityInput(
+ attachments=[
+ Attachment(
+ content_type="application/vnd.microsoft.card.adaptive",
+ content=card,
+ )
+ ]
+ ),
+ )
+ )
+ except httpx.HTTPStatusError as ex:
+ error = TeamsTransportError(ex.response.status_code, ex.response.headers)
+ await ex.response.aclose()
+ raise error from None
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout):
+ raise TeamsTransportError(retryable=True) from None
+ except httpx.RequestError:
+ # The connector may have accepted the POST before the connection failed.
+ raise TeamsTransportError() from None
+ except requests.RequestException:
+ # requests is used only for authentication, before the connector POST.
+ raise TeamsTransportError(retryable=True) from None
+ except ValueError:
+ # Includes invalid SDK models/response JSON. Replaying a successful
+ # POST whose response could not be decoded could duplicate delivery.
+ raise TeamsDeliveryError("parameter") from None
Review Comment:
If the response fails to parse, the POST may have already landed (as the comment says), so I think this wants `unknown` rather than `parameter`. A test or two might need to follow.
```suggestion
raise TeamsDeliveryError("unknown") from None
```
##########
superset/migrations/versions/2026-11-02_00-00_7b9d2f8a6c31_add_teams_installations.py:
##########
@@ -0,0 +1,65 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add Teams bot installation persistence.
+
+Revision ID: 7b9d2f8a6c31
+Revises: b8f3a2c91d64
+"""
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects import mysql
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import create_table
+
+revision: str = "7b9d2f8a6c31"
+down_revision: str = "b8f3a2c91d64"
+
+
+def upgrade() -> None:
+ """Add installation metadata without changing alerts or destinations."""
+ create_table(
+ "teams_installations",
+ sa.Column("id", UUIDType(binary=True), nullable=False),
+ sa.Column("tenant_id", UUIDType(binary=True), nullable=False),
+ sa.Column("application_id", UUIDType(binary=True), nullable=False),
+ sa.Column("team_id", sa.String(255), nullable=False),
+ sa.Column("service_url", sa.String(2048), nullable=False),
+ sa.Column("active", sa.Boolean(), nullable=False),
+ sa.Column(
+ "event_at",
+ sa.DateTime()
+ .with_variant(mysql.DATETIME(fsp=6), "mysql")
+ .with_variant(mysql.DATETIME(fsp=6), "mariadb"),
+ nullable=False,
+ ),
+ sa.Column("created_on", sa.DateTime(), nullable=False),
+ sa.Column("changed_on", sa.DateTime(), nullable=False),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint(
+ "tenant_id",
+ "application_id",
+ "team_id",
+ name="uq_teams_installation_identity",
+ ),
+ )
+
+
+def downgrade() -> None:
+ """Remove only the installation metadata table."""
+ op.drop_table("teams_installations")
Review Comment:
There's a `drop_table` helper in `superset.migrations.shared.utils` right next to the `create_table` you're already using. Mind swapping this over to it?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4558238058
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,572 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from functools import lru_cache
+from threading import Lock
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask owns the listening server. SDK authentication is reused, while each
+ callback runs to completion in an operation-scoped event loop. No SDK App,
+ outbound clients, tasks, or separate listening server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
+ or not isinstance(action, str)
+ or action not in actions
+ ):
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+@lru_cache(maxsize=8)
+def _callback_server(
+ process_id: int, application_id: str, tenant_id: str
+) -> tuple[HttpServer, Lock]:
+ """Retain SDK signing-key caches per process and configured identity.
+
+ The process ID avoids inheriting a locked server when a worker forks.
+ The lock serializes use of the SDK's mutable on_request callback.
+ """
+ return HttpServer(_FlaskServerAdapter(), messaging_endpoint=EVENTS_PATH), Lock()
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ Only the SDK server and its signing-key cache survive requests. Request
+ handlers and event loops are released after every callback, and no outbound
+ SDK client is created. Credentials and event bodies are not cache keys.
+ """
+ server, lock = _callback_server(
+ os.getpid(), config.application_id, config.tenant_id
+ )
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = server.adapter
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ response: HttpResponse = await server.handle_request(
+ HttpRequest(body=body, headers=headers)
+ )
+ if response["status"] != 200:
+ return TeamsEventResult(response["status"])
+ return result
+ finally:
+ server.on_request = None
+ await adapter.stop()
+
+ with lock:
+ return asyncio.run(process())
+
+
+# Count every send, including the single 401 replay, against the same retry bound.
+_DELIVERY_ATTEMPTS = 4
+_DELIVERY_TIMEOUT = 60.0
+_DELIVERY_REQUEST_TIMEOUT = 10.0
+
+
+class TeamsDeliveryError(Exception):
+ """Sanitized delivery outcome for mapping to existing notification exceptions."""
+
+ def __init__(
+ self, category: Literal["authorization", "transient", "parameter", "unknown"]
+ ) -> None:
+ """Expose a stable message without response bodies, SQL, tokens, or URLs."""
+ self.category = category
+ messages = {
+ "authorization": "Teams bot authorization failed",
+ "transient": "Teams alert delivery temporarily unavailable",
+ "parameter": "Teams alert delivery was rejected",
+ "unknown": (
+ "Teams alert delivery could not be confirmed. "
+ "It may have been delivered"
+ ),
+ }
+ super().__init__(messages[category])
+
+
+class TeamsTransportError(Exception):
+ """Sanitized HTTP failure with explicit retry safety for status-less errors."""
+
+ def __init__(
+ self,
+ status: int | None = None,
+ headers: httpx.Headers
+ | requests.structures.CaseInsensitiveDict[str]
+ | None = None,
+ *,
+ retryable: bool = False,
+ ) -> None:
+ """Retain only retry headers; never retain a response body or request token."""
+ super().__init__("Teams transport request failed")
+ self.status = status
+ self.retryable = retryable
+ self.retry_after = headers.get("Retry-After") if headers is not None else None
+ self.retry_after_ms = (
+ headers.get("x-ms-retry-after-ms") if headers is not None else None
+ )
+
+
+class TeamsTransport(Protocol):
+ """Replaceable operation-scoped transport; retries live outside SDK calls."""
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new channel root post containing the card."""
+ ...
+
+ async def refresh_auth(self) -> None:
+ """Invalidate cached authentication before a single 401 replay."""
+ ...
+
+
+def _remaining(deadline: float) -> float:
+ """Bound each request by its timeout and remaining delivery budget."""
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise TeamsTransportError(retryable=True)
+ return min(_DELIVERY_REQUEST_TIMEOUT, remaining)
+
+
+class _AuthHttpClient:
+ """MSAL HTTP interface backed by a caller-owned, timeout-bounded session."""
+
+ def __init__(self, session: requests.Session, deadline: float) -> None:
+ """Keep OAuth traffic within the same operation as the channel post."""
+ self.session = session
+ self.deadline = deadline
+
+ def get(self, url: str, **kwargs: Any) -> requests.Response:
+ """Fetch MSAL metadata without leaving a response open."""
+ return self._request("GET", url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> requests.Response:
+ """Acquire tokens without leaving a response open."""
+ return self._request("POST", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
+ """Use normal serialization, explicit timeouts, and sanitized retry errors."""
+ kwargs["timeout"] = _remaining(self.deadline)
+ response = self.session.request(method, url, **kwargs)
+ try:
+ _remaining(self.deadline)
+ # requests eagerly reads responses; MSAL can still read cached JSON
+ # after close. Closing here also covers retryable OAuth errors.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise TeamsTransportError(response.status_code, response.headers)
+ return response
+ finally:
+ response.close()
+
+
+class _ChannelConversationParams(CreateConversationParams):
+ """Include the connector's group flag, absent from the SDK base parameter model."""
+
+ is_group: Literal[True] = True
+
+
+class _SDKTeamsTransport:
+ """Use the SDK create-conversation API with shared, explicitly owned resources."""
+
+ def __init__(
+ self,
+ config: TeamsConfig,
+ service_url: str,
+ http: Client,
+ auth_http: _AuthHttpClient,
+ deadline: float,
+ ) -> None:
+ """Prepare the SDK without constructing a full App or starting a server."""
+ self.config = config
+ self.http = http
+ self.auth_http = auth_http
+ self.deadline = deadline
+ self.auth: ConfidentialClientApplication | None = None
+ self.api = ApiClient(service_url, http)
+
+ def _authenticate(self) -> None:
+ """Acquire a bot token without exposing identity-provider errors."""
+ if self.http.token:
+ return
+ if self.auth is None:
+ self.auth = ConfidentialClientApplication(
+ self.config.application_id,
+ client_credential=self.config.credential,
+ authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
+ http_client=self.auth_http,
+ instance_discovery=False,
+ )
+ result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
+ token = result.get("access_token")
+ if not isinstance(token, str) or not token:
+ status = (
+ 503
+ if result.get("error") in {"temporarily_unavailable", "server_error"}
+ else 401
+ )
+ raise TeamsTransportError(status)
+ self.http.token = token
+
+ async def refresh_auth(self) -> None:
+ """Invalidate MSAL app tokens so the next request acquires a fresh token."""
+ if self.auth is not None:
+ self.auth.remove_tokens_for_client()
+ self.http.token = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new conversation with an initial card, never reply to a thread."""
+ try:
+ self._authenticate()
+ self.http.http.timeout = httpx.Timeout(_remaining(self.deadline))
+ await self.api.conversations.create(
+ _ChannelConversationParams(
+ tenant_id=self.config.tenant_id,
+ channel_data={
+ "tenant": {"id": self.config.tenant_id},
+ "team": {"id": destination.team_id},
+ "channel": {"id": destination.channel_id},
+ },
+ activity=MessageActivityInput(
+ attachments=[
+ Attachment(
+ content_type="application/vnd.microsoft.card.adaptive",
+ content=card,
+ )
+ ]
+ ),
+ )
+ )
+ except httpx.HTTPStatusError as ex:
+ error = TeamsTransportError(ex.response.status_code, ex.response.headers)
+ await ex.response.aclose()
+ raise error from None
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout):
+ raise TeamsTransportError(retryable=True) from None
+ except httpx.RequestError:
+ # The connector may have accepted the POST before the connection failed.
+ raise TeamsTransportError() from None
+ except requests.RequestException:
+ # requests is used only for authentication, before the connector POST.
+ raise TeamsTransportError(retryable=True) from None
+ except ValueError:
+ # Includes invalid SDK models/response JSON. Replaying a successful
+ # POST whose response could not be decoded could duplicate delivery.
+ raise TeamsDeliveryError("parameter") from None
Review Comment:
Done :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4363963358
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,538 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask registers its route once at startup. Each request creates a fresh SDK
+ authentication server; its handler runs to completion in an operation-scoped
+ event loop. No SDK App, outbound clients, tasks, or separate server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ if body.get("type") != "installationUpdate" or body.get("action") not in (
Review Comment:
This returns 400 for any action other than `add` or `remove`, but Teams also sends `add-upgrade` and `remove-upgrade` installation updates when an app upgrade adds or removes the bot. If the bot is added to a team through an upgrade, no installation record is created and alerts keep failing with "No active Teams bot installation" until it is uninstalled and reinstalled. Should the upgrade variants be accepted and mapped to add/remove?
##########
superset/migrations/versions/2026-10-19_00-00_7b9d2f8a6c31_add_teams_installations.py:
##########
@@ -0,0 +1,58 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add Teams bot installation persistence.
+
+Revision ID: 7b9d2f8a6c31
+Revises: d623a0cb6bb0
+"""
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import create_table
+
+revision: str = "7b9d2f8a6c31"
+down_revision: str = "d623a0cb6bb0"
+
+
+def upgrade() -> None:
+ """Add installation metadata without changing alerts or destinations."""
+ create_table(
+ "teams_installations",
+ sa.Column("id", UUIDType(binary=True), nullable=False),
+ sa.Column("tenant_id", UUIDType(binary=True), nullable=False),
+ sa.Column("application_id", UUIDType(binary=True), nullable=False),
+ sa.Column("team_id", sa.String(255), nullable=False),
+ sa.Column("service_url", sa.String(2048), nullable=False),
+ sa.Column("active", sa.Boolean(), nullable=False),
+ sa.Column("event_at", sa.DateTime(), nullable=False),
Review Comment:
On MySQL, `sa.DateTime()` creates a `DATETIME` column with no fractional seconds, but `TeamsInstallationStore._apply()` compares full-precision event timestamps against `event_at`. A removal at `12:00:00.200Z` is stored as `12:00:00`, so a delayed install stamped `12:00:00.100Z` still passes the `event_at < incoming` check and reactivates a bot that was already removed. Should `event_at` (here and in `models.py`) use a fractional-seconds type, for example `mysql.DATETIME(fsp=6)` via `with_variant`, and should the lifecycle tests cover sub-second timestamps?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4366333675
##########
superset/integrations/teams/api.py:
##########
@@ -0,0 +1,128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Independently authenticated, installation-only Teams bot callback."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING
+
+from flask import Blueprint, current_app, Flask, request, Response
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+from werkzeug.exceptions import RequestEntityTooLarge
+
+from superset.extensions import csrf, db, feature_flag_manager
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsConfigError,
+)
+from superset.integrations.teams.store import TeamsInstallationStore
+
+if TYPE_CHECKING:
+ from superset.integrations.teams.adapter import TeamsInstallationEvent
+
+_MAX_EVENT_BYTES = 256 * 1024
+
+logger = logging.getLogger(__name__)
+blueprint = Blueprint("teams", __name__)
+
+
+def _check_event_body_size() -> None:
+ """Bound body reading and reject oversized input before JSON parsing."""
+ configured_limit = request.max_content_length
+ limit = (
+ min(_MAX_EVENT_BYTES, configured_limit)
+ if configured_limit is not None
+ else _MAX_EVENT_BYTES
+ )
+ if request.content_length is not None and request.content_length > limit:
+ raise RequestEntityTooLarge()
+ # Werkzeug can truncate lengthless streams at the limit without raising.
+ # Read one lookahead byte through Flask's bounded stream before parsing JSON.
+ request.max_content_length = limit + 1
Review Comment:
`Request.max_content_length` only became writable in Flask 3.1, but `pyproject.toml` still allows `flask>=2.2.5`. On an older supported Flask this assignment raises `AttributeError`, so every install/remove callback returns 500 before authentication and no installation is ever recorded, which leaves alerts undeliverable. Should the `teams` extra require Flask 3.1+, or should the bounded read avoid assigning to the request?
##########
superset/commands/report/update.py:
##########
@@ -496,6 +496,8 @@ def validate(self) -> None: # noqa: C901
self._properties.get("report_format", self._model.report_format),
exceptions,
)
+ # Always validate the effective Teams recipients, even for metadata-only PUTs.
+ self.validate_teams_recipients(exceptions)
Review Comment:
This now runs for every PUT, including `{"active": false}`. If an operator disables `ALERT_REPORT_TEAMS`, clears the Teams config, or removes a destination key that an existing alert still references, the owner can no longer pause that alert: validation rejects the request and the schedule keeps running its queries and other deliveries. Should deactivation (and edits that leave recipients untouched) skip the Teams deliverability check?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-6783278808
@sadpandajoe Seems this has all the stamps needed to merge. Just bumping this in case it got lost :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-7112272389
### ⚠️ Possible DB migration conflict
@KristiDodaj the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-7085307043
@rusackas should be good for another look whenever you have a chance 🙏
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4368562620
##########
superset/commands/report/update.py:
##########
@@ -131,7 +131,7 @@ def _normalize_recipients(recipients: Any) -> list[tuple[str, str]]:
config = json.loads(config)
except json.JSONDecodeError:
pass
- if isinstance(config, dict):
+ if recipient_type == ReportRecipientType.EMAIL and isinstance(config, dict):
Review Comment:
Limiting the empty `ccTarget`/`bccTarget` stripping to Email means a Slack/SlackV2/Webhook recipient stored as `{"target": "C123"}` (for example created through the API) now compares as changed when the modal re-saves it with `ccTarget: ""` and `bccTarget: ""` (`AlertReportModal.tsx` still sends them for every non-Teams method). A non-admin editor who only renames a schedule that runs as another user then gets `ReportScheduleRunAsContentForbiddenError`; `test_empty_cc_and_bcc_change_non_email_recipients` now asserts that rejection. Is that intended, or should the empty-value normalization stay for non-Teams types and only exclude Teams?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-6307972429
### ⚠️ Possible DB migration conflict
@KristiDodaj the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4397454249
##########
superset/migrations/versions/2026-10-19_00-00_7b9d2f8a6c31_add_teams_installations.py:
##########
@@ -0,0 +1,65 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add Teams bot installation persistence.
+
+Revision ID: 7b9d2f8a6c31
+Revises: 3740c7bcb2c6
+"""
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects import mysql
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import create_table
+
+revision: str = "7b9d2f8a6c31"
+down_revision: str = "3740c7bcb2c6"
Review Comment:
`f72b6e9c104a` (`add_oauth2_token_management_indexes`) already on master also has `down_revision = "3740c7bcb2c6"`, so with this parent the merged tree has two Alembic heads and `superset db upgrade` fails with a multiple-heads error, whether or not Teams is enabled. Should this be re-parented onto `f72b6e9c104a` (and the revision file name/date kept after it)?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4414438306
##########
superset/reports/notifications/teams.py:
##########
@@ -0,0 +1,160 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Attachment-free alert delivery to configured Teams standard channels."""
+
+from typing import Any
+from urllib.parse import urlsplit
+
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.extensions import db
+from superset.integrations.teams.config import (
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.integrations.teams.validation import (
+ TeamsRecipientValidationError,
+ validate_teams_recipient,
+)
+from superset.reports.models import ReportRecipientType
+from superset.reports.notifications.base import BaseNotification, NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+
+
+def build_teams_card(content: NotificationContent) -> dict[str, Any]:
+ """Build a card using structured data, omitting raw execution diagnostics."""
+ body: list[dict[str, Any]] = [
+ {
+ "type": "TextBlock",
+ "text": content.name,
+ "weight": "Bolder",
+ "size": "Medium",
+ "wrap": True,
+ },
+ ]
+ if content.description:
+ body.append({"type": "TextBlock", "text": content.description, "wrap": True})
+ if content.text:
+ body.append(
+ {
+ "type": "TextBlock",
+ "text": "Alert execution failed. Contact the alert owner for details.",
Review Comment:
This failure text (and the "Open in Superset" button title further down) is hard-coded English, while the email and webhook notifications run their equivalent "Contact the report owner for error details." through `flask_babel.gettext`. On a non-English deployment, Teams recipients always get English here, and translators have nothing to localize since neither string is in `messages.pot`. Should these two go through `__()` and be added to the catalog like the other notification text?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-7024031764
### ⚠️ Possible DB migration conflict
@KristiDodaj the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4638104395
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,578 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from functools import lru_cache
+from threading import Lock
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask owns the listening server. SDK authentication is reused, while each
+ callback runs to completion in an operation-scoped event loop. No SDK App,
+ outbound clients, tasks, or separate listening server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if not isinstance(action, str) or action not in actions:
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+@lru_cache(maxsize=8)
+def _callback_server(
+ process_id: int, application_id: str, tenant_id: str
+) -> tuple[HttpServer, Lock]:
+ """Retain SDK signing-key caches per process and configured identity.
+
+ The process ID avoids inheriting a locked server when a worker forks.
+ The lock serializes use of the SDK's mutable on_request callback.
+ """
+ return HttpServer(_FlaskServerAdapter(), messaging_endpoint=EVENTS_PATH), Lock()
+
+
+_CALLBACK_LOCK_TIMEOUT = 1.0
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ Only the SDK server and its signing-key cache survive requests. Request
+ handlers and event loops are released after every callback, and no outbound
+ SDK client is created. Credentials and event bodies are not cache keys.
+ """
+ server, lock = _callback_server(
+ os.getpid(), config.application_id, config.tenant_id
+ )
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = server.adapter
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ if not _allowed_token(config, event):
+ result = TeamsEventResult(403)
+ elif body.get("type") != "installationUpdate":
+ result = TeamsEventResult(200)
+ else:
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ response: HttpResponse = await server.handle_request(
+ HttpRequest(body=body, headers=headers)
+ )
Review Comment:
Good catch! We now reject non-connector issuers before acquiring the lock
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "rusackas (via GitHub) via notifications" <no...@superset.apache.org>.
rusackas merged PR #45508:
URL: https://github.com/apache/superset/pull/45508
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4406260406
##########
tests/unit_tests/integrations/teams/delivery_test.py:
##########
@@ -0,0 +1,976 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Teams notification formatting, resolution, retry, and SDK delivery tests."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import importlib.util
+import threading
+import time
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager, nullcontext
+from datetime import datetime, timedelta, timezone
+from email.utils import format_datetime
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+import requests
+from billiard.exceptions import SoftTimeLimitExceeded
+from flask import current_app, Flask
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import validation as teams_validation
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.models import TeamsInstallation
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.reports.models import ReportRecipients, ReportRecipientType
+from superset.reports.notifications import create_notification, teams as notifications
+from superset.reports.notifications.base import NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+from superset.utils import json
+
+if importlib.util.find_spec("microsoft_teams") is None:
+ pytest.skip("Optional Teams SDK is not installed", allow_module_level=True)
+
+adapter = importlib.import_module("superset.integrations.teams.adapter")
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+SERVICE_URL = "https://smba.trafficmanager.net/amer/"
+
+
+@pytest.fixture
+def configured(teams_config: dict[str, Any]) -> TeamsConfig:
+ """Parse the same deployment configuration used by real notifications."""
+ config = parse_teams_config(teams_config)
+ assert config is not None
+ return config
+
+
+@pytest.fixture
+def content() -> NotificationContent:
+ """Include difficult text to verify normal structured JSON serialization."""
+ return NotificationContent(
+ name='Alert "Revenue"\nCafé 東京 🚨',
+ description='Description "quoted"\n第二行',
+ header_data={
+ "notification_type": "Alert",
+ "notification_format": "NONE",
+ "editors": [],
+ "notification_source": None,
+ "chart_id": None,
+ "dashboard_id": None,
+ "slack_channels": None,
+ "execution_id": None,
+ },
+ url="https://superset.example/chart/42/",
+ )
+
+
+@pytest.fixture
+def notification_context(
+ teams_config: dict[str, Any],
+ teams_engine: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[SimpleNamespace]:
+ """Use the real installation table and resolve through the notification class."""
+ app = Flask(__name__)
+ app.config.update(
+ ALERT_REPORTS_TEAMS=teams_config, FEATURE_FLAGS={"ALERT_REPORT_TEAMS": True}
+ )
+ engine = teams_engine
+ with Session(engine) as session:
+ TeamsInstallationStore(session).install(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ session.commit()
+ monkeypatch.setattr(notifications, "db", SimpleNamespace(engine=engine))
+ monkeypatch.setattr(
+ teams_validation.feature_flag_manager,
+ "is_feature_enabled",
+ lambda name: current_app.config["FEATURE_FLAGS"].get(name, False),
+ )
+ send = MagicMock()
+ monkeypatch.setattr(notifications, "_send_to_teams", send)
+ with app.app_context():
+ yield SimpleNamespace(app=app, engine=engine, send=send)
+
+
+def recipient(target: str = "ops") -> ReportRecipients:
+ """Recipients store only a configured destination key."""
+ return ReportRecipients(
+ type=ReportRecipientType.TEAMS,
+ recipient_config_json=json.dumps({"target": target}),
+ )
+
+
+def test_factory_resolves_active_installation_and_formats_card(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+) -> None:
+ notification = create_notification(recipient(), content)
+ assert isinstance(notification, notifications.TeamsNotification)
+ notification.send()
+ config, destination, service_url, card = notification_context.send.call_args.args
+ assert config.credential == "deployment-secret"
+ assert destination.key == "ops"
+ assert destination.channel_id == "channel-1"
+ assert service_url == SERVICE_URL
+ assert card["body"][0]["text"] == content.name
+ assert card["body"][1]["text"] == content.description
+ assert card["actions"][0]["url"] == content.url
+ assert "deployment-secret" not in json.dumps(card)
+
+
+@pytest.mark.parametrize(
+ "mode", ["inactive", "missing", "other-tenant", "other-application"]
+)
+def test_installation_must_be_active_for_exact_identity(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+ mode: str,
+) -> None:
+ with Session(notification_context.engine) as session:
+ store = TeamsInstallationStore(session)
+ if mode == "inactive":
+ store.remove(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ else:
+ session.query(TeamsInstallation).delete()
+ other = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+ if mode != "missing":
+ store.install(
+ other if mode == "other-tenant" else TENANT,
+ other if mode == "other-application" else APPLICATION,
+ "team-1",
+ SERVICE_URL,
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ with pytest.raises(NotificationAuthorizationException):
+ notifications.TeamsNotification(recipient(), content).send()
+ notification_context.send.assert_not_called()
+
+
+class FakeTransport:
+ """Deterministic replaceable transport for bounded retry policy tests."""
+
+ def __init__(self, errors: list[Exception | None]) -> None:
+ """Consume one outcome for each root post attempt."""
+ self.errors = iter(errors)
+ self.posts: list[tuple[TeamsDestination, dict[str, Any]]] = []
+ self.refreshes = 0
+ self.closed = False
+ self.loop: asyncio.AbstractEventLoop | None = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Record every fresh root-post attempt."""
+ self.posts.append((destination, card))
+ error = next(self.errors)
+ if error:
+ raise error
+
+ async def refresh_auth(self) -> None:
+ """Record a cache invalidation without contacting Entra."""
+ self.refreshes += 1
+
+ @asynccontextmanager
+ async def factory(
+ self, config: TeamsConfig, service_url: str, deadline: float
+ ) -> AsyncIterator[FakeTransport]:
+ """Track operation cleanup on both successful and failed delivery."""
+ self.loop = asyncio.get_running_loop()
+ try:
+ yield self
+ finally:
+ self.closed = True
+
+
+@pytest.fixture
+def retry_clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
+ """Advance retry time without actually sleeping."""
+ elapsed = [0.0]
+ sleeps: list[float] = []
+ monkeypatch.setattr(adapter, "monotonic", lambda: elapsed[0])
+
+ async def sleep(delay: float) -> None:
+ """Advance the same clock used by the retry budget."""
+ elapsed[0] += delay
+ sleeps.append(delay)
+
+ monkeypatch.setattr(adapter.asyncio, "sleep", sleep)
+ return sleeps
+
+
+@pytest.mark.parametrize(
+ "status,retryable",
+ [
+ (None, False),
+ (None, True),
+ (408, False),
+ (429, False),
+ (500, False),
+ (502, False),
+ (503, False),
+ (504, False),
+ ],
+)
+def test_transport_failures_respect_retry_safety_and_attempt_bound(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ status: int | None,
+ retryable: bool,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status, retryable=retryable)] * 4
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ ambiguous = status is None and not retryable
+ assert exc.value.category == ("unknown" if ambiguous else "transient")
+ assert len(transport.posts) == (1 if ambiguous else 4)
+ assert retry_clock == ([] if ambiguous else [1.0, 2.0, 4.0])
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "headers,expected",
+ [
+ ({"Retry-After": "3"}, 3.0),
+ ({"x-ms-retry-after-ms": "1500"}, 1.5),
+ ({"Retry-After": "2", "x-ms-retry-after-ms": "3000"}, 3.0),
+ ({"Retry-After": "invalid"}, 1.0),
+ ],
+)
+def test_microsoft_retry_delays_are_respected(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ headers: dict[str, str],
+ expected: float,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers(headers)), None]
+ )
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert retry_clock == [expected]
+ assert len(transport.posts) == 2
+ assert transport.closed
+
+
+def test_retry_after_http_date() -> None:
+ retry_at = datetime.now(timezone.utc) + timedelta(seconds=5)
+ error = adapter.TeamsTransportError(
+ 429, httpx.Headers({"Retry-After": format_datetime(retry_at, usegmt=True)})
+ )
+ assert 3.0 <= adapter._retry_delay(error, 0) <= 5.0
+
+
+def test_excessive_server_delay_is_not_shortened(
+ configured: TeamsConfig, retry_clock: list[float]
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers({"Retry-After": "120"}))]
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == "transient"
+ assert len(transport.posts) == 1
+ assert retry_clock == []
+ assert transport.closed
+
+
+@pytest.mark.parametrize(
+ "outcomes,category,posts,refreshes",
+ [
+ ([401, None], None, 2, 1),
+ ([401, 401], "authorization", 2, 1),
+ ([403], "authorization", 1, 0),
+ ([400], "parameter", 1, 0),
+ ([404], "parameter", 1, 0),
+ ([302], "parameter", 1, 0),
+ ([401, 503, 503, None], None, 4, 1),
+ ([503, 503, 503, 401], "authorization", 4, 0),
+ ],
+)
+def test_one_authentication_refresh_and_permanent_errors(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ outcomes: list[int | None],
+ category: str | None,
+ posts: int,
+ refreshes: int,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status) if status else None for status in outcomes]
+ )
+ if category:
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == category
+ else:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert len(transport.posts) == posts
+ assert transport.refreshes == refreshes
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "category,exception",
+ [
+ ("authorization", NotificationAuthorizationException),
+ ("transient", NotificationTransientError),
+ ("parameter", NotificationParamException),
+ ("unknown", NotificationError),
+ ],
+)
+def test_transport_errors_map_to_existing_notification_exceptions(
+ configured: TeamsConfig,
+ monkeypatch: pytest.MonkeyPatch,
+ category: str,
+ exception: type[Exception],
+) -> None:
+ monkeypatch.setattr(
+ adapter,
+ "deliver_teams_alert",
+ MagicMock(side_effect=adapter.TeamsDeliveryError(category)),
+ )
+ with pytest.raises(exception) as exc:
Review Comment:
Good catch. Added the exact type assertion so the unknown case fails if it gets mapped to a transient error
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4394686178
##########
tests/unit_tests/integrations/teams/delivery_test.py:
##########
@@ -0,0 +1,971 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Teams notification formatting, resolution, retry, and SDK delivery tests."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import importlib.util
+import threading
+import time
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager, nullcontext
+from datetime import datetime, timedelta, timezone
+from email.utils import format_datetime
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+import requests
+from billiard.exceptions import SoftTimeLimitExceeded
+from flask import current_app, Flask
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import validation as teams_validation
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.models import TeamsInstallation
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.reports.models import ReportRecipients, ReportRecipientType
+from superset.reports.notifications import create_notification, teams as notifications
+from superset.reports.notifications.base import NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+from superset.utils import json
+
+if importlib.util.find_spec("microsoft_teams") is None:
+ pytest.skip("Optional Teams SDK is not installed", allow_module_level=True)
+
+adapter = importlib.import_module("superset.integrations.teams.adapter")
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+SERVICE_URL = "https://smba.trafficmanager.net/amer/"
+
+
+@pytest.fixture
+def configured(teams_config: dict[str, Any]) -> TeamsConfig:
+ """Parse the same deployment configuration used by real notifications."""
+ config = parse_teams_config(teams_config)
+ assert config is not None
+ return config
+
+
+@pytest.fixture
+def content() -> NotificationContent:
+ """Include difficult text to verify normal structured JSON serialization."""
+ return NotificationContent(
+ name='Alert "Revenue"\nCafé 東京 🚨',
+ description='Description "quoted"\n第二行',
+ header_data={
+ "notification_type": "Alert",
+ "notification_format": "NONE",
+ "editors": [],
+ "notification_source": None,
+ "chart_id": None,
+ "dashboard_id": None,
+ "slack_channels": None,
+ "execution_id": None,
+ },
+ url="https://superset.example/chart/42/",
+ )
+
+
+@pytest.fixture
+def notification_context(
+ teams_config: dict[str, Any],
+ teams_engine: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[SimpleNamespace]:
+ """Use the real installation table and resolve through the notification class."""
+ app = Flask(__name__)
+ app.config.update(
+ ALERT_REPORTS_TEAMS=teams_config, FEATURE_FLAGS={"ALERT_REPORT_TEAMS": True}
+ )
+ engine = teams_engine
+ with Session(engine) as session:
+ TeamsInstallationStore(session).install(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ session.commit()
+ monkeypatch.setattr(notifications, "db", SimpleNamespace(engine=engine))
+ monkeypatch.setattr(
+ teams_validation.feature_flag_manager,
+ "is_feature_enabled",
+ lambda name: current_app.config["FEATURE_FLAGS"].get(name, False),
+ )
+ send = MagicMock()
+ monkeypatch.setattr(notifications, "_send_to_teams", send)
+ with app.app_context():
+ yield SimpleNamespace(app=app, engine=engine, send=send)
+
+
+def recipient(target: str = "ops") -> ReportRecipients:
+ """Recipients store only a configured destination key."""
+ return ReportRecipients(
+ type=ReportRecipientType.TEAMS,
+ recipient_config_json=json.dumps({"target": target}),
+ )
+
+
+def test_factory_resolves_active_installation_and_formats_card(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+) -> None:
+ notification = create_notification(recipient(), content)
+ assert isinstance(notification, notifications.TeamsNotification)
+ notification.send()
+ config, destination, service_url, card = notification_context.send.call_args.args
+ assert config.credential == "deployment-secret"
+ assert destination.key == "ops"
+ assert destination.channel_id == "channel-1"
+ assert service_url == SERVICE_URL
+ assert card["body"][0]["text"] == content.name
+ assert card["body"][1]["text"] == content.description
+ assert card["actions"][0]["url"] == content.url
+ assert "deployment-secret" not in json.dumps(card)
+
+
+@pytest.mark.parametrize(
+ "mode", ["inactive", "missing", "other-tenant", "other-application"]
+)
+def test_installation_must_be_active_for_exact_identity(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+ mode: str,
+) -> None:
+ with Session(notification_context.engine) as session:
+ store = TeamsInstallationStore(session)
+ if mode == "inactive":
+ store.remove(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ else:
+ session.query(TeamsInstallation).delete()
+ other = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+ if mode != "missing":
+ store.install(
+ other if mode == "other-tenant" else TENANT,
+ other if mode == "other-application" else APPLICATION,
+ "team-1",
+ SERVICE_URL,
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ with pytest.raises(NotificationAuthorizationException):
+ notifications.TeamsNotification(recipient(), content).send()
+ notification_context.send.assert_not_called()
+
+
+class FakeTransport:
+ """Deterministic replaceable transport for bounded retry policy tests."""
+
+ def __init__(self, errors: list[Exception | None]) -> None:
+ """Consume one outcome for each root post attempt."""
+ self.errors = iter(errors)
+ self.posts: list[tuple[TeamsDestination, dict[str, Any]]] = []
+ self.refreshes = 0
+ self.closed = False
+ self.loop: asyncio.AbstractEventLoop | None = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Record every fresh root-post attempt."""
+ self.posts.append((destination, card))
+ error = next(self.errors)
+ if error:
+ raise error
+
+ async def refresh_auth(self) -> None:
+ """Record a cache invalidation without contacting Entra."""
+ self.refreshes += 1
+
+ @asynccontextmanager
+ async def factory(
+ self, config: TeamsConfig, service_url: str, deadline: float
+ ) -> AsyncIterator[FakeTransport]:
+ """Track operation cleanup on both successful and failed delivery."""
+ self.loop = asyncio.get_running_loop()
+ try:
+ yield self
+ finally:
+ self.closed = True
+
+
+@pytest.fixture
+def retry_clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
+ """Advance retry time without actually sleeping."""
+ elapsed = [0.0]
+ sleeps: list[float] = []
+ monkeypatch.setattr(adapter, "monotonic", lambda: elapsed[0])
+
+ async def sleep(delay: float) -> None:
+ """Advance the same clock used by the retry budget."""
+ elapsed[0] += delay
+ sleeps.append(delay)
+
+ monkeypatch.setattr(adapter.asyncio, "sleep", sleep)
+ return sleeps
+
+
+@pytest.mark.parametrize(
+ "status,retryable",
+ [
+ (None, False),
+ (None, True),
+ (408, False),
+ (429, False),
+ (500, False),
+ (502, False),
+ (503, False),
+ (504, False),
+ ],
+)
+def test_transport_failures_respect_retry_safety_and_attempt_bound(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ status: int | None,
+ retryable: bool,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status, retryable=retryable)] * 4
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ ambiguous = status is None and not retryable
+ assert exc.value.category == ("unknown" if ambiguous else "transient")
+ assert len(transport.posts) == (1 if ambiguous else 4)
+ assert retry_clock == ([] if ambiguous else [1.0, 2.0, 4.0])
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "headers,expected",
+ [
+ ({"Retry-After": "3"}, 3.0),
+ ({"x-ms-retry-after-ms": "1500"}, 1.5),
+ ({"Retry-After": "2", "x-ms-retry-after-ms": "3000"}, 3.0),
+ ({"Retry-After": "invalid"}, 1.0),
+ ],
+)
+def test_microsoft_retry_delays_are_respected(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ headers: dict[str, str],
+ expected: float,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers(headers)), None]
+ )
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert retry_clock == [expected]
+ assert len(transport.posts) == 2
+ assert transport.closed
+
+
+def test_retry_after_http_date() -> None:
+ retry_at = datetime.now(timezone.utc) + timedelta(seconds=5)
+ error = adapter.TeamsTransportError(
+ 429, httpx.Headers({"Retry-After": format_datetime(retry_at, usegmt=True)})
+ )
+ assert 3.0 <= adapter._retry_delay(error, 0) <= 5.0
+
+
+def test_excessive_server_delay_is_not_shortened(
+ configured: TeamsConfig, retry_clock: list[float]
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers({"Retry-After": "120"}))]
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == "transient"
+ assert len(transport.posts) == 1
+ assert retry_clock == []
+ assert transport.closed
+
+
+@pytest.mark.parametrize(
+ "outcomes,category,posts,refreshes",
+ [
+ ([401, None], None, 2, 1),
+ ([401, 401], "authorization", 2, 1),
+ ([403], "authorization", 1, 0),
+ ([400], "parameter", 1, 0),
+ ([404], "parameter", 1, 0),
+ ([302], "parameter", 1, 0),
+ ([401, 503, 503, None], None, 4, 1),
+ ([503, 503, 503, 401], "authorization", 4, 0),
+ ],
+)
+def test_one_authentication_refresh_and_permanent_errors(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ outcomes: list[int | None],
+ category: str | None,
+ posts: int,
+ refreshes: int,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status) if status else None for status in outcomes]
+ )
+ if category:
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == category
+ else:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert len(transport.posts) == posts
+ assert transport.refreshes == refreshes
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "category,exception",
+ [
+ ("authorization", NotificationAuthorizationException),
+ ("transient", NotificationTransientError),
+ ("parameter", NotificationParamException),
+ ("unknown", NotificationError),
+ ],
+)
+def test_transport_errors_map_to_existing_notification_exceptions(
+ configured: TeamsConfig,
+ monkeypatch: pytest.MonkeyPatch,
+ category: str,
+ exception: type[Exception],
+) -> None:
+ monkeypatch.setattr(
+ adapter,
+ "deliver_teams_alert",
+ MagicMock(side_effect=adapter.TeamsDeliveryError(category)),
+ )
+ with pytest.raises(exception) as exc:
+ notifications._send_to_teams(
+ configured, configured.destinations[0], SERVICE_URL, {}
+ )
+ assert exc.value.__cause__ is None
+
+
+def _sdk_post_response(status: int) -> httpx.Response:
+ """Script a successful root, malformed success, or failing connector response."""
+ if status == 201:
+ return httpx.Response(
+ status, json={"id": "new-thread", "activityId": "root-message"}
+ )
+ if status == 299:
+ return httpx.Response(201, json={"malformed": "success response"})
+ return httpx.Response(
+ status, headers={"Retry-After": "2"}, json={"error": "secret SQL diagnostic"}
+ )
+
+
+@pytest.fixture
+def sdk_network(
+ monkeypatch: pytest.MonkeyPatch, retry_clock: list[float]
+) -> SimpleNamespace:
+ """Run real MSAL and SDK serializers against offline HTTP endpoints."""
+ state = SimpleNamespace(
+ posts=[],
+ tokens=0,
+ oauth_responses=[],
+ auth_sessions=[],
+ clients=[],
+ statuses=[],
+ oauth_error=None,
+ )
+
+ class TrackedResponse(requests.Response):
+ """Track closure of metadata and token HTTP responses."""
+
+ closed = False
+
+ def close(self) -> None:
+ """Record deterministic cleanup even on OAuth failures."""
+ super().close()
+ self.closed = True
+
+ class AuthSession(requests.Session):
+ """Provide real requests response objects to MSAL's HTTP contract."""
+
+ closed = False
+
+ def __init__(self) -> None:
+ """Record operation-owned sessions."""
+ super().__init__()
+ state.auth_sessions.append(self)
+
+ def request(
+ self, method: Any, url: Any, *args: Any, **kwargs: Any
+ ) -> requests.Response:
+ """Answer only known Microsoft metadata and client-credential calls."""
+ assert 0 < kwargs["timeout"] <= 10
+ response = TrackedResponse()
+ response.status_code = 200
+ response.url = url
+ if method == "GET":
+ assert (
+ url
+ == f"https://login.microsoftonline.com/{TENANT}/v2.0/.well-known/openid-configuration"
+ )
+ data: dict[str, Any] = {
+ "authorization_endpoint": f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/authorize",
+ "token_endpoint": f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token",
+ "issuer": f"https://login.microsoftonline.com/{TENANT}/v2.0",
+ }
+ else:
+ assert method == "POST"
+ assert (
+ url
+ == f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token"
+ )
+ assert kwargs["data"]["grant_type"] == "client_credentials"
+ assert (
+ kwargs["data"]["scope"] == "https://api.botframework.com/.default"
+ )
+ state.tokens += 1
+ data = {
+ "access_token": f"token-{state.tokens}",
+ "token_type": "Bearer",
+ "expires_in": 3600,
+ }
+ if state.oauth_error:
+ response.status_code = 400
+ data = {
+ "error": "invalid_client",
Review Comment:
The OAuth stub only ever returns `invalid_client`, so the `temporarily_unavailable` / `server_error` -> 503 branch in `_authenticate` (adapter.py) is never exercised. If that mapping were dropped, every transient identity-provider outage would be reported as an authorization failure and tested as passing. Could you add a case where the token endpoint returns `temporarily_unavailable` (or `server_error`) and assert the delivery fails as transient after the retries, with no connector POST?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4372942419
##########
superset-frontend/src/features/alerts/notificationMethods.ts:
##########
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { NotificationMethodOption, NotificationSetting } from './types';
+
+const isSlackMethod = (method: NotificationMethodOption | undefined) =>
+ method === NotificationMethodOption.Slack ||
+ method === NotificationMethodOption.SlackV2;
+
+export function getNotificationMethodOptions(
+ available: NotificationMethodOption[],
+ settings: NotificationSetting[],
+ currentIndex?: number,
+): NotificationMethodOption[] {
+ const selected =
+ currentIndex === undefined ? undefined : settings[currentIndex]?.method;
+ const options = available.filter(
+ method =>
+ method === NotificationMethodOption.Teams ||
Review Comment:
Good catch. Added backend validation to reject repeated Teams destination keys, covering both UI and API saves. Existing alerts can still be paused or have metadata edited
##########
superset-frontend/src/features/alerts/AlertReportModal.test.tsx:
##########
@@ -4662,3 +4665,406 @@ test('global attachment policy hides both the alert toggle and attachment contro
);
}
});
+
+test('Teams preserves separate destination entries and serializes only their keys', async () => {
Review Comment:
Agreed, updated it to switch the first row from Teams to Email and verify the saved payload still includes the unchanged finance Teams recipient
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4372667916
##########
superset-frontend/src/features/alerts/notificationMethods.ts:
##########
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { NotificationMethodOption, NotificationSetting } from './types';
+
+const isSlackMethod = (method: NotificationMethodOption | undefined) =>
+ method === NotificationMethodOption.Slack ||
+ method === NotificationMethodOption.SlackV2;
+
+export function getNotificationMethodOptions(
+ available: NotificationMethodOption[],
+ settings: NotificationSetting[],
+ currentIndex?: number,
+): NotificationMethodOption[] {
+ const selected =
+ currentIndex === undefined ? undefined : settings[currentIndex]?.method;
+ const options = available.filter(
+ method =>
+ method === NotificationMethodOption.Teams ||
Review Comment:
Teams is exempted from the one-per-method filter here, `TeamsDestinationSelect` doesn't hide keys already chosen in another row, and `validate_teams_recipients` in `commands/report/base.py` doesn't reject repeated keys. If an editor adds two Teams rows and picks `ops` in both, the save succeeds and each run posts two identical cards to the same channel. Should the select exclude keys used by other rows, or the backend reject duplicate Teams destination keys?
##########
superset-frontend/src/features/alerts/AlertReportModal.test.tsx:
##########
@@ -4662,3 +4665,406 @@ test('global attachment policy hides both the alert toggle and attachment contro
);
}
});
+
+test('Teams preserves separate destination entries and serializes only their keys', async () => {
Review Comment:
This test saves two preloaded Teams rows without changing either row's method, so it doesn't cover the removal of the old "drop trailing rows when a method changes" behavior in `updateNotificationSetting`. If that truncation came back, the test would still pass. Could you add a case that loads `ops` and `finance`, switches the first row to Email with an address, saves, and asserts the PUT body contains both the new Email recipient and the unchanged `finance` Teams recipient?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-6589649723
### ⚠️ Possible DB migration conflict
@KristiDodaj the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-6282049532
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | e48ef27574d1eef6bc3a6b83123c398f5436579f |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6ad6d3b74be758b0bd7a596e |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-45508--superset-docs-preview.netlify.app](https://deploy-preview-45508--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
|<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#q1YqKMrPLShRslJS0lFKKkrMS84AstNSE0tKi1L1S1ITc4t1E3NSi0qKgfIpqQU5-ZWeKUAVZokpZinGSeYmSanmphZJBkkp5ommlmapSrUA) |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-45508--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4419965646
##########
superset/reports/notifications/teams.py:
##########
@@ -0,0 +1,160 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Attachment-free alert delivery to configured Teams standard channels."""
+
+from typing import Any
+from urllib.parse import urlsplit
+
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.extensions import db
+from superset.integrations.teams.config import (
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.integrations.teams.validation import (
+ TeamsRecipientValidationError,
+ validate_teams_recipient,
+)
+from superset.reports.models import ReportRecipientType
+from superset.reports.notifications.base import BaseNotification, NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+
+
+def build_teams_card(content: NotificationContent) -> dict[str, Any]:
+ """Build a card using structured data, omitting raw execution diagnostics."""
+ body: list[dict[str, Any]] = [
+ {
+ "type": "TextBlock",
+ "text": content.name,
+ "weight": "Bolder",
+ "size": "Medium",
+ "wrap": True,
+ },
+ ]
+ if content.description:
+ body.append({"type": "TextBlock", "text": content.description, "wrap": True})
+ if content.text:
+ body.append(
+ {
+ "type": "TextBlock",
+ "text": "Alert execution failed. Contact the alert owner for details.",
Review Comment:
Addressed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4558242729
##########
superset/reports/notifications/teams.py:
##########
@@ -0,0 +1,163 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Attachment-free alert delivery to configured Teams standard channels."""
+
+from typing import Any
+from urllib.parse import urlsplit
+
+from flask_babel import gettext as __
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.extensions import db
+from superset.integrations.teams.config import (
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.integrations.teams.validation import (
+ TeamsRecipientValidationError,
+ validate_teams_recipient,
+)
+from superset.reports.models import ReportRecipientType
+from superset.reports.notifications.base import BaseNotification, NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+
+
+def build_teams_card(content: NotificationContent) -> dict[str, Any]:
+ """Build a card using structured data, omitting raw execution diagnostics."""
+ body: list[dict[str, Any]] = [
+ {
+ "type": "TextBlock",
+ "text": content.name,
+ "weight": "Bolder",
+ "size": "Medium",
+ "wrap": True,
+ },
+ ]
+ if content.description:
+ body.append({"type": "TextBlock", "text": content.description, "wrap": True})
+ if content.text:
+ body.append(
+ {
+ "type": "TextBlock",
+ "text": __(
+ "Alert execution failed. Contact the alert owner for details."
+ ),
+ "wrap": True,
+ }
+ )
+ card: dict[str, Any] = {
+ "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
+ "type": "AdaptiveCard",
+ "version": "1.2",
+ "body": body,
+ }
+ if content.include_cta and content.url:
+ try:
+ url = urlsplit(content.url)
+ safe_link = url.scheme in {"http", "https"} and bool(url.hostname)
+ except ValueError:
+ safe_link = False
+ if safe_link:
+ card["actions"] = [
+ {
+ "type": "Action.OpenUrl",
+ "title": __("Open in Superset"),
+ "url": content.url,
+ }
+ ]
+ return card
+
+
+def _send_to_teams(
+ config: TeamsConfig,
+ destination: TeamsDestination,
+ service_url: str,
+ card: dict[str, Any],
+ *,
+ retry_deadline: float | None = None,
+) -> None:
+ """Load the optional SDK only for delivery and map sanitized transport errors."""
+ try:
+ from superset.integrations.teams.adapter import (
+ deliver_teams_alert,
+ TeamsDeliveryError,
+ )
+ except ImportError:
+ raise NotificationParamException("Teams SDK is not installed") from None
+ try:
+ deliver_teams_alert(
+ config, destination, service_url, card, retry_deadline=retry_deadline
+ )
+ except TeamsDeliveryError as ex:
+ exception = {
+ "authorization": NotificationAuthorizationException,
+ "transient": NotificationTransientError,
+ "parameter": NotificationParamException,
+ "unknown": NotificationError,
+ }[ex.category]
+ raise exception(str(ex)) from None
+
+
+class TeamsNotification(BaseNotification):
+ """Resolve the configured destination and its active installation before send."""
+
+ type = ReportRecipientType.TEAMS
+
+ def send(self) -> None:
Review Comment:
Added `statsd_gauge("reports.teams.send")`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4360918345
##########
superset/integrations/teams/store.py:
##########
@@ -0,0 +1,159 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Transactional persistence for authenticated Teams installation events."""
+
+from datetime import datetime, timezone
+from urllib.parse import urlsplit
+from uuid import UUID
+
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams.config import validate_team_id
+from superset.integrations.teams.models import TeamsInstallation
+
+
+def _identity(
+ tenant_id: str, application_id: str, team_id: str
+) -> tuple[UUID, UUID, str]:
+ """Validate and normalize the installation identity without echoing input."""
+ try:
+ tenant = UUID(tenant_id)
+ application = UUID(application_id)
+ except (ValueError, TypeError, AttributeError):
+ raise ValueError("Teams tenant and application IDs must be UUIDs") from None
+ if not tenant.int or not application.int:
+ raise ValueError("Teams tenant and application IDs must be nonzero UUIDs")
+ return tenant, application, validate_team_id(team_id)
+
+
+def _service_url(value: str) -> str:
+ """Check URL shape; the caller must verify authenticity and Microsoft ownership."""
+ try:
+ url = urlsplit(value)
+ valid = (
+ isinstance(value, str)
+ and len(value) <= 2048
+ and not any(
+ character.isspace() or ord(character) < 32 for character in value
+ )
+ and url.scheme == "https"
+ and bool(url.hostname)
+ and url.port in (None, 443)
+ and url.username is None
+ and url.password is None
+ and not url.query
+ and not url.fragment
+ )
+ except (ValueError, TypeError, AttributeError):
+ valid = False
+ if not valid:
+ raise ValueError("Teams verified service URL must be an HTTPS URL")
+ return value
+
+
+class TeamsInstallationStore:
+ """Persist verified events without committing or modifying configured destinations.
+
+ Callers must authenticate events, enforce the deployment tenant/application,
+ and verify service URLs before invoking this store. This layer stores no
+ credentials or channels and never makes a team selectable on its own.
+ Events are applied in processing order; duplicate installs/removals are safe.
+ """
+
+ def __init__(self, session: Session) -> None:
+ """Use the caller's metadata database transaction."""
+ self.session = session
+
+ def get_active(
+ self, tenant_id: str, application_id: str, team_id: str
+ ) -> TeamsInstallation | None:
+ """Return the active installation for exactly the supplied identity."""
+ tenant, application, team = _identity(tenant_id, application_id, team_id)
+ return (
+ self.session.query(TeamsInstallation)
+ .populate_existing()
+ .filter_by(
+ tenant_id=tenant, application_id=application, team_id=team, active=True
+ )
+ .one_or_none()
+ )
+
+ def install(
+ self,
+ tenant_id: str,
+ application_id: str,
+ team_id: str,
+ verified_service_url: str,
+ ) -> TeamsInstallation:
+ """Create, refresh, or reactivate an installation, including insert races."""
+ tenant, application, team = _identity(tenant_id, application_id, team_id)
+ service_url = _service_url(verified_service_url)
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ table = TeamsInstallation.__table__
+ update = (
+ table.update()
+ .where(table.c.tenant_id == tenant)
+ .where(table.c.application_id == application)
+ .where(table.c.team_id == team)
+ .values(service_url=service_url, active=True, changed_on=now)
Review Comment:
**Suggestion:** If an earlier add callback is delayed or retried until after a later removal commits, this update reactivates the bot and enables delivery despite it being uninstalled.
**Assessment:** 🟠 `Major` · 🔁 `Occurrence: Rarely` · 🏷️ `Race condition`
[](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c4cc72e0669b4546a6b870295e56aba5&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=c4cc72e0669b4546a6b870295e56aba5&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/integrations/teams/store.py
**Line:** 113:113
**Comment:**
*Race Condition: If an earlier add callback is delayed or retried until after a later removal commits, this update reactivates the bot and enables delivery despite it being uninstalled.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F45508&comment_hash=2567471e8eb4fd85bf8e7b37317be6097806b8a8fe5a98671183c70ba87e7eca&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F45508&comment_hash=2567471e8eb4fd85bf8e7b37317be6097806b8a8fe5a98671183c70ba87e7eca&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4374074467
##########
tests/unit_tests/integrations/teams/delivery_test.py:
##########
@@ -0,0 +1,965 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Teams notification formatting, resolution, retry, and SDK delivery tests."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import importlib.util
+import threading
+import time
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager
+from datetime import datetime, timedelta, timezone
+from email.utils import format_datetime
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+import requests
+from billiard.exceptions import SoftTimeLimitExceeded
+from flask import current_app, Flask
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import validation as teams_validation
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.models import TeamsInstallation
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.reports.models import ReportRecipients, ReportRecipientType
+from superset.reports.notifications import create_notification, teams as notifications
+from superset.reports.notifications.base import NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+from superset.utils import json
+
+if importlib.util.find_spec("microsoft_teams") is None:
+ pytest.skip("Optional Teams SDK is not installed", allow_module_level=True)
+
+adapter = importlib.import_module("superset.integrations.teams.adapter")
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+SERVICE_URL = "https://smba.trafficmanager.net/amer/"
+
+
+@pytest.fixture
+def configured(teams_config: dict[str, Any]) -> TeamsConfig:
+ """Parse the same deployment configuration used by real notifications."""
+ config = parse_teams_config(teams_config)
+ assert config is not None
+ return config
+
+
+@pytest.fixture
+def content() -> NotificationContent:
+ """Include difficult text to verify normal structured JSON serialization."""
+ return NotificationContent(
+ name='Alert "Revenue"\nCafé 東京 🚨',
+ description='Description "quoted"\n第二行',
+ header_data={
+ "notification_type": "Alert",
+ "notification_format": "NONE",
+ "editors": [],
+ "notification_source": None,
+ "chart_id": None,
+ "dashboard_id": None,
+ "slack_channels": None,
+ "execution_id": None,
+ },
+ url="https://superset.example/chart/42/",
+ )
+
+
+@pytest.fixture
+def notification_context(
+ teams_config: dict[str, Any],
+ teams_engine: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[SimpleNamespace]:
+ """Use the real installation table and resolve through the notification class."""
+ app = Flask(__name__)
+ app.config.update(
+ ALERT_REPORTS_TEAMS=teams_config, FEATURE_FLAGS={"ALERT_REPORT_TEAMS": True}
+ )
+ engine = teams_engine
+ with Session(engine) as session:
+ TeamsInstallationStore(session).install(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ session.commit()
+ monkeypatch.setattr(notifications, "db", SimpleNamespace(engine=engine))
+ monkeypatch.setattr(
+ teams_validation.feature_flag_manager,
+ "is_feature_enabled",
+ lambda name: current_app.config["FEATURE_FLAGS"].get(name, False),
+ )
+ send = MagicMock()
+ monkeypatch.setattr(notifications, "_send_to_teams", send)
+ with app.app_context():
+ yield SimpleNamespace(app=app, engine=engine, send=send)
+
+
+def recipient(target: str = "ops") -> ReportRecipients:
+ """Recipients store only a configured destination key."""
+ return ReportRecipients(
+ type=ReportRecipientType.TEAMS,
+ recipient_config_json=json.dumps({"target": target}),
+ )
+
+
+def test_factory_resolves_active_installation_and_formats_card(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+) -> None:
+ notification = create_notification(recipient(), content)
+ assert isinstance(notification, notifications.TeamsNotification)
+ notification.send()
+ config, destination, service_url, card = notification_context.send.call_args.args
+ assert config.credential == "deployment-secret"
+ assert destination.key == "ops"
+ assert destination.channel_id == "channel-1"
+ assert service_url == SERVICE_URL
+ assert card["body"][0]["text"] == content.name
+ assert card["body"][1]["text"] == content.description
+ assert card["actions"][0]["url"] == content.url
+ assert "deployment-secret" not in json.dumps(card)
+
+
+@pytest.mark.parametrize(
+ "mode", ["inactive", "missing", "other-tenant", "other-application"]
+)
+def test_installation_must_be_active_for_exact_identity(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+ mode: str,
+) -> None:
+ with Session(notification_context.engine) as session:
+ store = TeamsInstallationStore(session)
+ if mode == "inactive":
+ store.remove(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ else:
+ session.query(TeamsInstallation).delete()
+ other = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+ if mode != "missing":
+ store.install(
+ other if mode == "other-tenant" else TENANT,
+ other if mode == "other-application" else APPLICATION,
+ "team-1",
+ SERVICE_URL,
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ with pytest.raises(NotificationAuthorizationException):
+ notifications.TeamsNotification(recipient(), content).send()
+ notification_context.send.assert_not_called()
+
+
+class FakeTransport:
+ """Deterministic replaceable transport for bounded retry policy tests."""
+
+ def __init__(self, errors: list[Exception | None]) -> None:
+ """Consume one outcome for each root post attempt."""
+ self.errors = iter(errors)
+ self.posts: list[tuple[TeamsDestination, dict[str, Any]]] = []
+ self.refreshes = 0
+ self.closed = False
+ self.loop: asyncio.AbstractEventLoop | None = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Record every fresh root-post attempt."""
+ self.posts.append((destination, card))
+ error = next(self.errors)
+ if error:
+ raise error
+
+ async def refresh_auth(self) -> None:
+ """Record a cache invalidation without contacting Entra."""
+ self.refreshes += 1
+
+ @asynccontextmanager
+ async def factory(
+ self, config: TeamsConfig, service_url: str, deadline: float
+ ) -> AsyncIterator[FakeTransport]:
+ """Track operation cleanup on both successful and failed delivery."""
+ self.loop = asyncio.get_running_loop()
+ try:
+ yield self
+ finally:
+ self.closed = True
+
+
+@pytest.fixture
+def retry_clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
+ """Advance retry time without actually sleeping."""
+ elapsed = [0.0]
+ sleeps: list[float] = []
+ monkeypatch.setattr(adapter, "monotonic", lambda: elapsed[0])
+
+ async def sleep(delay: float) -> None:
+ """Advance the same clock used by the retry budget."""
+ elapsed[0] += delay
+ sleeps.append(delay)
+
+ monkeypatch.setattr(adapter.asyncio, "sleep", sleep)
+ return sleeps
+
+
+@pytest.mark.parametrize(
+ "status,retryable",
+ [
+ (None, False),
+ (None, True),
+ (408, False),
+ (429, False),
+ (500, False),
+ (502, False),
+ (503, False),
+ (504, False),
+ ],
+)
+def test_transport_failures_respect_retry_safety_and_attempt_bound(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ status: int | None,
+ retryable: bool,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status, retryable=retryable)] * 4
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ ambiguous = status is None and not retryable
+ assert exc.value.category == ("unknown" if ambiguous else "transient")
+ assert len(transport.posts) == (1 if ambiguous else 4)
+ assert retry_clock == ([] if ambiguous else [1.0, 2.0, 4.0])
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "headers,expected",
+ [
+ ({"Retry-After": "3"}, 3.0),
+ ({"x-ms-retry-after-ms": "1500"}, 1.5),
+ ({"Retry-After": "2", "x-ms-retry-after-ms": "3000"}, 3.0),
+ ({"Retry-After": "invalid"}, 1.0),
+ ],
+)
+def test_microsoft_retry_delays_are_respected(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ headers: dict[str, str],
+ expected: float,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers(headers)), None]
+ )
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert retry_clock == [expected]
+ assert len(transport.posts) == 2
+ assert transport.closed
+
+
+def test_retry_after_http_date() -> None:
+ retry_at = datetime.now(timezone.utc) + timedelta(seconds=5)
+ error = adapter.TeamsTransportError(
+ 429, httpx.Headers({"Retry-After": format_datetime(retry_at, usegmt=True)})
+ )
+ assert 3.0 <= adapter._retry_delay(error, 0) <= 5.0
+
+
+def test_excessive_server_delay_is_not_shortened(
+ configured: TeamsConfig, retry_clock: list[float]
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers({"Retry-After": "120"}))]
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == "transient"
+ assert len(transport.posts) == 1
+ assert retry_clock == []
+ assert transport.closed
+
+
+@pytest.mark.parametrize(
+ "outcomes,category,posts,refreshes",
+ [
+ ([401, None], None, 2, 1),
+ ([401, 401], "authorization", 2, 1),
+ ([403], "authorization", 1, 0),
+ ([400], "parameter", 1, 0),
+ ([404], "parameter", 1, 0),
+ ([302], "parameter", 1, 0),
+ ([401, 503, 503, None], None, 4, 1),
Review Comment:
If the fourth send is the first to return `401`, the `attempt == _DELIVERY_ATTEMPTS - 1` guard in `_deliver_with_retries` is what makes delivery fail as `authorization` with no token refresh. Every case here hits the `401` on attempt one or two, so removing that guard would still pass: the fourth-attempt `401` would refresh the token and then fall out of the loop as `transient`. Could you add a `[503, 503, 503, 401]` case that asserts four posts, zero refreshes, and category `authorization`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4379917672
##########
docs/admin_docs/configuration/alerts-reports.mdx:
##########
@@ -892,6 +892,206 @@ This information can then be retrieved from the endpoint `/api/v1/saved_query/`
schedule the queries that have `schedule_info` in their JSON metadata. For schedulers other than
Airflow, additional fields can be easily added to the configuration file above.
+## Microsoft Teams configuration
+
+Teams is an optional, disabled-by-default notification destination for
+attachment-free alerts in standard channels. Each deployment supports one
+Microsoft tenant and bot identity. Scheduled reports, private/shared channels,
+direct messages, and file attachments are not supported.
+
+### Install and configure
+
+Install the extra in both the web-server and Celery worker images using the same
+Superset release as the deployment:
+
+```bash
+pip install 'apache-superset[teams]==<your-superset-version>'
+superset db upgrade
+```
+
+Configure both processes with the same server-side settings. Load the secret
+value from a deployment secret store, rather than checking it into source control:
+
+```python
+import os
+
+FEATURE_FLAGS = {
+ "ALERT_REPORTS": True,
+ "ALERT_REPORT_TEAMS": True,
+}
+ALERT_REPORTS_TEAMS = {
+ "tenant_id": os.environ["TEAMS_TENANT_ID"],
+ "application_id": os.environ["TEAMS_APPLICATION_ID"],
+ "credential": os.environ["TEAMS_CLIENT_SECRET"],
+ "destinations": [
+ {
+ "key": "ops",
+ "label": "Operations alerts",
+ "team_id": os.environ["TEAMS_OPS_TEAM_ID"],
+ "channel_id": os.environ["TEAMS_OPS_CHANNEL_ID"],
+ },
+ ],
+}
+```
+
+Destination keys must be unique, stable identifiers of 1–128 letters, digits,
+underscores or hyphens, starting with a letter or digit. Keep keys stable when
+changing routing. Each destination requires a label, team ID, and channel ID.
Review Comment:
The installation callback matches the event's team ID exactly against `team_id`, and Teams sends that in the thread form (`19:...@thread.tacv2`), not the group GUID that Graph and the Teams admin center call the Team ID. An operator who configures the GUID here gets a 403 on every install event, no installation is recorded, and every alert run fails with no active installation and nothing in the logs pointing at the ID format. Could the docs state the expected format with an example and where to find it?
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask registers its route once at startup. Each request creates a fresh SDK
+ authentication server; its handler runs to completion in an operation-scoped
+ event loop. No SDK App, outbound clients, tasks, or separate server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
+ or not isinstance(action, str)
+ or action not in actions
+ ):
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ The SDK's HttpServer uses PyJWKClient, whose network responses close within
+ its scoped fetch. It creates no persistent HTTP clients. Keep construction,
+ authentication, and adapter cleanup within the same event loop; asyncio.run
+ closes that loop on success and failure. SDK response bodies are never exposed.
+ """
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = _FlaskServerAdapter()
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server = HttpServer(adapter, messaging_endpoint=EVENTS_PATH)
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ if adapter.handler is None:
+ return TeamsEventResult(500)
+ response: HttpResponse = await adapter.handler(
+ HttpRequest(body=body, headers=headers)
+ )
+ if response["status"] != 200:
+ return TeamsEventResult(response["status"])
+ return result
+ finally:
+ await adapter.stop()
+
+ return asyncio.run(process())
+
+
+# Count every send, including the single 401 replay, against the same retry bound.
+_DELIVERY_ATTEMPTS = 4
+_DELIVERY_TIMEOUT = 60.0
+_DELIVERY_REQUEST_TIMEOUT = 10.0
+
+
+class TeamsDeliveryError(Exception):
+ """Sanitized delivery outcome for mapping to existing notification exceptions."""
+
+ def __init__(
+ self, category: Literal["authorization", "transient", "parameter", "unknown"]
+ ) -> None:
+ """Expose a stable message without response bodies, SQL, tokens, or URLs."""
+ self.category = category
+ messages = {
+ "authorization": "Teams bot authorization failed",
+ "transient": "Teams alert delivery temporarily unavailable",
+ "parameter": "Teams alert delivery was rejected",
+ "unknown": (
+ "Teams alert delivery could not be confirmed. "
+ "It may have been delivered"
+ ),
+ }
+ super().__init__(messages[category])
+
+
+class TeamsTransportError(Exception):
+ """Sanitized HTTP failure with explicit retry safety for status-less errors."""
+
+ def __init__(
+ self,
+ status: int | None = None,
+ headers: httpx.Headers
+ | requests.structures.CaseInsensitiveDict[str]
+ | None = None,
+ *,
+ retryable: bool = False,
+ ) -> None:
+ """Retain only retry headers; never retain a response body or request token."""
+ super().__init__("Teams transport request failed")
+ self.status = status
+ self.retryable = retryable
+ self.retry_after = headers.get("Retry-After") if headers is not None else None
+ self.retry_after_ms = (
+ headers.get("x-ms-retry-after-ms") if headers is not None else None
+ )
+
+
+class TeamsTransport(Protocol):
+ """Replaceable operation-scoped transport; retries live outside SDK calls."""
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new channel root post containing the card."""
+ ...
+
+ async def refresh_auth(self) -> None:
+ """Invalidate cached authentication before a single 401 replay."""
+ ...
+
+
+def _remaining(deadline: float) -> float:
+ """Bound each request by its timeout and remaining delivery budget."""
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise TeamsTransportError(retryable=True)
+ return min(_DELIVERY_REQUEST_TIMEOUT, remaining)
+
+
+class _AuthHttpClient:
+ """MSAL HTTP interface backed by a caller-owned, timeout-bounded session."""
+
+ def __init__(self, session: requests.Session, deadline: float) -> None:
+ """Keep OAuth traffic within the same operation as the channel post."""
+ self.session = session
+ self.deadline = deadline
+
+ def get(self, url: str, **kwargs: Any) -> requests.Response:
+ """Fetch MSAL metadata without leaving a response open."""
+ return self._request("GET", url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> requests.Response:
+ """Acquire tokens without leaving a response open."""
+ return self._request("POST", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
+ """Use normal serialization, explicit timeouts, and sanitized retry errors."""
+ kwargs["timeout"] = _remaining(self.deadline)
+ response = self.session.request(method, url, **kwargs)
+ try:
+ _remaining(self.deadline)
+ # requests eagerly reads responses; MSAL can still read cached JSON
+ # after close. Closing here also covers retryable OAuth errors.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise TeamsTransportError(response.status_code, response.headers)
+ return response
+ finally:
+ response.close()
+
+
+class _ChannelConversationParams(CreateConversationParams):
+ """Include the connector's group flag, absent from the SDK base parameter model."""
+
+ is_group: Literal[True] = True
+
+
+class _SDKTeamsTransport:
+ """Use the SDK create-conversation API with shared, explicitly owned resources."""
+
+ def __init__(
+ self,
+ config: TeamsConfig,
+ service_url: str,
+ http: Client,
+ auth_http: _AuthHttpClient,
+ deadline: float,
+ ) -> None:
+ """Prepare the SDK without constructing a full App or starting a server."""
+ self.config = config
+ self.http = http
+ self.auth_http = auth_http
+ self.deadline = deadline
+ self.auth: ConfidentialClientApplication | None = None
+ self.api = ApiClient(service_url, http)
+
+ def _authenticate(self) -> None:
+ """Acquire a bot token without exposing identity-provider errors."""
+ if self.http.token:
+ return
+ if self.auth is None:
+ self.auth = ConfidentialClientApplication(
+ self.config.application_id,
+ client_credential=self.config.credential,
+ authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
+ http_client=self.auth_http,
+ instance_discovery=False,
+ )
+ result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
+ token = result.get("access_token")
+ if not isinstance(token, str) or not token:
+ status = (
+ 503
+ if result.get("error") in {"temporarily_unavailable", "server_error"}
+ else 401
+ )
+ raise TeamsTransportError(status)
+ self.http.token = token
+
+ async def refresh_auth(self) -> None:
+ """Invalidate MSAL app tokens so the next request acquires a fresh token."""
+ if self.auth is not None:
+ self.auth.remove_tokens_for_client()
+ self.http.token = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new conversation with an initial card, never reply to a thread."""
+ try:
+ self._authenticate()
+ self.http.http.timeout = httpx.Timeout(_remaining(self.deadline))
+ await self.api.conversations.create(
+ _ChannelConversationParams(
+ tenant_id=self.config.tenant_id,
+ channel_data={
+ "tenant": {"id": self.config.tenant_id},
+ "team": {"id": destination.team_id},
+ "channel": {"id": destination.channel_id},
+ },
+ activity=MessageActivityInput(
+ attachments=[
+ Attachment(
+ content_type="application/vnd.microsoft.card.adaptive",
+ content=card,
+ )
+ ]
+ ),
+ )
+ )
+ except httpx.HTTPStatusError as ex:
+ error = TeamsTransportError(ex.response.status_code, ex.response.headers)
+ await ex.response.aclose()
+ raise error from None
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout):
+ raise TeamsTransportError(retryable=True) from None
+ except httpx.RequestError:
+ # The connector may have accepted the POST before the connection failed.
+ raise TeamsTransportError() from None
+ except requests.RequestException:
+ # requests is used only for authentication, before the connector POST.
+ raise TeamsTransportError(retryable=True) from None
+ except ValueError:
+ # Includes invalid SDK models/response JSON. Replaying a successful
+ # POST whose response could not be decoded could duplicate delivery.
+ raise TeamsDeliveryError("parameter") from None
+
+
+@asynccontextmanager
+async def _create_transport(
+ config: TeamsConfig, service_url: str, deadline: float
+) -> AsyncIterator[TeamsTransport]:
+ """Close the SDK's shared async client and MSAL's session in the same operation."""
+ http = Client(ClientOptions(timeout=_DELIVERY_REQUEST_TIMEOUT))
+ try:
+ with requests.Session() as session:
+ yield _SDKTeamsTransport(
+ config, service_url, http, _AuthHttpClient(session, deadline), deadline
+ )
+ finally:
+ await http.http.aclose()
+
+
+def _retry_delay(error: TeamsTransportError, attempt: int) -> float:
+ """Honor Microsoft's retry headers, falling back to bounded exponential delays."""
+ delays: list[float] = []
+ for value, divisor in [(error.retry_after_ms, 1000), (error.retry_after, 1)]:
+ if value is None:
+ continue
+ try:
+ delay = float(value) / divisor
+ except ValueError:
+ if divisor != 1:
+ continue
+ try:
+ retry_at = parsedate_to_datetime(value)
+ if retry_at.tzinfo is None:
+ retry_at = retry_at.replace(tzinfo=timezone.utc)
+ delay = (retry_at - datetime.now(timezone.utc)).total_seconds()
+ except (ValueError, TypeError, OverflowError):
+ continue
+ if math.isfinite(delay):
+ delays.append(max(0.0, delay))
+ return max(delays) if delays else min(2.0**attempt, 8.0)
+
+
+async def _deliver_with_retries(
+ transport: TeamsTransport,
+ destination: TeamsDestination,
+ card: dict[str, Any],
+ deadline: float,
+) -> None:
+ """Bound transient retries and allow exactly one authentication refresh."""
+ refreshed = False
+ for attempt in range(_DELIVERY_ATTEMPTS):
+ if monotonic() >= deadline:
+ raise TeamsDeliveryError("transient")
+ try:
+ await transport.post_root(destination, card)
+ if monotonic() >= deadline:
Review Comment:
Once `post_root` has returned, the message is already in the channel, but this check (and the one after `asyncio.run` in `deliver_teams_alert`) raises `transient` if the clock crossed the deadline during the post or transport teardown. That maps to `NotificationTransientError`, so the execution is recorded as ERROR even though Teams has the message, and the alert grace period keys off the last SUCCESS log, so the next cron tick can post the same alert again. Should these post-send checks raise `unknown` (or return normally) instead, since the outcome is already known?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4380656061
##########
docs/admin_docs/configuration/alerts-reports.mdx:
##########
@@ -892,6 +892,206 @@ This information can then be retrieved from the endpoint `/api/v1/saved_query/`
schedule the queries that have `schedule_info` in their JSON metadata. For schedulers other than
Airflow, additional fields can be easily added to the configuration file above.
+## Microsoft Teams configuration
+
+Teams is an optional, disabled-by-default notification destination for
+attachment-free alerts in standard channels. Each deployment supports one
+Microsoft tenant and bot identity. Scheduled reports, private/shared channels,
+direct messages, and file attachments are not supported.
+
+### Install and configure
+
+Install the extra in both the web-server and Celery worker images using the same
+Superset release as the deployment:
+
+```bash
+pip install 'apache-superset[teams]==<your-superset-version>'
+superset db upgrade
+```
+
+Configure both processes with the same server-side settings. Load the secret
+value from a deployment secret store, rather than checking it into source control:
+
+```python
+import os
+
+FEATURE_FLAGS = {
+ "ALERT_REPORTS": True,
+ "ALERT_REPORT_TEAMS": True,
+}
+ALERT_REPORTS_TEAMS = {
+ "tenant_id": os.environ["TEAMS_TENANT_ID"],
+ "application_id": os.environ["TEAMS_APPLICATION_ID"],
+ "credential": os.environ["TEAMS_CLIENT_SECRET"],
+ "destinations": [
+ {
+ "key": "ops",
+ "label": "Operations alerts",
+ "team_id": os.environ["TEAMS_OPS_TEAM_ID"],
+ "channel_id": os.environ["TEAMS_OPS_CHANNEL_ID"],
+ },
+ ],
+}
+```
+
+Destination keys must be unique, stable identifiers of 1–128 letters, digits,
+underscores or hyphens, starting with a letter or digit. Keep keys stable when
+changing routing. Each destination requires a label, team ID, and channel ID.
Review Comment:
Clarified the required `team_id` format with an example and steps to extract it from the team link
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-6455927639
### ⚠️ Possible DB migration conflict
@KristiDodaj the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4558235839
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,572 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from functools import lru_cache
+from threading import Lock
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask owns the listening server. SDK authentication is reused, while each
+ callback runs to completion in an operation-scoped event loop. No SDK App,
+ outbound clients, tasks, or separate listening server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
Review Comment:
Good catch! I think that makes sense, authed non install events return 200 without now
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub) via notifications" <no...@superset.apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4429462411
##########
tests/unit_tests/integrations/teams/destinations_test.py:
##########
@@ -0,0 +1,275 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Browser discovery only projects approved keys and active-installation status."""
+
+import subprocess
+import sys
+from collections.abc import Iterator
+from datetime import datetime, timezone
+from textwrap import dedent
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from flask import current_app, Flask
+from sqlalchemy import event
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import destinations
+from superset.integrations.teams.store import TeamsInstallationStore
+
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+OTHER = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+
+
+@pytest.fixture
+def configured_app(
+ teams_config: dict[str, Any], teams_engine: Engine, monkeypatch: pytest.MonkeyPatch
+) -> Iterator[Flask]:
+ app = Flask(__name__)
+ teams_config["destinations"].extend(
+ [
+ {
+ "key": "finance",
+ "label": "Finance",
+ "team_id": "team-1",
+ "channel_id": "channel-2",
+ },
+ {
+ "key": "support",
+ "label": "Support",
+ "team_id": "team-2",
+ "channel_id": "channel-3",
+ },
+ ]
+ )
+ app.config["ALERT_REPORTS_TEAMS"] = teams_config
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda name: True
+ )
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", lambda: True)
+ engine = teams_engine
+ monkeypatch.setattr(destinations, "db", MagicMock(engine=engine))
+ with app.app_context():
+ yield app
+
+
+def test_only_approved_public_fields_and_missing_installations(
+ configured_app: Flask,
+) -> None:
+ assert destinations.list_teams_destinations() == [
+ {"key": "ops", "label": "Operations", "available": False},
+ {"key": "finance", "label": "Finance", "available": False},
+ {"key": "support", "label": "Support", "available": False},
+ ]
+
+
+def test_removal_and_reinstallation_update_availability(configured_app: Flask) -> None:
+ with Session(destinations.db.engine) as session:
+ store = TeamsInstallationStore(session)
+ store.install(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ store.install(
+ TENANT,
+ APPLICATION,
+ "unapproved-team",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert [
+ item["available"] for item in destinations.list_teams_destinations()
+ ] == [True, True, False]
+ store.remove(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert not any(
+ item["available"] for item in destinations.list_teams_destinations()
+ )
+ store.install(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/emea/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert [
+ item["available"] for item in destinations.list_teams_destinations()
+ ] == [True, True, False]
+ assert len(destinations.list_teams_destinations()) == 3
+
+
+@pytest.mark.parametrize("tenant,application", [(OTHER, APPLICATION), (TENANT, OTHER)])
+def test_other_identity_cannot_make_destination_available(
+ configured_app: Flask, tenant: str, application: str
+) -> None:
+ with Session(destinations.db.engine) as session:
+ TeamsInstallationStore(session).install(
+ tenant,
+ application,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert not any(item["available"] for item in destinations.list_teams_destinations())
+
+
+@pytest.mark.parametrize("configuration", [{}, {"credential": "invalid-secret"}])
+def test_unconfigured_or_invalid_integration_is_hidden(
+ configured_app: Flask, configuration: dict[str, Any]
+) -> None:
+ current_app.config["ALERT_REPORTS_TEAMS"] = configuration
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+
+
+def test_disabled_integration_does_not_query_installations(
+ configured_app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda name: False
+ )
+ monkeypatch.setattr(
+ destinations, "Session", MagicMock(side_effect=AssertionError("must not query"))
+ )
+ assert destinations.list_teams_destinations() == []
+
+
+@pytest.mark.parametrize("team_id", ["t" * 256, " team-1", "team-1 ", "\tteam-1\n"])
+def test_invalid_team_config_is_hidden_before_installation_lookup(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ team_id: str,
+) -> None:
+ """Discovery handles invalid deployment IDs instead of raising store ValueError."""
+ configured_app.config["ALERT_REPORTS_TEAMS"]["destinations"][0]["team_id"] = team_id
+ lookup = MagicMock(side_effect=AssertionError("must not query installations"))
+ monkeypatch.setattr(destinations, "Session", lookup)
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ lookup.assert_not_called()
+
+
+@pytest.mark.parametrize("installed", [False, True])
+def test_optional_sdk_controls_both_discovery_and_notification_methods(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ installed: bool,
+) -> None:
+ """Bootstrap and destination discovery agree when the optional SDK is missing."""
+ from superset.reports.models import ReportRecipientType
+ from superset.views import base
+
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", lambda: installed)
+ monkeypatch.setattr(base, "app", configured_app)
+ configured_app.config["SLACK_API_TOKEN"] = None
+ if installed:
+ assert destinations.configured_teams() is not None
+ assert len(destinations.list_teams_destinations()) == 3
+ assert ReportRecipientType.TEAMS in base._notification_methods()
+ else:
+ session = MagicMock(side_effect=AssertionError("must not query installations"))
+ monkeypatch.setattr(destinations, "Session", session)
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ assert ReportRecipientType.TEAMS not in base._notification_methods()
+ session.assert_not_called()
+
+
+def test_disabled_integration_registers_and_bootstraps_without_sdk() -> None:
+ """Block optional imports before loading the startup paths in a fresh process."""
+ result = subprocess.run( # noqa: S603 -- fixed interpreter and inline test script
+ [
+ sys.executable,
+ "-c",
+ dedent("""
+ import importlib.abc
+ import sys
+
+ class NoTeamsSDK(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ if (fullname == "microsoft_teams"
+ or fullname.startswith("microsoft_teams.")
+ or fullname == "superset.integrations.teams.adapter"):
+ raise AssertionError("Unexpected optional import: " + fullname)
+
+ sys.meta_path.insert(0, NoTeamsSDK())
+ from superset.app import create_app
+ app = create_app()
+ from superset.integrations.teams import destinations
+ from superset.reports.models import ReportRecipientType
+ from superset.views import base
+
+ def unexpected_lookup():
+ raise AssertionError("must not check SDK")
+
+ app.config["SLACK_API_TOKEN"] = None
+ destinations.feature_flag_manager.is_feature_enabled = lambda _: False
+ destinations.is_teams_sdk_installed = unexpected_lookup
+ base.app = app
+ with app.app_context():
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ assert ReportRecipientType.TEAMS not in base._notification_methods()
+ assert app.test_client().post(
+ "/api/v1/teams/events/", json={}
+ ).status_code == 404
Review Comment:
Good catch. Added an assertion that the callback is registered with the expected URL, endpoint, and POST method before checking the disabled 404 response
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-7038863404
### ⚠️ Possible DB migration conflict
@KristiDodaj the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4373808983
##########
tests/unit_tests/integrations/teams/teams_api_test.py:
##########
@@ -0,0 +1,832 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Exercise the real Teams SDK authentication boundary and Flask persistence."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import importlib.util
+from collections.abc import Callable
+from copy import deepcopy
+from datetime import datetime, timedelta, timezone
+from io import BytesIO
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import patch
+
+import jwt
+import pytest
+from cryptography.hazmat.primitives.asymmetric import rsa
+from flask import current_app, Flask, Response
+from flask.testing import FlaskClient
+from sqlalchemy.engine import Engine
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import api as teams_api
+from superset.integrations.teams.config import parse_teams_config
+from superset.integrations.teams.models import TeamsInstallation
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.utils import json
+
+if importlib.util.find_spec("microsoft_teams") is None:
+ pytest.skip("Optional Teams SDK is not installed", allow_module_level=True)
+
+teams_adapter = importlib.import_module("superset.integrations.teams.adapter")
+PATH = "/api/v1/teams/events/"
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+OTHER = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+SERVICE_URL = "https://smba.trafficmanager.net/amer/"
+
+
+@pytest.fixture(scope="module")
+def signing_key() -> rsa.RSAPrivateKey:
+ """Sign real SDK-validated tokens without contacting Microsoft's JWKS service."""
+ return rsa.generate_private_key(public_exponent=65537, key_size=2048)
+
+
+@pytest.fixture(autouse=True)
+def trusted_signing_key(
+ monkeypatch: pytest.MonkeyPatch, signing_key: rsa.RSAPrivateKey
+) -> None:
+ """Replace only key discovery; the SDK verifies signature and claims itself."""
+ monkeypatch.setattr(
+ jwt.PyJWKClient,
+ "get_signing_key_from_jwt",
+ lambda self, token: SimpleNamespace(key=signing_key.public_key()),
+ )
+
+
+@pytest.fixture
+def auth_headers(signing_key: rsa.RSAPrivateKey) -> Callable[..., dict[str, str]]:
+ """Build connector JWTs with optional invalid claims or signing key."""
+
+ def sign(
+ claims: dict[str, Any] | None = None,
+ key: rsa.RSAPrivateKey | None = None,
+ ) -> dict[str, str]:
+ """Sign a token so failures exercise the SDK's real validator."""
+ now = datetime.now(timezone.utc)
+ payload = {
+ "aud": APPLICATION,
+ "iss": "https://api.botframework.com",
+ "iat": int(now.timestamp()),
+ "nbf": int(now.timestamp()),
+ "exp": int((now + timedelta(hours=1)).timestamp()),
+ "serviceurl": SERVICE_URL,
+ }
+ payload.update(claims or {})
+ return {
+ "Authorization": "Bearer "
+ + jwt.encode(payload, key or signing_key, algorithm="RS256")
+ }
+
+ return sign
+
+
+@pytest.fixture
+def installation() -> dict[str, Any]:
+ """An installationUpdate event from a standard team channel."""
+ return {
+ "type": "installationUpdate",
+ "action": "add",
+ "id": "event-1",
+ "timestamp": "2026-10-01T12:00:00Z",
+ "serviceUrl": SERVICE_URL,
+ "channelId": "msteams",
+ "from": {"id": "29:installer"},
+ "recipient": {"id": f"28:{APPLICATION}"},
+ "conversation": {
+ "id": "channel-1",
+ "conversationType": "channel",
+ "tenantId": TENANT,
+ },
+ "channelData": {
+ "tenant": {"id": TENANT},
+ "team": {"id": "team-1"},
+ "channel": {"id": "channel-1", "type": "standard"},
+ },
+ }
+
+
+@pytest.fixture
+def teams_client(
+ teams_config: dict[str, Any],
+ teams_engine: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+) -> FlaskClient:
+ """Mount the callback in Flask with real CSRF enforcement and SQLAlchemy."""
+ app = Flask(__name__)
+ app.config.update(
+ TESTING=True,
+ SECRET_KEY="test-callback-key", # noqa: S106
+ WTF_CSRF_ENABLED=True,
+ FEATURE_FLAGS={"ALERT_REPORT_TEAMS": True},
+ ALERT_REPORTS_TEAMS=teams_config,
+ )
+ monkeypatch.setattr(teams_api, "db", SimpleNamespace(engine=teams_engine))
+ monkeypatch.setattr(
+ teams_api.feature_flag_manager,
+ "is_feature_enabled",
+ lambda name: current_app.config["FEATURE_FLAGS"].get(name, False),
+ )
+ teams_api.csrf.init_app(app)
+ teams_api.register_teams_api(app)
+
+ @app.post("/csrf-control")
+ def csrf_control() -> Response:
+ """An unrelated route must remain CSRF protected."""
+ return Response(status=200)
+
+ return app.test_client()
+
+
+def test_callback_persists_only_approved_metadata(
+ teams_client: FlaskClient,
+ teams_engine: Engine,
+ teams_config: dict[str, Any],
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+) -> None:
+ before = deepcopy(teams_config)
+ response = teams_client.post(PATH, json=installation, headers=auth_headers())
+ assert response.status_code == 200
+ assert response.data == b""
+ with Session(teams_engine) as session:
+ persisted = session.query(TeamsInstallation).one()
+ assert persisted.service_url == SERVICE_URL
+ assert persisted.active
+ assert str(persisted.tenant_id) == TENANT
+ assert str(persisted.application_id) == APPLICATION
+ assert persisted.team_id == "team-1"
+ assert teams_config == before
+ assert b"deployment-secret" not in response.data
+
+
+@pytest.mark.parametrize(
+ "authentication",
+ [
+ "missing",
+ "malformed",
+ "bad-signature",
+ "wrong-audience",
+ "expired",
+ "wrong-issuer",
+ "missing-serviceurl",
+ "mismatched-serviceurl",
+ ],
+)
+def test_invalid_authentication_never_opens_database_session(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ authentication: str,
+) -> None:
+ if authentication == "missing":
+ headers = {}
+ elif authentication == "malformed":
+ headers = {"Authorization": "Bearer not-a-jwt"}
+ elif authentication == "bad-signature":
+ headers = auth_headers(
+ key=rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ )
+ else:
+ claims = {
+ "wrong-audience": {"aud": OTHER},
+ "expired": {"exp": 1},
+ "wrong-issuer": {"iss": "https://untrusted.example"},
+ "missing-serviceurl": {"serviceurl": None},
+ "mismatched-serviceurl": {
+ "serviceurl": "https://smba.trafficmanager.net/other/"
+ },
+ }
+ headers = auth_headers(claims[authentication])
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(PATH, json=installation, headers=headers)
+ assert response.status_code == 401
+ assert response.data == b""
+ session.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "mismatch",
+ [
+ "tenant",
+ "conversation-tenant",
+ "token-tenant",
+ "recipient",
+ "team",
+ "personal",
+ "groupChat",
+ "private",
+ "shared",
+ "private-team",
+ "shared-team",
+ ],
+)
+def test_authenticated_events_must_match_deployment_scope(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ mismatch: str,
+) -> None:
+ claims = {}
+ if mismatch == "tenant":
+ installation["channelData"]["tenant"]["id"] = OTHER
+ elif mismatch == "conversation-tenant":
+ installation["conversation"]["tenantId"] = OTHER
+ elif mismatch == "token-tenant":
+ claims = {"tid": OTHER}
+ elif mismatch == "recipient":
+ installation["recipient"]["id"] = f"28:{OTHER}"
+ elif mismatch == "team":
+ installation["channelData"]["team"]["id"] = "unapproved-team"
+ elif mismatch in {"personal", "groupChat"}:
+ installation["conversation"]["conversationType"] = mismatch
+ elif mismatch in {"private", "shared"}:
+ installation["channelData"]["channel"]["type"] = mismatch
+ else:
+ installation["channelData"]["team"]["teamType"] = (
+ "privateChannel" if mismatch == "private-team" else "sharedChannel"
+ )
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(
+ PATH, json=installation, headers=auth_headers(claims)
+ )
+ assert response.status_code == 403
+ session.assert_not_called()
+
+
+def test_entra_tokens_cannot_bypass_signed_service_url_binding(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+) -> None:
+ # The SDK also supports Agent 365 tokens; this notification bot accepts only
+ # connector tokens whose signed serviceurl claim binds the installation URL.
+ headers = auth_headers(
+ {
+ "iss": f"https://login.microsoftonline.com/{TENANT}/v2.0",
+ "tid": TENANT,
+ "azp": "5a807f24-c9de-44ee-a3a7-329e88a00ffc",
+ "serviceurl": None,
+ }
+ )
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(PATH, json=installation, headers=headers)
+ assert response.status_code == 403
+ session.assert_not_called()
+
+
+def test_tokens_without_expiration_are_rejected(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+) -> None:
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(
+ PATH, json=installation, headers=auth_headers({"exp": None})
+ )
+ assert response.status_code in (401, 403)
+ session.assert_not_called()
+
+
+@pytest.mark.parametrize("add_action", ["add", "add-upgrade"])
+@pytest.mark.parametrize("remove_action", ["remove", "remove-upgrade"])
+def test_repeated_events_removal_and_reinstallation(
+ teams_client: FlaskClient,
+ teams_engine: Engine,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ add_action: str,
+ remove_action: str,
+) -> None:
+ installation["action"] = add_action
+ headers = auth_headers()
+ for _ in range(2):
+ assert (
+ teams_client.post(PATH, json=installation, headers=headers).status_code
+ == 200
+ )
+ with Session(teams_engine) as session:
+ original = session.query(TeamsInstallation).one()
+ identity, created_on = original.id, original.created_on
+ installation["action"] = remove_action
+ for _ in range(2):
+ assert (
+ teams_client.post(PATH, json=installation, headers=headers).status_code
+ == 200
+ )
+ with Session(teams_engine) as session:
+ removed = session.query(TeamsInstallation).one()
+ assert removed.id == identity
+ assert not removed.active
+ installation["action"] = add_action
+ installation["timestamp"] = "2026-10-01T12:01:00Z"
+ refreshed = "https://smba.trafficmanager.net/emea/"
+ installation["serviceUrl"] = refreshed
+ for _ in range(2):
+ response = teams_client.post(
+ PATH, json=installation, headers=auth_headers({"serviceurl": refreshed})
+ )
+ assert response.status_code == 200
+ with Session(teams_engine) as session:
+ reinstalled = session.query(TeamsInstallation).one()
+ assert reinstalled.id == identity
+ assert reinstalled.created_on == created_on
+ assert reinstalled.active
+ assert reinstalled.service_url == refreshed
+
+
+def test_removal_retains_unknown_installation_tombstone(
+ teams_client: FlaskClient,
+ teams_engine: Engine,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+) -> None:
+ installation["action"] = "remove"
+ assert (
+ teams_client.post(PATH, json=installation, headers=auth_headers()).status_code
+ == 200
+ )
+ with Session(teams_engine) as session:
+ assert not session.query(TeamsInstallation).one().active
+
+
+@pytest.mark.parametrize(
+ "change",
+ [
+ "type",
+ "action",
+ "malformed-action",
+ "missing-service",
+ "missing-channel",
+ "missing-recipient",
+ "attachment",
+ ],
+)
+def test_unsupported_or_incomplete_events_do_not_persist(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ change: str,
+) -> None:
+ if change == "type":
+ installation["type"] = "message"
+ elif change == "action":
+ installation["action"] = "unknown"
+ elif change == "malformed-action":
+ installation["action"] = []
+ elif change == "missing-service":
+ installation.pop("serviceUrl")
+ elif change == "missing-channel":
+ installation.pop("channelId")
+ elif change == "missing-recipient":
+ installation.pop("recipient")
+ else:
+ installation["attachments"] = [{"contentType": "image/png"}]
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(PATH, json=installation, headers=auth_headers())
+ assert response.status_code == 400
+ session.assert_not_called()
+
+
+def test_session_cookie_does_not_authenticate_callback(
+ teams_client: FlaskClient, installation: dict[str, Any]
+) -> None:
+ with teams_client.session_transaction() as browser_session:
+ browser_session["_user_id"] = "1"
+ browser_session["_fresh"] = True
+ with patch.object(teams_api, "Session") as session:
+ response = teams_client.post(PATH, json=installation)
+ assert response.status_code == 401
+ session.assert_not_called()
+
+
+def test_csrf_exemption_is_only_for_callback(teams_client: FlaskClient) -> None:
+ # Without a CSRF exemption this would be 400 before SDK authentication.
+ assert teams_client.post(PATH, json={}).status_code == 401
+ assert teams_client.post("/csrf-control").status_code == 400
+ assert teams_client.get(PATH).status_code == 405
+
+
+@pytest.mark.parametrize(
+ "mode", ["disabled", "unconfigured", "invalid-config", "missing-sdk"]
+)
+def test_callback_fails_closed_without_sdk_or_configuration(
+ teams_client: FlaskClient,
+ installation: dict[str, Any],
+ auth_headers: Callable[..., dict[str, str]],
+ mode: str,
+) -> None:
+ expected = 503
+ if mode == "disabled":
+ teams_client.application.config["FEATURE_FLAGS"]["ALERT_REPORT_TEAMS"] = False
+ expected = 404
+ elif mode == "unconfigured":
+ teams_client.application.config["ALERT_REPORTS_TEAMS"] = {}
+ elif mode == "invalid-config":
+ teams_client.application.config["ALERT_REPORTS_TEAMS"] = {
+ "credential": "deployment-secret"
+ }
+ with patch.dict("sys.modules", {"superset.integrations.teams.adapter": None}):
Review Comment:
Agreed, the missing SDK patch was masking the configuration check. Limited it to missing-sdk so the unconfigured case runs with the adapter available and asserts 503 without calling event processing
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,545 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask registers its route once at startup. Each request creates a fresh SDK
+ authentication server; its handler runs to completion in an operation-scoped
+ event loop. No SDK App, outbound clients, tasks, or separate server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
+ or not isinstance(action, str)
+ or action not in actions
+ ):
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ The SDK's HttpServer uses PyJWKClient, whose network responses close within
+ its scoped fetch. It creates no persistent HTTP clients. Keep construction,
+ authentication, and adapter cleanup within the same event loop; asyncio.run
+ closes that loop on success and failure. SDK response bodies are never exposed.
+ """
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = _FlaskServerAdapter()
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server = HttpServer(adapter, messaging_endpoint=EVENTS_PATH)
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ if adapter.handler is None:
+ return TeamsEventResult(500)
+ response: HttpResponse = await adapter.handler(
+ HttpRequest(body=body, headers=headers)
+ )
+ if response["status"] != 200:
+ return TeamsEventResult(response["status"])
+ return result
+ finally:
+ await adapter.stop()
+
+ return asyncio.run(process())
+
+
+# Count every send, including the single 401 replay, against the same retry bound.
+_DELIVERY_ATTEMPTS = 4
+_DELIVERY_TIMEOUT = 60.0
+_DELIVERY_REQUEST_TIMEOUT = 10.0
+
+
+class TeamsDeliveryError(Exception):
+ """Sanitized delivery outcome for mapping to existing notification exceptions."""
+
+ def __init__(
+ self, category: Literal["authorization", "transient", "parameter"]
+ ) -> None:
+ """Expose a stable message without response bodies, SQL, tokens, or URLs."""
+ self.category = category
+ messages = {
+ "authorization": "Teams bot authorization failed",
+ "transient": "Teams alert delivery temporarily unavailable",
+ "parameter": "Teams alert delivery was rejected",
+ }
+ super().__init__(messages[category])
+
+
+class TeamsTransportError(Exception):
+ """An HTTP failure carrying only the status and Microsoft's retry metadata."""
+
+ def __init__(
+ self,
+ status: int | None = None,
+ headers: httpx.Headers
+ | requests.structures.CaseInsensitiveDict[str]
+ | None = None,
+ ) -> None:
+ """Retain only retry headers; never retain a response body or request token."""
+ super().__init__("Teams transport request failed")
+ self.status = status
+ self.retry_after = headers.get("Retry-After") if headers is not None else None
+ self.retry_after_ms = (
+ headers.get("x-ms-retry-after-ms") if headers is not None else None
+ )
+
+
+class TeamsTransport(Protocol):
+ """Replaceable operation-scoped transport; retries live outside SDK calls."""
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new channel root post containing the card."""
+ ...
+
+ async def refresh_auth(self) -> None:
+ """Invalidate cached authentication before a single 401 replay."""
+ ...
+
+
+def _remaining(deadline: float) -> float:
+ """Bound each request by its timeout and remaining delivery budget."""
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise TeamsTransportError()
+ return min(_DELIVERY_REQUEST_TIMEOUT, remaining)
+
+
+class _AuthHttpClient:
+ """MSAL HTTP interface backed by a caller-owned, timeout-bounded session."""
+
+ def __init__(self, session: requests.Session, deadline: float) -> None:
+ """Keep OAuth traffic within the same operation as the channel post."""
+ self.session = session
+ self.deadline = deadline
+
+ def get(self, url: str, **kwargs: Any) -> requests.Response:
+ """Fetch MSAL metadata without leaving a response open."""
+ return self._request("GET", url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> requests.Response:
+ """Acquire tokens without leaving a response open."""
+ return self._request("POST", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
+ """Use normal serialization, explicit timeouts, and sanitized retry errors."""
+ kwargs["timeout"] = _remaining(self.deadline)
+ response = self.session.request(method, url, **kwargs)
+ try:
+ _remaining(self.deadline)
+ # requests eagerly reads responses; MSAL can still read cached JSON
+ # after close. Closing here also covers retryable OAuth errors.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise TeamsTransportError(response.status_code, response.headers)
+ return response
+ finally:
+ response.close()
+
+
+class _ChannelConversationParams(CreateConversationParams):
+ """Include the connector's group flag, absent from the SDK base parameter model."""
+
+ is_group: Literal[True] = True
+
+
+class _SDKTeamsTransport:
+ """Use the SDK create-conversation API with shared, explicitly owned resources."""
+
+ def __init__(
+ self,
+ config: TeamsConfig,
+ service_url: str,
+ http: Client,
+ auth_http: _AuthHttpClient,
+ deadline: float,
+ ) -> None:
+ """Prepare the SDK without constructing a full App or starting a server."""
+ self.config = config
+ self.http = http
+ self.auth_http = auth_http
+ self.deadline = deadline
+ self.auth: ConfidentialClientApplication | None = None
+ self.api = ApiClient(service_url, http)
+
+ def _authenticate(self) -> None:
+ """Acquire a bot token without exposing identity-provider errors."""
+ if self.http.token:
+ return
+ if self.auth is None:
+ self.auth = ConfidentialClientApplication(
+ self.config.application_id,
+ client_credential=self.config.credential,
+ authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
+ http_client=self.auth_http,
+ instance_discovery=False,
+ )
+ result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
+ token = result.get("access_token")
+ if not isinstance(token, str) or not token:
+ status = (
+ 503
+ if result.get("error") in {"temporarily_unavailable", "server_error"}
+ else 401
+ )
+ raise TeamsTransportError(status)
+ self.http.token = token
+
+ async def refresh_auth(self) -> None:
+ """Invalidate MSAL app tokens so the next request acquires a fresh token."""
+ if self.auth is not None:
+ self.auth.remove_tokens_for_client()
+ self.http.token = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new conversation with an initial card, never reply to a thread."""
+ try:
+ self._authenticate()
+ self.http.http.timeout = httpx.Timeout(_remaining(self.deadline))
+ await self.api.conversations.create(
+ _ChannelConversationParams(
+ tenant_id=self.config.tenant_id,
+ channel_data={
+ "tenant": {"id": self.config.tenant_id},
+ "team": {"id": destination.team_id},
+ "channel": {"id": destination.channel_id},
+ },
+ activity=MessageActivityInput(
+ attachments=[
+ Attachment(
+ content_type="application/vnd.microsoft.card.adaptive",
+ content=card,
+ )
+ ]
+ ),
+ )
+ )
+ except httpx.HTTPStatusError as ex:
+ error = TeamsTransportError(ex.response.status_code, ex.response.headers)
+ await ex.response.aclose()
+ raise error from None
+ except (httpx.RequestError, requests.RequestException):
Review Comment:
Restricted transport retries to safe pre-send failures. Read, write, and protocol errors now stop after one attempt and report that delivery may have succeeded. Added regression tests for both paths also
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4380641426
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask registers its route once at startup. Each request creates a fresh SDK
+ authentication server; its handler runs to completion in an operation-scoped
+ event loop. No SDK App, outbound clients, tasks, or separate server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ if not _allowed_token(config, event):
+ return TeamsEventResult(403)
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if (
+ body.get("type") != "installationUpdate"
+ or not isinstance(action, str)
+ or action not in actions
+ ):
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ The SDK's HttpServer uses PyJWKClient, whose network responses close within
+ its scoped fetch. It creates no persistent HTTP clients. Keep construction,
+ authentication, and adapter cleanup within the same event loop; asyncio.run
+ closes that loop on success and failure. SDK response bodies are never exposed.
+ """
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = _FlaskServerAdapter()
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server = HttpServer(adapter, messaging_endpoint=EVENTS_PATH)
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ if adapter.handler is None:
+ return TeamsEventResult(500)
+ response: HttpResponse = await adapter.handler(
+ HttpRequest(body=body, headers=headers)
+ )
+ if response["status"] != 200:
+ return TeamsEventResult(response["status"])
+ return result
+ finally:
+ await adapter.stop()
+
+ return asyncio.run(process())
+
+
+# Count every send, including the single 401 replay, against the same retry bound.
+_DELIVERY_ATTEMPTS = 4
+_DELIVERY_TIMEOUT = 60.0
+_DELIVERY_REQUEST_TIMEOUT = 10.0
+
+
+class TeamsDeliveryError(Exception):
+ """Sanitized delivery outcome for mapping to existing notification exceptions."""
+
+ def __init__(
+ self, category: Literal["authorization", "transient", "parameter", "unknown"]
+ ) -> None:
+ """Expose a stable message without response bodies, SQL, tokens, or URLs."""
+ self.category = category
+ messages = {
+ "authorization": "Teams bot authorization failed",
+ "transient": "Teams alert delivery temporarily unavailable",
+ "parameter": "Teams alert delivery was rejected",
+ "unknown": (
+ "Teams alert delivery could not be confirmed. "
+ "It may have been delivered"
+ ),
+ }
+ super().__init__(messages[category])
+
+
+class TeamsTransportError(Exception):
+ """Sanitized HTTP failure with explicit retry safety for status-less errors."""
+
+ def __init__(
+ self,
+ status: int | None = None,
+ headers: httpx.Headers
+ | requests.structures.CaseInsensitiveDict[str]
+ | None = None,
+ *,
+ retryable: bool = False,
+ ) -> None:
+ """Retain only retry headers; never retain a response body or request token."""
+ super().__init__("Teams transport request failed")
+ self.status = status
+ self.retryable = retryable
+ self.retry_after = headers.get("Retry-After") if headers is not None else None
+ self.retry_after_ms = (
+ headers.get("x-ms-retry-after-ms") if headers is not None else None
+ )
+
+
+class TeamsTransport(Protocol):
+ """Replaceable operation-scoped transport; retries live outside SDK calls."""
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new channel root post containing the card."""
+ ...
+
+ async def refresh_auth(self) -> None:
+ """Invalidate cached authentication before a single 401 replay."""
+ ...
+
+
+def _remaining(deadline: float) -> float:
+ """Bound each request by its timeout and remaining delivery budget."""
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise TeamsTransportError(retryable=True)
+ return min(_DELIVERY_REQUEST_TIMEOUT, remaining)
+
+
+class _AuthHttpClient:
+ """MSAL HTTP interface backed by a caller-owned, timeout-bounded session."""
+
+ def __init__(self, session: requests.Session, deadline: float) -> None:
+ """Keep OAuth traffic within the same operation as the channel post."""
+ self.session = session
+ self.deadline = deadline
+
+ def get(self, url: str, **kwargs: Any) -> requests.Response:
+ """Fetch MSAL metadata without leaving a response open."""
+ return self._request("GET", url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> requests.Response:
+ """Acquire tokens without leaving a response open."""
+ return self._request("POST", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
+ """Use normal serialization, explicit timeouts, and sanitized retry errors."""
+ kwargs["timeout"] = _remaining(self.deadline)
+ response = self.session.request(method, url, **kwargs)
+ try:
+ _remaining(self.deadline)
+ # requests eagerly reads responses; MSAL can still read cached JSON
+ # after close. Closing here also covers retryable OAuth errors.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise TeamsTransportError(response.status_code, response.headers)
+ return response
+ finally:
+ response.close()
+
+
+class _ChannelConversationParams(CreateConversationParams):
+ """Include the connector's group flag, absent from the SDK base parameter model."""
+
+ is_group: Literal[True] = True
+
+
+class _SDKTeamsTransport:
+ """Use the SDK create-conversation API with shared, explicitly owned resources."""
+
+ def __init__(
+ self,
+ config: TeamsConfig,
+ service_url: str,
+ http: Client,
+ auth_http: _AuthHttpClient,
+ deadline: float,
+ ) -> None:
+ """Prepare the SDK without constructing a full App or starting a server."""
+ self.config = config
+ self.http = http
+ self.auth_http = auth_http
+ self.deadline = deadline
+ self.auth: ConfidentialClientApplication | None = None
+ self.api = ApiClient(service_url, http)
+
+ def _authenticate(self) -> None:
+ """Acquire a bot token without exposing identity-provider errors."""
+ if self.http.token:
+ return
+ if self.auth is None:
+ self.auth = ConfidentialClientApplication(
+ self.config.application_id,
+ client_credential=self.config.credential,
+ authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
+ http_client=self.auth_http,
+ instance_discovery=False,
+ )
+ result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
+ token = result.get("access_token")
+ if not isinstance(token, str) or not token:
+ status = (
+ 503
+ if result.get("error") in {"temporarily_unavailable", "server_error"}
+ else 401
+ )
+ raise TeamsTransportError(status)
+ self.http.token = token
+
+ async def refresh_auth(self) -> None:
+ """Invalidate MSAL app tokens so the next request acquires a fresh token."""
+ if self.auth is not None:
+ self.auth.remove_tokens_for_client()
+ self.http.token = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new conversation with an initial card, never reply to a thread."""
+ try:
+ self._authenticate()
+ self.http.http.timeout = httpx.Timeout(_remaining(self.deadline))
+ await self.api.conversations.create(
+ _ChannelConversationParams(
+ tenant_id=self.config.tenant_id,
+ channel_data={
+ "tenant": {"id": self.config.tenant_id},
+ "team": {"id": destination.team_id},
+ "channel": {"id": destination.channel_id},
+ },
+ activity=MessageActivityInput(
+ attachments=[
+ Attachment(
+ content_type="application/vnd.microsoft.card.adaptive",
+ content=card,
+ )
+ ]
+ ),
+ )
+ )
+ except httpx.HTTPStatusError as ex:
+ error = TeamsTransportError(ex.response.status_code, ex.response.headers)
+ await ex.response.aclose()
+ raise error from None
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout):
+ raise TeamsTransportError(retryable=True) from None
+ except httpx.RequestError:
+ # The connector may have accepted the POST before the connection failed.
+ raise TeamsTransportError() from None
+ except requests.RequestException:
+ # requests is used only for authentication, before the connector POST.
+ raise TeamsTransportError(retryable=True) from None
+ except ValueError:
+ # Includes invalid SDK models/response JSON. Replaying a successful
+ # POST whose response could not be decoded could duplicate delivery.
+ raise TeamsDeliveryError("parameter") from None
+
+
+@asynccontextmanager
+async def _create_transport(
+ config: TeamsConfig, service_url: str, deadline: float
+) -> AsyncIterator[TeamsTransport]:
+ """Close the SDK's shared async client and MSAL's session in the same operation."""
+ http = Client(ClientOptions(timeout=_DELIVERY_REQUEST_TIMEOUT))
+ try:
+ with requests.Session() as session:
+ yield _SDKTeamsTransport(
+ config, service_url, http, _AuthHttpClient(session, deadline), deadline
+ )
+ finally:
+ await http.http.aclose()
+
+
+def _retry_delay(error: TeamsTransportError, attempt: int) -> float:
+ """Honor Microsoft's retry headers, falling back to bounded exponential delays."""
+ delays: list[float] = []
+ for value, divisor in [(error.retry_after_ms, 1000), (error.retry_after, 1)]:
+ if value is None:
+ continue
+ try:
+ delay = float(value) / divisor
+ except ValueError:
+ if divisor != 1:
+ continue
+ try:
+ retry_at = parsedate_to_datetime(value)
+ if retry_at.tzinfo is None:
+ retry_at = retry_at.replace(tzinfo=timezone.utc)
+ delay = (retry_at - datetime.now(timezone.utc)).total_seconds()
+ except (ValueError, TypeError, OverflowError):
+ continue
+ if math.isfinite(delay):
+ delays.append(max(0.0, delay))
+ return max(delays) if delays else min(2.0**attempt, 8.0)
+
+
+async def _deliver_with_retries(
+ transport: TeamsTransport,
+ destination: TeamsDestination,
+ card: dict[str, Any],
+ deadline: float,
+) -> None:
+ """Bound transient retries and allow exactly one authentication refresh."""
+ refreshed = False
+ for attempt in range(_DELIVERY_ATTEMPTS):
+ if monotonic() >= deadline:
+ raise TeamsDeliveryError("transient")
+ try:
+ await transport.post_root(destination, card)
+ if monotonic() >= deadline:
Review Comment:
Removed both post-send deadline checks so confirmed delivery stays successful. Pre-send deadlines and request timeouts are still in place
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4426553738
##########
tests/unit_tests/integrations/teams/destinations_test.py:
##########
@@ -0,0 +1,255 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Browser discovery only projects approved keys and active-installation status."""
+
+from collections.abc import Iterator
+from datetime import datetime, timezone
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from flask import current_app, Flask
+from sqlalchemy import event
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import destinations
+from superset.integrations.teams.store import TeamsInstallationStore
+
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+OTHER = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+
+
+@pytest.fixture
+def configured_app(
+ teams_config: dict[str, Any], teams_engine: Engine, monkeypatch: pytest.MonkeyPatch
+) -> Iterator[Flask]:
+ app = Flask(__name__)
+ teams_config["destinations"].extend(
+ [
+ {
+ "key": "finance",
+ "label": "Finance",
+ "team_id": "team-1",
+ "channel_id": "channel-2",
+ },
+ {
+ "key": "support",
+ "label": "Support",
+ "team_id": "team-2",
+ "channel_id": "channel-3",
+ },
+ ]
+ )
+ app.config["ALERT_REPORTS_TEAMS"] = teams_config
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda name: True
+ )
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", lambda: True)
+ engine = teams_engine
+ monkeypatch.setattr(destinations, "db", MagicMock(engine=engine))
+ with app.app_context():
+ yield app
+
+
+def test_only_approved_public_fields_and_missing_installations(
+ configured_app: Flask,
+) -> None:
+ assert destinations.list_teams_destinations() == [
+ {"key": "ops", "label": "Operations", "available": False},
+ {"key": "finance", "label": "Finance", "available": False},
+ {"key": "support", "label": "Support", "available": False},
+ ]
+
+
+def test_removal_and_reinstallation_update_availability(configured_app: Flask) -> None:
+ with Session(destinations.db.engine) as session:
+ store = TeamsInstallationStore(session)
+ store.install(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ store.install(
+ TENANT,
+ APPLICATION,
+ "unapproved-team",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert [
+ item["available"] for item in destinations.list_teams_destinations()
+ ] == [True, True, False]
+ store.remove(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert not any(
+ item["available"] for item in destinations.list_teams_destinations()
+ )
+ store.install(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/emea/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert [
+ item["available"] for item in destinations.list_teams_destinations()
+ ] == [True, True, False]
+ assert len(destinations.list_teams_destinations()) == 3
+
+
+@pytest.mark.parametrize("tenant,application", [(OTHER, APPLICATION), (TENANT, OTHER)])
+def test_other_identity_cannot_make_destination_available(
+ configured_app: Flask, tenant: str, application: str
+) -> None:
+ with Session(destinations.db.engine) as session:
+ TeamsInstallationStore(session).install(
+ tenant,
+ application,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert not any(item["available"] for item in destinations.list_teams_destinations())
+
+
+@pytest.mark.parametrize("configuration", [{}, {"credential": "invalid-secret"}])
+def test_unconfigured_or_invalid_integration_is_hidden(
+ configured_app: Flask, configuration: dict[str, Any]
+) -> None:
+ current_app.config["ALERT_REPORTS_TEAMS"] = configuration
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+
+
+def test_disabled_integration_does_not_query_installations(
+ configured_app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda name: False
+ )
+ monkeypatch.setattr(
+ destinations, "Session", MagicMock(side_effect=AssertionError("must not query"))
+ )
+ assert destinations.list_teams_destinations() == []
+
+
+@pytest.mark.parametrize("team_id", ["t" * 256, " team-1", "team-1 ", "\tteam-1\n"])
+def test_invalid_team_config_is_hidden_before_installation_lookup(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ team_id: str,
+) -> None:
+ """Discovery handles invalid deployment IDs instead of raising store ValueError."""
+ configured_app.config["ALERT_REPORTS_TEAMS"]["destinations"][0]["team_id"] = team_id
+ lookup = MagicMock(side_effect=AssertionError("must not query installations"))
+ monkeypatch.setattr(destinations, "Session", lookup)
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ lookup.assert_not_called()
+
+
+@pytest.mark.parametrize("installed", [False, True])
+def test_optional_sdk_controls_both_discovery_and_notification_methods(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ installed: bool,
+) -> None:
+ """Bootstrap and destination discovery agree when the optional SDK is missing."""
+ from superset.reports.models import ReportRecipientType
+ from superset.views import base
+
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", lambda: installed)
+ monkeypatch.setattr(base, "app", configured_app)
+ configured_app.config["SLACK_API_TOKEN"] = None
+ if installed:
+ assert destinations.configured_teams() is not None
+ assert len(destinations.list_teams_destinations()) == 3
+ assert ReportRecipientType.TEAMS in base._notification_methods()
+ else:
+ session = MagicMock(side_effect=AssertionError("must not query installations"))
+ monkeypatch.setattr(destinations, "Session", session)
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ assert ReportRecipientType.TEAMS not in base._notification_methods()
+ session.assert_not_called()
+
+
+def test_disabled_integration_registers_and_bootstraps_without_sdk(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The Teams startup paths require neither SDK imports nor a dependency lookup."""
+ import sys
+
+ from superset.integrations.teams.api import register_teams_api
+ from superset.reports.models import ReportRecipientType
+ from superset.views import base
+
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda _: False
+ )
+ missing_sdk = MagicMock(side_effect=AssertionError("must not check SDK"))
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", missing_sdk)
+ monkeypatch.setitem(sys.modules, "superset.integrations.teams.adapter", None)
Review Comment:
Moved this to a fresh interpreter that blocks SDK imports before Superset starts. It verifies startup succeeds and the disabled callback returns 404.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4427585877
##########
tests/unit_tests/integrations/teams/destinations_test.py:
##########
@@ -0,0 +1,275 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Browser discovery only projects approved keys and active-installation status."""
+
+import subprocess
+import sys
+from collections.abc import Iterator
+from datetime import datetime, timezone
+from textwrap import dedent
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from flask import current_app, Flask
+from sqlalchemy import event
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import destinations
+from superset.integrations.teams.store import TeamsInstallationStore
+
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+OTHER = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+
+
+@pytest.fixture
+def configured_app(
+ teams_config: dict[str, Any], teams_engine: Engine, monkeypatch: pytest.MonkeyPatch
+) -> Iterator[Flask]:
+ app = Flask(__name__)
+ teams_config["destinations"].extend(
+ [
+ {
+ "key": "finance",
+ "label": "Finance",
+ "team_id": "team-1",
+ "channel_id": "channel-2",
+ },
+ {
+ "key": "support",
+ "label": "Support",
+ "team_id": "team-2",
+ "channel_id": "channel-3",
+ },
+ ]
+ )
+ app.config["ALERT_REPORTS_TEAMS"] = teams_config
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda name: True
+ )
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", lambda: True)
+ engine = teams_engine
+ monkeypatch.setattr(destinations, "db", MagicMock(engine=engine))
+ with app.app_context():
+ yield app
+
+
+def test_only_approved_public_fields_and_missing_installations(
+ configured_app: Flask,
+) -> None:
+ assert destinations.list_teams_destinations() == [
+ {"key": "ops", "label": "Operations", "available": False},
+ {"key": "finance", "label": "Finance", "available": False},
+ {"key": "support", "label": "Support", "available": False},
+ ]
+
+
+def test_removal_and_reinstallation_update_availability(configured_app: Flask) -> None:
+ with Session(destinations.db.engine) as session:
+ store = TeamsInstallationStore(session)
+ store.install(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ store.install(
+ TENANT,
+ APPLICATION,
+ "unapproved-team",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert [
+ item["available"] for item in destinations.list_teams_destinations()
+ ] == [True, True, False]
+ store.remove(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert not any(
+ item["available"] for item in destinations.list_teams_destinations()
+ )
+ store.install(
+ TENANT,
+ APPLICATION,
+ "team-1",
+ "https://smba.trafficmanager.net/emea/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert [
+ item["available"] for item in destinations.list_teams_destinations()
+ ] == [True, True, False]
+ assert len(destinations.list_teams_destinations()) == 3
+
+
+@pytest.mark.parametrize("tenant,application", [(OTHER, APPLICATION), (TENANT, OTHER)])
+def test_other_identity_cannot_make_destination_available(
+ configured_app: Flask, tenant: str, application: str
+) -> None:
+ with Session(destinations.db.engine) as session:
+ TeamsInstallationStore(session).install(
+ tenant,
+ application,
+ "team-1",
+ "https://smba.trafficmanager.net/amer/",
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ assert not any(item["available"] for item in destinations.list_teams_destinations())
+
+
+@pytest.mark.parametrize("configuration", [{}, {"credential": "invalid-secret"}])
+def test_unconfigured_or_invalid_integration_is_hidden(
+ configured_app: Flask, configuration: dict[str, Any]
+) -> None:
+ current_app.config["ALERT_REPORTS_TEAMS"] = configuration
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+
+
+def test_disabled_integration_does_not_query_installations(
+ configured_app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ destinations.feature_flag_manager, "is_feature_enabled", lambda name: False
+ )
+ monkeypatch.setattr(
+ destinations, "Session", MagicMock(side_effect=AssertionError("must not query"))
+ )
+ assert destinations.list_teams_destinations() == []
+
+
+@pytest.mark.parametrize("team_id", ["t" * 256, " team-1", "team-1 ", "\tteam-1\n"])
+def test_invalid_team_config_is_hidden_before_installation_lookup(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ team_id: str,
+) -> None:
+ """Discovery handles invalid deployment IDs instead of raising store ValueError."""
+ configured_app.config["ALERT_REPORTS_TEAMS"]["destinations"][0]["team_id"] = team_id
+ lookup = MagicMock(side_effect=AssertionError("must not query installations"))
+ monkeypatch.setattr(destinations, "Session", lookup)
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ lookup.assert_not_called()
+
+
+@pytest.mark.parametrize("installed", [False, True])
+def test_optional_sdk_controls_both_discovery_and_notification_methods(
+ configured_app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ installed: bool,
+) -> None:
+ """Bootstrap and destination discovery agree when the optional SDK is missing."""
+ from superset.reports.models import ReportRecipientType
+ from superset.views import base
+
+ monkeypatch.setattr(destinations, "is_teams_sdk_installed", lambda: installed)
+ monkeypatch.setattr(base, "app", configured_app)
+ configured_app.config["SLACK_API_TOKEN"] = None
+ if installed:
+ assert destinations.configured_teams() is not None
+ assert len(destinations.list_teams_destinations()) == 3
+ assert ReportRecipientType.TEAMS in base._notification_methods()
+ else:
+ session = MagicMock(side_effect=AssertionError("must not query installations"))
+ monkeypatch.setattr(destinations, "Session", session)
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ assert ReportRecipientType.TEAMS not in base._notification_methods()
+ session.assert_not_called()
+
+
+def test_disabled_integration_registers_and_bootstraps_without_sdk() -> None:
+ """Block optional imports before loading the startup paths in a fresh process."""
+ result = subprocess.run( # noqa: S603 -- fixed interpreter and inline test script
+ [
+ sys.executable,
+ "-c",
+ dedent("""
+ import importlib.abc
+ import sys
+
+ class NoTeamsSDK(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ if (fullname == "microsoft_teams"
+ or fullname.startswith("microsoft_teams.")
+ or fullname == "superset.integrations.teams.adapter"):
+ raise AssertionError("Unexpected optional import: " + fullname)
+
+ sys.meta_path.insert(0, NoTeamsSDK())
+ from superset.app import create_app
+ app = create_app()
+ from superset.integrations.teams import destinations
+ from superset.reports.models import ReportRecipientType
+ from superset.views import base
+
+ def unexpected_lookup():
+ raise AssertionError("must not check SDK")
+
+ app.config["SLACK_API_TOKEN"] = None
+ destinations.feature_flag_manager.is_feature_enabled = lambda _: False
+ destinations.is_teams_sdk_installed = unexpected_lookup
+ base.app = app
+ with app.app_context():
+ assert destinations.configured_teams() is None
+ assert destinations.list_teams_destinations() == []
+ assert ReportRecipientType.TEAMS not in base._notification_methods()
+ assert app.test_client().post(
+ "/api/v1/teams/events/", json={}
+ ).status_code == 404
Review Comment:
This 404 is also what `teams_events` returns when the flag is off, and what an unregistered route returns, so the test passes even if `register_teams_api(self.superset_app)` is dropped from `register_blueprints`. The other callback tests register the blueprint by hand, so nothing else would notice, and in a real deployment every installation callback would 404 and no installation would ever be recorded. Could this assert the route exists in `app.url_map` (for example `teams.teams_events` for `/api/v1/teams/events/`) in addition to the disabled response?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4372517648
##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -1906,6 +1890,20 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
return false;
}
+ const hasTeamsRecipients = notificationSettings.some(
+ setting => setting.method === NotificationMethodOption.Teams,
+ );
+ const invalidTeamsRecipients =
+ hasTeamsRecipients &&
+ (!teamsSupported ||
+ !teamsIntegrationAvailable ||
Review Comment:
Fixed! Pausing and metadata edits can save when Teams is unavailable. Reactivation and delivery changes still validate. Added some regression testing for this as well
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4368380917
##########
superset/integrations/teams/api.py:
##########
@@ -0,0 +1,128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Independently authenticated, installation-only Teams bot callback."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING
+
+from flask import Blueprint, current_app, Flask, request, Response
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+from werkzeug.exceptions import RequestEntityTooLarge
+
+from superset.extensions import csrf, db, feature_flag_manager
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsConfigError,
+)
+from superset.integrations.teams.store import TeamsInstallationStore
+
+if TYPE_CHECKING:
+ from superset.integrations.teams.adapter import TeamsInstallationEvent
+
+_MAX_EVENT_BYTES = 256 * 1024
+
+logger = logging.getLogger(__name__)
+blueprint = Blueprint("teams", __name__)
+
+
+def _check_event_body_size() -> None:
+ """Bound body reading and reject oversized input before JSON parsing."""
+ configured_limit = request.max_content_length
+ limit = (
+ min(_MAX_EVENT_BYTES, configured_limit)
+ if configured_limit is not None
+ else _MAX_EVENT_BYTES
+ )
+ if request.content_length is not None and request.content_length > limit:
+ raise RequestEntityTooLarge()
+ # Werkzeug can truncate lengthless streams at the limit without raising.
+ # Read one lookahead byte through Flask's bounded stream before parsing JSON.
+ request.max_content_length = limit + 1
Review Comment:
Good catch! Replaced the request limit assignment with a bounded read. Tested the callbacks on Flask 2.2.5 too, keeping the existing body-size limits
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "KristiDodaj (via GitHub)" <gi...@apache.org>.
KristiDodaj commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4395307820
##########
tests/unit_tests/integrations/teams/delivery_test.py:
##########
@@ -0,0 +1,971 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Teams notification formatting, resolution, retry, and SDK delivery tests."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import importlib.util
+import threading
+import time
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager, nullcontext
+from datetime import datetime, timedelta, timezone
+from email.utils import format_datetime
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+import requests
+from billiard.exceptions import SoftTimeLimitExceeded
+from flask import current_app, Flask
+from sqlalchemy.engine import Engine
+from sqlalchemy.orm import Session
+
+from superset.integrations.teams import validation as teams_validation
+from superset.integrations.teams.config import (
+ parse_teams_config,
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.models import TeamsInstallation
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.reports.models import ReportRecipients, ReportRecipientType
+from superset.reports.notifications import create_notification, teams as notifications
+from superset.reports.notifications.base import NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+from superset.utils import json
+
+if importlib.util.find_spec("microsoft_teams") is None:
+ pytest.skip("Optional Teams SDK is not installed", allow_module_level=True)
+
+adapter = importlib.import_module("superset.integrations.teams.adapter")
+TENANT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
+APPLICATION = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+SERVICE_URL = "https://smba.trafficmanager.net/amer/"
+
+
+@pytest.fixture
+def configured(teams_config: dict[str, Any]) -> TeamsConfig:
+ """Parse the same deployment configuration used by real notifications."""
+ config = parse_teams_config(teams_config)
+ assert config is not None
+ return config
+
+
+@pytest.fixture
+def content() -> NotificationContent:
+ """Include difficult text to verify normal structured JSON serialization."""
+ return NotificationContent(
+ name='Alert "Revenue"\nCafé 東京 🚨',
+ description='Description "quoted"\n第二行',
+ header_data={
+ "notification_type": "Alert",
+ "notification_format": "NONE",
+ "editors": [],
+ "notification_source": None,
+ "chart_id": None,
+ "dashboard_id": None,
+ "slack_channels": None,
+ "execution_id": None,
+ },
+ url="https://superset.example/chart/42/",
+ )
+
+
+@pytest.fixture
+def notification_context(
+ teams_config: dict[str, Any],
+ teams_engine: Engine,
+ monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[SimpleNamespace]:
+ """Use the real installation table and resolve through the notification class."""
+ app = Flask(__name__)
+ app.config.update(
+ ALERT_REPORTS_TEAMS=teams_config, FEATURE_FLAGS={"ALERT_REPORT_TEAMS": True}
+ )
+ engine = teams_engine
+ with Session(engine) as session:
+ TeamsInstallationStore(session).install(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ session.commit()
+ monkeypatch.setattr(notifications, "db", SimpleNamespace(engine=engine))
+ monkeypatch.setattr(
+ teams_validation.feature_flag_manager,
+ "is_feature_enabled",
+ lambda name: current_app.config["FEATURE_FLAGS"].get(name, False),
+ )
+ send = MagicMock()
+ monkeypatch.setattr(notifications, "_send_to_teams", send)
+ with app.app_context():
+ yield SimpleNamespace(app=app, engine=engine, send=send)
+
+
+def recipient(target: str = "ops") -> ReportRecipients:
+ """Recipients store only a configured destination key."""
+ return ReportRecipients(
+ type=ReportRecipientType.TEAMS,
+ recipient_config_json=json.dumps({"target": target}),
+ )
+
+
+def test_factory_resolves_active_installation_and_formats_card(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+) -> None:
+ notification = create_notification(recipient(), content)
+ assert isinstance(notification, notifications.TeamsNotification)
+ notification.send()
+ config, destination, service_url, card = notification_context.send.call_args.args
+ assert config.credential == "deployment-secret"
+ assert destination.key == "ops"
+ assert destination.channel_id == "channel-1"
+ assert service_url == SERVICE_URL
+ assert card["body"][0]["text"] == content.name
+ assert card["body"][1]["text"] == content.description
+ assert card["actions"][0]["url"] == content.url
+ assert "deployment-secret" not in json.dumps(card)
+
+
+@pytest.mark.parametrize(
+ "mode", ["inactive", "missing", "other-tenant", "other-application"]
+)
+def test_installation_must_be_active_for_exact_identity(
+ notification_context: SimpleNamespace,
+ content: NotificationContent,
+ mode: str,
+) -> None:
+ with Session(notification_context.engine) as session:
+ store = TeamsInstallationStore(session)
+ if mode == "inactive":
+ store.remove(
+ TENANT, APPLICATION, "team-1", SERVICE_URL, datetime.now(timezone.utc)
+ )
+ else:
+ session.query(TeamsInstallation).delete()
+ other = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"
+ if mode != "missing":
+ store.install(
+ other if mode == "other-tenant" else TENANT,
+ other if mode == "other-application" else APPLICATION,
+ "team-1",
+ SERVICE_URL,
+ datetime.now(timezone.utc),
+ )
+ session.commit()
+ with pytest.raises(NotificationAuthorizationException):
+ notifications.TeamsNotification(recipient(), content).send()
+ notification_context.send.assert_not_called()
+
+
+class FakeTransport:
+ """Deterministic replaceable transport for bounded retry policy tests."""
+
+ def __init__(self, errors: list[Exception | None]) -> None:
+ """Consume one outcome for each root post attempt."""
+ self.errors = iter(errors)
+ self.posts: list[tuple[TeamsDestination, dict[str, Any]]] = []
+ self.refreshes = 0
+ self.closed = False
+ self.loop: asyncio.AbstractEventLoop | None = None
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Record every fresh root-post attempt."""
+ self.posts.append((destination, card))
+ error = next(self.errors)
+ if error:
+ raise error
+
+ async def refresh_auth(self) -> None:
+ """Record a cache invalidation without contacting Entra."""
+ self.refreshes += 1
+
+ @asynccontextmanager
+ async def factory(
+ self, config: TeamsConfig, service_url: str, deadline: float
+ ) -> AsyncIterator[FakeTransport]:
+ """Track operation cleanup on both successful and failed delivery."""
+ self.loop = asyncio.get_running_loop()
+ try:
+ yield self
+ finally:
+ self.closed = True
+
+
+@pytest.fixture
+def retry_clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
+ """Advance retry time without actually sleeping."""
+ elapsed = [0.0]
+ sleeps: list[float] = []
+ monkeypatch.setattr(adapter, "monotonic", lambda: elapsed[0])
+
+ async def sleep(delay: float) -> None:
+ """Advance the same clock used by the retry budget."""
+ elapsed[0] += delay
+ sleeps.append(delay)
+
+ monkeypatch.setattr(adapter.asyncio, "sleep", sleep)
+ return sleeps
+
+
+@pytest.mark.parametrize(
+ "status,retryable",
+ [
+ (None, False),
+ (None, True),
+ (408, False),
+ (429, False),
+ (500, False),
+ (502, False),
+ (503, False),
+ (504, False),
+ ],
+)
+def test_transport_failures_respect_retry_safety_and_attempt_bound(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ status: int | None,
+ retryable: bool,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status, retryable=retryable)] * 4
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ ambiguous = status is None and not retryable
+ assert exc.value.category == ("unknown" if ambiguous else "transient")
+ assert len(transport.posts) == (1 if ambiguous else 4)
+ assert retry_clock == ([] if ambiguous else [1.0, 2.0, 4.0])
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "headers,expected",
+ [
+ ({"Retry-After": "3"}, 3.0),
+ ({"x-ms-retry-after-ms": "1500"}, 1.5),
+ ({"Retry-After": "2", "x-ms-retry-after-ms": "3000"}, 3.0),
+ ({"Retry-After": "invalid"}, 1.0),
+ ],
+)
+def test_microsoft_retry_delays_are_respected(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ headers: dict[str, str],
+ expected: float,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers(headers)), None]
+ )
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert retry_clock == [expected]
+ assert len(transport.posts) == 2
+ assert transport.closed
+
+
+def test_retry_after_http_date() -> None:
+ retry_at = datetime.now(timezone.utc) + timedelta(seconds=5)
+ error = adapter.TeamsTransportError(
+ 429, httpx.Headers({"Retry-After": format_datetime(retry_at, usegmt=True)})
+ )
+ assert 3.0 <= adapter._retry_delay(error, 0) <= 5.0
+
+
+def test_excessive_server_delay_is_not_shortened(
+ configured: TeamsConfig, retry_clock: list[float]
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(429, httpx.Headers({"Retry-After": "120"}))]
+ )
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == "transient"
+ assert len(transport.posts) == 1
+ assert retry_clock == []
+ assert transport.closed
+
+
+@pytest.mark.parametrize(
+ "outcomes,category,posts,refreshes",
+ [
+ ([401, None], None, 2, 1),
+ ([401, 401], "authorization", 2, 1),
+ ([403], "authorization", 1, 0),
+ ([400], "parameter", 1, 0),
+ ([404], "parameter", 1, 0),
+ ([302], "parameter", 1, 0),
+ ([401, 503, 503, None], None, 4, 1),
+ ([503, 503, 503, 401], "authorization", 4, 0),
+ ],
+)
+def test_one_authentication_refresh_and_permanent_errors(
+ configured: TeamsConfig,
+ retry_clock: list[float],
+ outcomes: list[int | None],
+ category: str | None,
+ posts: int,
+ refreshes: int,
+) -> None:
+ transport = FakeTransport(
+ [adapter.TeamsTransportError(status) if status else None for status in outcomes]
+ )
+ if category:
+ with pytest.raises(adapter.TeamsDeliveryError) as exc:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert exc.value.category == category
+ else:
+ adapter.deliver_teams_alert(
+ configured,
+ configured.destinations[0],
+ SERVICE_URL,
+ {},
+ transport_factory=transport.factory,
+ )
+ assert len(transport.posts) == posts
+ assert transport.refreshes == refreshes
+ assert transport.closed
+ assert transport.loop is not None
+ assert transport.loop.is_closed()
+
+
+@pytest.mark.parametrize(
+ "category,exception",
+ [
+ ("authorization", NotificationAuthorizationException),
+ ("transient", NotificationTransientError),
+ ("parameter", NotificationParamException),
+ ("unknown", NotificationError),
+ ],
+)
+def test_transport_errors_map_to_existing_notification_exceptions(
+ configured: TeamsConfig,
+ monkeypatch: pytest.MonkeyPatch,
+ category: str,
+ exception: type[Exception],
+) -> None:
+ monkeypatch.setattr(
+ adapter,
+ "deliver_teams_alert",
+ MagicMock(side_effect=adapter.TeamsDeliveryError(category)),
+ )
+ with pytest.raises(exception) as exc:
+ notifications._send_to_teams(
+ configured, configured.destinations[0], SERVICE_URL, {}
+ )
+ assert exc.value.__cause__ is None
+
+
+def _sdk_post_response(status: int) -> httpx.Response:
+ """Script a successful root, malformed success, or failing connector response."""
+ if status == 201:
+ return httpx.Response(
+ status, json={"id": "new-thread", "activityId": "root-message"}
+ )
+ if status == 299:
+ return httpx.Response(201, json={"malformed": "success response"})
+ return httpx.Response(
+ status, headers={"Retry-After": "2"}, json={"error": "secret SQL diagnostic"}
+ )
+
+
+@pytest.fixture
+def sdk_network(
+ monkeypatch: pytest.MonkeyPatch, retry_clock: list[float]
+) -> SimpleNamespace:
+ """Run real MSAL and SDK serializers against offline HTTP endpoints."""
+ state = SimpleNamespace(
+ posts=[],
+ tokens=0,
+ oauth_responses=[],
+ auth_sessions=[],
+ clients=[],
+ statuses=[],
+ oauth_error=None,
+ )
+
+ class TrackedResponse(requests.Response):
+ """Track closure of metadata and token HTTP responses."""
+
+ closed = False
+
+ def close(self) -> None:
+ """Record deterministic cleanup even on OAuth failures."""
+ super().close()
+ self.closed = True
+
+ class AuthSession(requests.Session):
+ """Provide real requests response objects to MSAL's HTTP contract."""
+
+ closed = False
+
+ def __init__(self) -> None:
+ """Record operation-owned sessions."""
+ super().__init__()
+ state.auth_sessions.append(self)
+
+ def request(
+ self, method: Any, url: Any, *args: Any, **kwargs: Any
+ ) -> requests.Response:
+ """Answer only known Microsoft metadata and client-credential calls."""
+ assert 0 < kwargs["timeout"] <= 10
+ response = TrackedResponse()
+ response.status_code = 200
+ response.url = url
+ if method == "GET":
+ assert (
+ url
+ == f"https://login.microsoftonline.com/{TENANT}/v2.0/.well-known/openid-configuration"
+ )
+ data: dict[str, Any] = {
+ "authorization_endpoint": f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/authorize",
+ "token_endpoint": f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token",
+ "issuer": f"https://login.microsoftonline.com/{TENANT}/v2.0",
+ }
+ else:
+ assert method == "POST"
+ assert (
+ url
+ == f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token"
+ )
+ assert kwargs["data"]["grant_type"] == "client_credentials"
+ assert (
+ kwargs["data"]["scope"] == "https://api.botframework.com/.default"
+ )
+ state.tokens += 1
+ data = {
+ "access_token": f"token-{state.tokens}",
+ "token_type": "Bearer",
+ "expires_in": 3600,
+ }
+ if state.oauth_error:
+ response.status_code = 400
+ data = {
+ "error": "invalid_client",
Review Comment:
Added both `temporarily_unavailable` and `server_error` cases, checking that retries end as transient with no connector POST
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "sadpandajoe (via GitHub) via notifications" <no...@superset.apache.org>.
sadpandajoe commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4460080105
##########
superset/reports/notifications/teams.py:
##########
@@ -0,0 +1,163 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Attachment-free alert delivery to configured Teams standard channels."""
+
+from typing import Any
+from urllib.parse import urlsplit
+
+from flask_babel import gettext as __
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from superset.extensions import db
+from superset.integrations.teams.config import (
+ TeamsConfig,
+ TeamsDestination,
+)
+from superset.integrations.teams.store import TeamsInstallationStore
+from superset.integrations.teams.validation import (
+ TeamsRecipientValidationError,
+ validate_teams_recipient,
+)
+from superset.reports.models import ReportRecipientType
+from superset.reports.notifications.base import BaseNotification, NotificationContent
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationError,
+ NotificationParamException,
+ NotificationTransientError,
+)
+
+
+def build_teams_card(content: NotificationContent) -> dict[str, Any]:
+ """Build a card using structured data, omitting raw execution diagnostics."""
+ body: list[dict[str, Any]] = [
+ {
+ "type": "TextBlock",
+ "text": content.name,
+ "weight": "Bolder",
+ "size": "Medium",
+ "wrap": True,
+ },
+ ]
+ if content.description:
+ body.append({"type": "TextBlock", "text": content.description, "wrap": True})
+ if content.text:
+ body.append(
+ {
+ "type": "TextBlock",
+ "text": __(
+ "Alert execution failed. Contact the alert owner for details."
+ ),
+ "wrap": True,
+ }
+ )
+ card: dict[str, Any] = {
+ "$schema": "https://adaptivecards.io/schemas/adaptive-card.json",
+ "type": "AdaptiveCard",
+ "version": "1.2",
+ "body": body,
+ }
+ if content.include_cta and content.url:
+ try:
+ url = urlsplit(content.url)
+ safe_link = url.scheme in {"http", "https"} and bool(url.hostname)
+ except ValueError:
+ safe_link = False
+ if safe_link:
+ card["actions"] = [
+ {
+ "type": "Action.OpenUrl",
+ "title": __("Open in Superset"),
+ "url": content.url,
+ }
+ ]
+ return card
+
+
+def _send_to_teams(
+ config: TeamsConfig,
+ destination: TeamsDestination,
+ service_url: str,
+ card: dict[str, Any],
+ *,
+ retry_deadline: float | None = None,
+) -> None:
+ """Load the optional SDK only for delivery and map sanitized transport errors."""
+ try:
+ from superset.integrations.teams.adapter import (
+ deliver_teams_alert,
+ TeamsDeliveryError,
+ )
+ except ImportError:
+ raise NotificationParamException("Teams SDK is not installed") from None
+ try:
+ deliver_teams_alert(
+ config, destination, service_url, card, retry_deadline=retry_deadline
Review Comment:
`retry_deadline` is what keeps a Teams send inside the report's cleanup reserve, but no test asserts it reaches `deliver_teams_alert`: `test_transport_errors_map_to_existing_notification_exceptions` patches `deliver_teams_alert` with a `MagicMock` and never inspects its call arguments, and the `teams_tests.py` factory test stubs `_send_to_teams` entirely. Dropping `retry_deadline=retry_deadline` here would give every send a fresh budget and every existing test would still pass. Could one test call `_send_to_teams(..., retry_deadline=42.0)` and assert the adapter receives `retry_deadline=42.0`?
##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -1906,6 +1895,59 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
return false;
}
+ const hasTeamsRecipients = notificationSettings.some(
+ setting => setting.method === NotificationMethodOption.Teams,
+ );
+ // Match the backend's delivery-change check so unavailable integrations do
+ // not prevent pausing or editing metadata on an existing alert.
+ const normalizeRecipients = (
+ recipients: {
+ type: string;
+ recipient_config_json: string | Recipient['recipient_config_json'];
+ }[],
+ ) =>
+ JSON.stringify(
+ recipients
+ .map(({ type, recipient_config_json: config }) => {
+ const parsed =
+ typeof config === 'string' ? JSON.parse(config) : config;
+ return JSON.stringify([
+ type,
+ Object.entries(parsed)
+ .filter(
+ ([key, value]) =>
+ value !== undefined &&
+ !(
+ type !== NotificationMethodOption.Teams &&
+ ['ccTarget', 'bccTarget'].includes(key) &&
+ value === ''
+ ),
+ )
+ .sort(([left], [right]) => left.localeCompare(right)),
+ ]);
+ })
+ .sort(),
+ );
+ const deliveryUnchanged =
+ hasTeamsRecipients &&
+ isEditMode &&
+ resource &&
+ !(currentAlert?.active && !resource.active) &&
+ resource.type === (isReport ? 'Report' : 'Alert') &&
+ resource.report_format === effectiveReportFormat &&
+ normalizeRecipients(resource.recipients || []) ===
+ normalizeRecipients(getRecipients());
+ const invalidTeamsRecipients =
+ hasTeamsRecipients &&
+ ((!deliveryUnchanged &&
+ (!teamsSupported || !teamsIntegrationAvailable)) ||
Review Comment:
This `.some(... Teams && !setting.recipients)` clause is the only thing that blocks Save when a Teams row is added but no destination is picked next to a valid Email row: `hasInfo` below is satisfied by the Email row, and `getRecipients` skips the empty Teams entry. None of the new modal tests leaves a Teams destination blank alongside another recipient, so deleting this clause still passes and the PUT would silently drop the Teams recipient. Could a test add Teams next to a valid Email row, leave it blank and assert Save is disabled, then pick a destination and assert it is enabled?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4360917363
##########
superset-frontend/src/features/alerts/notificationMethods.ts:
##########
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { NotificationMethodOption, NotificationSetting } from './types';
+
+const isSlackMethod = (method: NotificationMethodOption | undefined) =>
+ method === NotificationMethodOption.Slack ||
+ method === NotificationMethodOption.SlackV2;
+
+export function getNotificationMethodOptions(
+ available: NotificationMethodOption[],
+ settings: NotificationSetting[],
+ currentIndex?: number,
+): NotificationMethodOption[] {
+ const selected =
+ currentIndex === undefined ? undefined : settings[currentIndex]?.method;
+ const options = available.filter(
+ method =>
+ method === NotificationMethodOption.Teams ||
+ !settings.some(
+ (setting, index) =>
+ index !== currentIndex &&
+ (setting.method === method ||
+ (isSlackMethod(setting.method) && isSlackMethod(method))),
+ ),
+ );
+ return selected ? Array.from(new Set([...options, selected])) : options;
+}
+
+export function supportsTeamsRecipients(
+ isReport: boolean,
+ attachmentsEnabled: boolean,
+ reportFormat: string,
+): boolean {
+ return !isReport && (!attachmentsEnabled || reportFormat === 'NONE');
Review Comment:
**Suggestion:** When attachments are globally disabled, this returns true even for saved PNG/CSV alerts; the modal preserves that format, so Teams edits pass client checks but the backend rejects the save.
**Assessment:** 🟠 `Major` · 🔁 `Occurrence: Sometimes` · 🏷️ `Incorrect condition logic`
[](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=110f66151ec047dc9271e826295d77f6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=110f66151ec047dc9271e826295d77f6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/features/alerts/notificationMethods.ts
**Line:** 50:50
**Comment:**
*Incorrect Condition Logic: When attachments are globally disabled, this returns true even for saved PNG/CSV alerts; the modal preserves that format, so Teams edits pass client checks but the backend rejects the save.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F45508&comment_hash=b0f4c1f05c178e01e81b8c61b97c88afe53322bd755b71c4a58bf0e4dc088983&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F45508&comment_hash=b0f4c1f05c178e01e81b8c61b97c88afe53322bd755b71c4a58bf0e4dc088983&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "github-actions[bot] (via GitHub) via notifications" <no...@superset.apache.org>.
github-actions[bot] commented on PR #45508:
URL: https://github.com/apache/superset/pull/45508#issuecomment-7047530239
### ⚠️ Possible DB migration conflict
@KristiDodaj the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(reports): add native Microsoft Teams alert notifications [superset]
Posted by "aminghadersohi (via GitHub) via notifications" <no...@superset.apache.org>.
aminghadersohi commented on code in PR #45508:
URL: https://github.com/apache/superset/pull/45508#discussion_r4636851016
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,578 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from functools import lru_cache
+from threading import Lock
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask owns the listening server. SDK authentication is reused, while each
+ callback runs to completion in an operation-scoped event loop. No SDK App,
+ outbound clients, tasks, or separate listening server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if not isinstance(action, str) or action not in actions:
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+@lru_cache(maxsize=8)
+def _callback_server(
+ process_id: int, application_id: str, tenant_id: str
+) -> tuple[HttpServer, Lock]:
+ """Retain SDK signing-key caches per process and configured identity.
+
+ The process ID avoids inheriting a locked server when a worker forks.
+ The lock serializes use of the SDK's mutable on_request callback.
+ """
+ return HttpServer(_FlaskServerAdapter(), messaging_endpoint=EVENTS_PATH), Lock()
+
+
+_CALLBACK_LOCK_TIMEOUT = 1.0
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ Only the SDK server and its signing-key cache survive requests. Request
+ handlers and event loops are released after every callback, and no outbound
+ SDK client is created. Credentials and event bodies are not cache keys.
+ """
+ server, lock = _callback_server(
+ os.getpid(), config.application_id, config.tenant_id
+ )
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = server.adapter
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ if not _allowed_token(config, event):
+ result = TeamsEventResult(403)
+ elif body.get("type") != "installationUpdate":
+ result = TeamsEventResult(200)
+ else:
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ response: HttpResponse = await server.handle_request(
+ HttpRequest(body=body, headers=headers)
+ )
Review Comment:
A forged token with iss https://sts.windows.net/<random tid>/ makes the SDK fetch that tenant's signing keys on every request while this process holds the callback lock; with 4 junk senders, 7 of 10 valid install events got 503. Rejecting non-connector issuers before the lock avoids it.
##########
superset/integrations/teams/adapter.py:
##########
@@ -0,0 +1,578 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Microsoft Teams SDK boundary for Flask callbacks and root channel delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from functools import lru_cache
+from threading import Lock
+from time import monotonic
+from typing import Any, Literal, Protocol
+from uuid import UUID
+
+import httpx
+import requests
+from microsoft_teams.api import (
+ ApiClient,
+ Attachment,
+ ClientCredentials,
+ InstalledActivity,
+ InvokeResponse,
+ JsonWebToken,
+ MessageActivityInput,
+ UninstalledActivity,
+)
+from microsoft_teams.api.auth.cloud_environment import PUBLIC
+from microsoft_teams.api.clients.conversation import CreateConversationParams
+from microsoft_teams.apps import HttpServer, HttpServerAdapter
+from microsoft_teams.apps.events import ActivityEvent
+from microsoft_teams.apps.http import HttpRequest, HttpResponse, HttpRouteHandler
+from microsoft_teams.common import Client, ClientOptions
+from msal import ConfidentialClientApplication
+from pydantic import ValidationError
+
+from superset.integrations.teams.config import TeamsConfig, TeamsDestination
+
+EVENTS_PATH = "/api/v1/teams/events/"
+
+
+@dataclass(frozen=True)
+class TeamsInstallationEvent:
+ """Authenticated, deployment-scoped installation data, with no SDK objects."""
+
+ team_id: str
+ service_url: str
+ active: bool
+ event_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamsEventResult:
+ """Callback outcome; only an authenticated event may reach persistence."""
+
+ status: int
+ event: TeamsInstallationEvent | None = None
+
+
+class _FlaskServerAdapter(HttpServerAdapter):
+ """Capture the SDK route for one invocation of Flask's existing POST route.
+
+ Flask owns the listening server. SDK authentication is reused, while each
+ callback runs to completion in an operation-scoped event loop. No SDK App,
+ outbound clients, tasks, or separate listening server are created.
+ """
+
+ def __init__(self) -> None:
+ """Hold only the handler for this request."""
+ self.handler: HttpRouteHandler | None = None
+
+ def register_route(
+ self, method: Literal["POST"], path: str, handler: HttpRouteHandler
+ ) -> None:
+ """Accept only the independently authenticated Teams callback."""
+ if method != "POST" or path != EVENTS_PATH or self.handler is not None:
+ raise ValueError("Unexpected Teams SDK route registration")
+ self.handler = handler
+
+ async def start(self, port: int) -> None:
+ """Prevent the SDK from starting its own HTTP server."""
+ raise RuntimeError("Flask manages the Teams callback server")
+
+ async def stop(self) -> None:
+ """Release the operation's handler; Flask owns the HTTP server."""
+ self.handler = None
+
+
+def _same_uuid(value: object, expected: str) -> bool:
+ """Compare concrete UUIDs without accepting tenant aliases."""
+ try:
+ return isinstance(value, str) and UUID(value) == UUID(expected)
+ except ValueError:
+ return False
+
+
+def _allowed_token(config: TeamsConfig, event: ActivityEvent) -> bool:
+ """Restrict the SDK's broader auth support to expiring bot service tokens."""
+ # Only Bot Framework service tokens bind serviceurl to a signed claim.
+ # Agent 365/Entra activities and bot-to-bot callers are outside this integration.
+ token = event.token
+ return (
+ isinstance(token, JsonWebToken)
+ and token.issuer == PUBLIC.token_issuer
+ and token.expiration is not None
+ and (not token.tenant_id or _same_uuid(token.tenant_id, config.tenant_id))
+ )
+
+
+def _installation_event(
+ config: TeamsConfig, event: ActivityEvent, body: dict[str, Any]
+) -> TeamsEventResult:
+ """Apply deployment restrictions only after the SDK has authenticated the token."""
+ token = event.token
+ actions = {
+ "add": "add",
+ "add-upgrade": "add",
+ "remove": "remove",
+ "remove-upgrade": "remove",
+ }
+ action = body.get("action")
+ if not isinstance(action, str) or action not in actions:
+ return TeamsEventResult(400)
+ action = actions[action]
+ # Require the wire-format fields used by SDK authentication. Do not allow
+ # model defaults or snake_case aliases to bypass missing channel/service data.
+ if body.get("channelId") != "msteams" or not isinstance(
+ body.get("serviceUrl"), str
+ ):
+ return TeamsEventResult(400)
+ service_url = body["serviceUrl"]
+ if not service_url or token.service_url.rstrip("/") != service_url.rstrip("/"):
+ return TeamsEventResult(403)
+ try:
+ model = InstalledActivity if action == "add" else UninstalledActivity
+ activity = model.model_validate({**body, "action": action})
+ except ValidationError:
+ return TeamsEventResult(400)
+ if activity.recipient.id not in {
+ config.application_id,
+ f"28:{config.application_id}",
+ }:
+ return TeamsEventResult(403)
+ data = activity.channel_data
+ if (
+ data is None
+ or data.tenant is None
+ or not _same_uuid(data.tenant.id, config.tenant_id)
+ or activity.conversation.conversation_type != "channel"
+ or (
+ activity.conversation.tenant_id is not None
+ and not _same_uuid(activity.conversation.tenant_id, config.tenant_id)
+ )
+ or data.team is None
+ or not data.team.id
+ or data.team.team_type not in (None, "standard")
+ or (data.channel is not None and data.channel.type not in (None, "standard"))
+ ):
+ return TeamsEventResult(403)
+ approved_teams = {destination.team_id for destination in config.destinations}
+ if data.team.id not in approved_teams:
+ return TeamsEventResult(403)
+ event_at = activity.timestamp
+ if (
+ body.get("attachments")
+ or event_at is None
+ or event_at.tzinfo is None
+ or event_at.utcoffset() is None
+ ):
+ return TeamsEventResult(400)
+ return TeamsEventResult(
+ 200,
+ TeamsInstallationEvent(data.team.id, service_url, action == "add", event_at),
+ )
+
+
+@lru_cache(maxsize=8)
+def _callback_server(
+ process_id: int, application_id: str, tenant_id: str
+) -> tuple[HttpServer, Lock]:
+ """Retain SDK signing-key caches per process and configured identity.
+
+ The process ID avoids inheriting a locked server when a worker forks.
+ The lock serializes use of the SDK's mutable on_request callback.
+ """
+ return HttpServer(_FlaskServerAdapter(), messaging_endpoint=EVENTS_PATH), Lock()
+
+
+_CALLBACK_LOCK_TIMEOUT = 1.0
+
+
+def process_teams_event(
+ config: TeamsConfig, body: dict[str, Any], headers: dict[str, str]
+) -> TeamsEventResult:
+ """Authenticate through the SDK's server adapter without starting a server.
+
+ Only the SDK server and its signing-key cache survive requests. Request
+ handlers and event loops are released after every callback, and no outbound
+ SDK client is created. Credentials and event bodies are not cache keys.
+ """
+ server, lock = _callback_server(
+ os.getpid(), config.application_id, config.tenant_id
+ )
+
+ async def process() -> TeamsEventResult:
+ """Run one SDK invocation, returning only sanitized application data."""
+ adapter = server.adapter
+ result = TeamsEventResult(500)
+
+ async def on_request(event: ActivityEvent) -> InvokeResponse[None]:
+ """Receive activities only after SDK authentication succeeds."""
+ nonlocal result
+ if not _allowed_token(config, event):
+ result = TeamsEventResult(403)
+ elif body.get("type") != "installationUpdate":
+ result = TeamsEventResult(200)
+ else:
+ result = _installation_event(config, event, body)
+ return InvokeResponse(status=result.status)
+
+ try:
+ server.on_request = on_request
+ server.initialize(
+ credentials=ClientCredentials(
+ client_id=config.application_id,
+ client_secret=config.credential,
+ tenant_id=config.tenant_id,
+ ),
+ dangerously_allow_unauthenticated_requests=False,
+ )
+ response: HttpResponse = await server.handle_request(
+ HttpRequest(body=body, headers=headers)
+ )
+ if response["status"] != 200:
+ return TeamsEventResult(response["status"])
+ return result
+ finally:
+ server.on_request = None
+ await adapter.stop()
+
+ if not lock.acquire(timeout=_CALLBACK_LOCK_TIMEOUT):
+ return TeamsEventResult(503)
+ try:
+ return asyncio.run(process())
+ finally:
+ lock.release()
+
+
+# Count every send, including the single 401 replay, against the same retry bound.
+_DELIVERY_ATTEMPTS = 4
+_DELIVERY_TIMEOUT = 60.0
+_DELIVERY_REQUEST_TIMEOUT = 10.0
+
+
+class TeamsDeliveryError(Exception):
+ """Sanitized delivery outcome for mapping to existing notification exceptions."""
+
+ def __init__(
+ self, category: Literal["authorization", "transient", "parameter", "unknown"]
+ ) -> None:
+ """Expose a stable message without response bodies, SQL, tokens, or URLs."""
+ self.category = category
+ messages = {
+ "authorization": "Teams bot authorization failed",
+ "transient": "Teams alert delivery temporarily unavailable",
+ "parameter": "Teams alert delivery was rejected",
+ "unknown": (
+ "Teams alert delivery could not be confirmed. "
+ "It may have been delivered"
+ ),
+ }
+ super().__init__(messages[category])
+
+
+class TeamsTransportError(Exception):
+ """Sanitized HTTP failure with explicit retry safety for status-less errors."""
+
+ def __init__(
+ self,
+ status: int | None = None,
+ headers: httpx.Headers
+ | requests.structures.CaseInsensitiveDict[str]
+ | None = None,
+ *,
+ retryable: bool = False,
+ ) -> None:
+ """Retain only retry headers; never retain a response body or request token."""
+ super().__init__("Teams transport request failed")
+ self.status = status
+ self.retryable = retryable
+ self.retry_after = headers.get("Retry-After") if headers is not None else None
+ self.retry_after_ms = (
+ headers.get("x-ms-retry-after-ms") if headers is not None else None
+ )
+
+
+class TeamsTransport(Protocol):
+ """Replaceable operation-scoped transport; retries live outside SDK calls."""
+
+ async def post_root(
+ self, destination: TeamsDestination, card: dict[str, Any]
+ ) -> None:
+ """Create a new channel root post containing the card."""
+ ...
+
+ async def refresh_auth(self) -> None:
+ """Invalidate cached authentication before a single 401 replay."""
+ ...
+
+
+def _remaining(deadline: float) -> float:
+ """Bound each request by its timeout and remaining delivery budget."""
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise TeamsTransportError(retryable=True)
+ return min(_DELIVERY_REQUEST_TIMEOUT, remaining)
+
+
+class _AuthHttpClient:
+ """MSAL HTTP interface backed by a caller-owned, timeout-bounded session."""
+
+ def __init__(self, session: requests.Session, deadline: float) -> None:
+ """Keep OAuth traffic within the same operation as the channel post."""
+ self.session = session
+ self.deadline = deadline
+
+ def get(self, url: str, **kwargs: Any) -> requests.Response:
+ """Fetch MSAL metadata without leaving a response open."""
+ return self._request("GET", url, **kwargs)
+
+ def post(self, url: str, **kwargs: Any) -> requests.Response:
+ """Acquire tokens without leaving a response open."""
+ return self._request("POST", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
+ """Use normal serialization, explicit timeouts, and sanitized retry errors."""
+ kwargs["timeout"] = _remaining(self.deadline)
+ response = self.session.request(method, url, **kwargs)
+ try:
+ _remaining(self.deadline)
+ # requests eagerly reads responses; MSAL can still read cached JSON
+ # after close. Closing here also covers retryable OAuth errors.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise TeamsTransportError(response.status_code, response.headers)
+ return response
+ finally:
+ response.close()
+
+
+class _ChannelConversationParams(CreateConversationParams):
+ """Include the connector's group flag, absent from the SDK base parameter model."""
+
+ is_group: Literal[True] = True
+
+
+class _SDKTeamsTransport:
+ """Use the SDK create-conversation API with shared, explicitly owned resources."""
+
+ def __init__(
+ self,
+ config: TeamsConfig,
+ service_url: str,
+ http: Client,
+ auth_http: _AuthHttpClient,
+ deadline: float,
+ ) -> None:
+ """Prepare the SDK without constructing a full App or starting a server."""
+ self.config = config
+ self.http = http
+ self.auth_http = auth_http
+ self.deadline = deadline
+ self.auth: ConfidentialClientApplication | None = None
+ self.api = ApiClient(service_url, http)
+
+ def _authenticate(self) -> None:
+ """Acquire a bot token without exposing identity-provider errors."""
+ if self.http.token:
+ return
+ if self.auth is None:
+ self.auth = ConfidentialClientApplication(
+ self.config.application_id,
+ client_credential=self.config.credential,
+ authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
+ http_client=self.auth_http,
+ instance_discovery=False,
+ )
+ result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
Review Comment:
Nit: MSAL raises ValueError from OIDC discovery when the tenant does not exist or a proxy answers 4xx, before any post; the `except ValueError` in `post_root` then reports 'may have been delivered'. Mapping it to an authorization failure here keeps that message for real post-send ambiguity.
```suggestion
try:
if self.auth is None:
self.auth = ConfidentialClientApplication(
self.config.application_id,
client_credential=self.config.credential,
authority=f"{PUBLIC.login_endpoint}/{self.config.tenant_id}",
http_client=self.auth_http,
instance_discovery=False,
)
result = self.auth.acquire_token_for_client([PUBLIC.bot_scope])
except ValueError:
# MSAL discovery or token parsing failed before any connector POST.
raise TeamsDeliveryError("authorization") from None
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org