Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Redirect on 401 #17597

Merged
merged 22 commits into from
Dec 8, 2021
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion requirements/base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ flask==1.1.4
# flask-openid
# flask-sqlalchemy
# flask-wtf
flask-appbuilder==3.4.0
flask-appbuilder==3.4.1rc2
# via apache-superset
flask-babel==1.0.0
# via flask-appbuilder
Expand Down
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def get_git_sha() -> str:
"cryptography>=3.3.2",
"deprecation>=2.1.0, <2.2.0",
"flask>=1.1.0, <2.0.0",
"flask-appbuilder>=3.4.0, <4.0.0",
"flask-appbuilder>=3.4.1rc2, <4.0.0",
"flask-caching>=1.10.0",
"flask-compress",
"flask-talisman",
Expand Down Expand Up @@ -109,7 +109,8 @@ def get_git_sha() -> str:
"sqlalchemy-utils>=0.37.8, <0.38",
"sqlparse==0.3.0", # PINNED! see https://github.com/andialbrecht/sqlparse/issues/562
"tabulate==0.8.9",
"typing-extensions>=3.10, <4", # needed to support Literal (3.8) and TypeGuard (3.10)
# needed to support Literal (3.8) and TypeGuard (3.10)
"typing-extensions>=3.10, <4",
"wtforms-json",
],
extras_require={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,32 @@
import callApi from './callApi';
import rejectAfterTimeout from './rejectAfterTimeout';
import parseResponse from './parseResponse';
import { CallApi, ClientTimeout, ParseMethod } from '../types';
import { CallApi, ClientTimeout, ParseMethod, Url } from '../types';

function redirectUnauthorized(redirectUrl: Url) {
// the next param will be picked by flask to redirect the user after the login
window.location.href = `${redirectUrl}?next=${window.location.href}`;
}

export default async function callApiAndParseWithTimeout<
T extends ParseMethod = 'json',
>({
timeout,
parseMethod,
unauthorizedRedirectUrl = '/login',
...rest
}: { timeout?: ClientTimeout; parseMethod?: T } & CallApi) {
const apiPromise = callApi(rest);
const racedPromise =
typeof timeout === 'number' && timeout > 0
? Promise.race([apiPromise, rejectAfterTimeout<Response>(timeout)])
: apiPromise;
const response = await racedPromise;
const parsedResponse = parseResponse(response, parseMethod);

if (response && response.status === 401) {
redirectUnauthorized(unauthorizedRedirectUrl);
}

return parseResponse(racedPromise, parseMethod);
return parsedResponse;
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,14 @@

import { ParseMethod, TextResponse, JsonResponse } from '../types';

function isPromise(
apiRequest: Response | Promise<Response>,
): apiRequest is Promise<Response> {
return (apiRequest as Promise<Response>).finally !== undefined;
}

export default async function parseResponse<T extends ParseMethod = 'json'>(
apiPromise: Promise<Response>,
apiRequest: Response | Promise<Response>,
parseMethod?: T,
) {
type ReturnType = T extends 'raw' | null
Expand All @@ -30,7 +36,8 @@ export default async function parseResponse<T extends ParseMethod = 'json'>(
: T extends 'text'
? TextResponse
: never;
const response = await apiPromise;

const response = isPromise(apiRequest) ? await apiRequest : apiRequest;
geido marked this conversation as resolved.
Show resolved Hide resolved
// reject failed HTTP requests with the raw response
if (!response.ok) {
return Promise.reject(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export interface CallApi extends RequestBase {
url: Url;
cache?: Cache;
redirect?: Redirect;
unauthorizedRedirectUrl?: Url;
}

export interface RequestWithEndpoint extends RequestBase {
Expand Down
2 changes: 2 additions & 0 deletions superset/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,8 @@ def _try_json_readsha(filepath: str, length: int) -> Optional[str]:
# { 'name': 'Yahoo', 'url': 'https://open.login.yahoo.com/' },
# { 'name': 'Flickr', 'url': 'https://www.flickr.com/<username>' },

AUTH_STRICT_RESPONSE_CODES = True

# ---------------------------------------------------
# Roles config
# ---------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion tests/integration_tests/databases/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1141,7 +1141,7 @@ def test_export_database_not_allowed(self):
argument = [database.id]
uri = f"api/v1/database/export/?q={prison.dumps(argument)}"
rv = self.client.get(uri)
assert rv.status_code == 401
assert rv.status_code == 403

def test_export_database_non_existing(self):
"""
Expand Down
12 changes: 6 additions & 6 deletions tests/integration_tests/datasets/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ def test_create_dataset_item_gamma(self):
}
uri = "api/v1/dataset/"
rv = self.client.post(uri, json=table_data)
assert rv.status_code == 401
assert rv.status_code == 403

def test_create_dataset_item_owner(self):
"""
Expand Down Expand Up @@ -986,7 +986,7 @@ def test_update_dataset_item_gamma(self):
table_data = {"description": "changed_description"}
uri = f"api/v1/dataset/{dataset.id}"
rv = self.client.put(uri, json=table_data)
assert rv.status_code == 401
assert rv.status_code == 403
db.session.delete(dataset)
db.session.commit()

Expand Down Expand Up @@ -1094,7 +1094,7 @@ def test_delete_dataset_item_not_authorized(self):
self.login(username="gamma")
uri = f"api/v1/dataset/{dataset.id}"
rv = self.client.delete(uri)
assert rv.status_code == 401
assert rv.status_code == 403
db.session.delete(dataset)
db.session.commit()

Expand Down Expand Up @@ -1313,7 +1313,7 @@ def test_bulk_delete_dataset_item_not_authorized(self):
self.login(username="gamma")
uri = f"api/v1/dataset/?q={prison.dumps(dataset_ids)}"
rv = self.client.delete(uri)
assert rv.status_code == 401
assert rv.status_code == 403

@pytest.mark.usefixtures("create_datasets")
def test_bulk_delete_dataset_item_incorrect(self):
Expand Down Expand Up @@ -1438,7 +1438,7 @@ def test_export_dataset_gamma(self):

self.login(username="gamma")
rv = self.client.get(uri)
assert rv.status_code == 401
assert rv.status_code == 403

perm1 = security_manager.find_permission_view_menu("can_export", "Dataset")

Expand Down Expand Up @@ -1516,7 +1516,7 @@ def test_export_dataset_bundle_gamma(self):
self.login(username="gamma")
rv = self.client.get(uri)
# gamma users by default do not have access to this dataset
assert rv.status_code == 401
assert rv.status_code == 403

@unittest.skip("Number of related objects depend on DB")
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
Expand Down
4 changes: 2 additions & 2 deletions tests/integration_tests/log_api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ def test_get_list_not_allowed(self):
self.login(username="gamma")
uri = "api/v1/log/"
rv = self.client.get(uri)
self.assertEqual(rv.status_code, 401)
self.assertEqual(rv.status_code, 403)
self.login(username="alpha")
rv = self.client.get(uri)
self.assertEqual(rv.status_code, 401)
self.assertEqual(rv.status_code, 403)

def test_get_item(self):
"""
Expand Down