Skip to content

Commit 9a5af7e

Browse files
committed
Fix OAuth2
1 parent 16b3df2 commit 9a5af7e

5 files changed

Lines changed: 163 additions & 2 deletions

File tree

‎superset-frontend/src/pages/Chart/Chart.test.tsx‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -788,4 +788,70 @@ describe('ChartPage', () => {
788788

789789
addDangerToastSpy.mockRestore();
790790
});
791+
792+
test('authorizes before loading semantic datasource metadata and retries the chart', async () => {
793+
const exploreApiRoute = 'glob:*/api/v1/explore/*';
794+
const hydrateSpy = jest.spyOn(hydrateExploreActions, 'hydrateExplore');
795+
const toastSpy = jest.spyOn(messageToastActions, 'addDangerToast');
796+
(getParsedExploreURLParams as jest.Mock).mockReturnValue(
797+
new Map([['slice_id', 106]]),
798+
);
799+
const formData = getExploreFormData({ viz_type: VizType.Table });
800+
let requests = 0;
801+
fetchMock.get(exploreApiRoute, () => {
802+
requests += 1;
803+
if (requests === 1) {
804+
return {
805+
status: 403,
806+
body: {
807+
errors: [
808+
{
809+
error_type: 'OAUTH2_REDIRECT',
810+
level: 'warning',
811+
message: "You don't have permission to access the data.",
812+
extra: { url: '/oauth2/start', tab_id: 'metadata-flow' },
813+
},
814+
],
815+
},
816+
};
817+
}
818+
return { result: { dataset: { id: 7 }, form_data: formData } };
819+
});
820+
render(<ChartPage />, { useRouter: true, useRedux: true, useDnd: true });
821+
const link = await screen.findByRole('link', {
822+
name: 'provide authorization',
823+
});
824+
expect(link).toHaveAttribute('href', '/oauth2/start');
825+
expect(hydrateSpy).not.toHaveBeenCalled();
826+
expect(toastSpy).not.toHaveBeenCalled();
827+
expect(
828+
screen.queryByTestId('mock-explore-chart-panel'),
829+
).not.toBeInTheDocument();
830+
831+
act(() => {
832+
window.dispatchEvent(
833+
new StorageEvent('storage', {
834+
key: 'oauth2_auth_complete',
835+
newValue: JSON.stringify({ tabId: 'other-flow' }),
836+
}),
837+
);
838+
});
839+
expect(requests).toBe(1);
840+
act(() => {
841+
window.dispatchEvent(
842+
new StorageEvent('storage', {
843+
key: 'oauth2_auth_complete',
844+
newValue: JSON.stringify({ tabId: 'metadata-flow' }),
845+
}),
846+
);
847+
});
848+
await screen.findByTestId('mock-explore-chart-panel');
849+
expect(requests).toBe(2);
850+
expect(hydrateSpy).toHaveBeenCalledTimes(1);
851+
expect(
852+
screen.queryByRole('link', { name: 'provide authorization' }),
853+
).not.toBeInTheDocument();
854+
hydrateSpy.mockRestore();
855+
toastSpy.mockRestore();
856+
});
791857
});

‎superset-frontend/src/pages/Chart/index.tsx‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,12 @@ import {
2828
makeApi,
2929
LabelsColorMapSource,
3030
getClientErrorObject,
31+
ErrorTypeEnum,
32+
SupersetError,
33+
SupersetApiError,
3134
} from '@superset-ui/core';
3235
import { Loading } from '@superset-ui/core/components';
36+
import { OAuth2RedirectMessage } from 'src/components/ErrorMessage';
3337
import { addDangerToast } from 'src/components/MessageToasts/actions';
3438
import { getUrlParam } from 'src/utils/urlUtils';
3539
import { URL_PARAMS } from 'src/constants';
@@ -144,6 +148,8 @@ const getDashboardContextFormData = (search: string) => {
144148

145149
export default function ExplorePage() {
146150
const [isLoaded, setIsLoaded] = useState(false);
151+
const [authenticationError, setAuthenticationError] =
152+
useState<SupersetError<{ url: string; tab_id: string }>>();
147153
const fetchGeneration = useRef(0);
148154
const abortControllerRef = useRef<AbortController | null>(null);
149155
const dispatch = useDispatch();
@@ -155,6 +161,7 @@ export default function ExplorePage() {
155161
loc: { search: string; pathname: string },
156162
saveAction?: SaveActionType | null,
157163
) => {
164+
setAuthenticationError(undefined);
158165
// Abort any in-flight request before starting a new one
159166
abortControllerRef.current?.abort();
160167
const controller = new AbortController();
@@ -231,6 +238,33 @@ export default function ExplorePage() {
231238
if (!err) {
232239
return Promise.resolve();
233240
}
241+
const oauthError: SupersetError | undefined =
242+
clientError?.errors?.find(
243+
error => error.error_type === ErrorTypeEnum.OAUTH2_REDIRECT,
244+
) ??
245+
(err instanceof SupersetApiError &&
246+
String(err.errorType) === ErrorTypeEnum.OAUTH2_REDIRECT
247+
? {
248+
error_type: ErrorTypeEnum.OAUTH2_REDIRECT,
249+
level: 'warning',
250+
message: err.message,
251+
extra: err.extra,
252+
}
253+
: undefined);
254+
if (
255+
oauthError &&
256+
typeof oauthError.extra?.url === 'string' &&
257+
typeof oauthError.extra?.tab_id === 'string'
258+
) {
259+
setAuthenticationError({
260+
...oauthError,
261+
extra: {
262+
url: oauthError.extra.url,
263+
tab_id: oauthError.extra.tab_id,
264+
},
265+
});
266+
return Promise.resolve();
267+
}
234268
const errorMesage =
235269
clientError?.message ||
236270
clientError?.error ||
@@ -379,5 +413,17 @@ export default function ExplorePage() {
379413
if (!isLoaded) {
380414
return <Loading />;
381415
}
416+
if (authenticationError) {
417+
return (
418+
<OAuth2RedirectMessage
419+
error={authenticationError}
420+
source="explore"
421+
errorMitigationFunction={() => {
422+
setIsLoaded(false);
423+
loadExploreData(history.location);
424+
}}
425+
/>
426+
);
427+
}
382428
return <ExploreViewContainer />;
383429
}

‎superset/commands/explore/get.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from superset.daos.dataset import DatasetDAO
3535
from superset.daos.datasource import DatasourceDAO
3636
from superset.daos.exceptions import DatasourceNotFound
37-
from superset.exceptions import SupersetException
37+
from superset.exceptions import OAuth2RedirectError, SupersetException
3838
from superset.explore.exceptions import WrongEndpointError
3939
from superset.explore.permalink.exceptions import ExplorePermalinkGetFailedError
4040
from superset.extensions import security_manager
@@ -196,6 +196,8 @@ def run(self) -> Optional[dict[str, Any]]: # noqa: C901
196196
try:
197197
if datasource:
198198
datasource_data = datasource.data
199+
except OAuth2RedirectError:
200+
raise
199201
except SupersetException as ex:
200202
message = ex.message
201203
except SQLAlchemyError:

‎superset/explore/api.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
from superset.explore.schemas import ExploreContextSchema
3434
from superset.extensions import event_logger
3535
from superset.views.base_api import BaseSupersetApi, statsd_metrics
36+
from superset.views.error_handling import handle_api_exception
3637

3738
logger = logging.getLogger(__name__)
3839

@@ -48,6 +49,7 @@ class ExploreRestApi(BaseSupersetApi):
4849
@expose("/", methods=("GET",))
4950
@protect()
5051
@safe
52+
@handle_api_exception
5153
@statsd_metrics
5254
@event_logger.log_this_with_context(
5355
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get",

‎tests/unit_tests/explore/api_test.py‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
# under the License.
1717

1818
from typing import Any
19-
from unittest.mock import patch
19+
from unittest.mock import MagicMock, patch, PropertyMock
2020

2121
from superset.commands.temporary_cache.exceptions import (
2222
TemporaryCacheAccessDeniedError,
@@ -70,3 +70,48 @@ def test_temporary_cache_access_denied_omits_inert_access_flag(
7070
response = client.get("/api/v1/explore/?form_data_key=abc")
7171

7272
assert "extra" not in response.json
73+
74+
75+
def test_explore_preserves_oauth_error_during_metadata_load(
76+
client: Any, full_api_access: None
77+
) -> None:
78+
"""Initial chart loading must retain the authorization link and correlation ID."""
79+
from superset.exceptions import OAuth2RedirectError
80+
81+
datasource = MagicMock()
82+
error = OAuth2RedirectError("/oauth2/start", "flow-id", "/oauth2/complete")
83+
with (
84+
patch(
85+
"superset.commands.explore.get.get_form_data",
86+
return_value=(
87+
{"datasource": "7__semantic_view", "viz_type": "table"},
88+
None,
89+
),
90+
),
91+
patch(
92+
"superset.commands.explore.get.get_datasource_info",
93+
return_value=(7, "semantic_view"),
94+
),
95+
patch(
96+
"superset.commands.explore.get.DatasourceDAO.get_datasource",
97+
return_value=datasource,
98+
),
99+
patch("superset.commands.explore.get._authorize_datasource") as authorize,
100+
patch.object(
101+
type(datasource),
102+
"data",
103+
new_callable=PropertyMock,
104+
side_effect=error,
105+
create=True,
106+
),
107+
):
108+
response = client.get(
109+
"/api/v1/explore/?datasource_id=7&datasource_type=semantic_view"
110+
)
111+
112+
authorize.assert_called_once_with(datasource, None)
113+
assert response.status_code == 403
114+
assert response.json["errors"][0]["error_type"] == "OAUTH2_REDIRECT"
115+
assert response.json["errors"][0]["extra"]["url"] == "/oauth2/start"
116+
assert response.json["errors"][0]["extra"]["tab_id"] == "flow-id"
117+
assert "result" not in response.json

0 commit comments

Comments
 (0)