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

Automatically use user token when sharing token is not sufficient for a request #8139

Merged
merged 16 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions CHANGELOG.unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ For upgrade instructions, please check the [migration guide](MIGRATIONS.released

### Fixed
- Fixed a bug during dataset upload in case the configured `datastore.baseFolder` is an absolute path. [#8098](https://github.com/scalableminds/webknossos/pull/8098) [#8103](https://github.com/scalableminds/webknossos/pull/8103)
- When trying to save an annotation opened via a link including a sharing token, the token is automatically discarded in case it is insufficient for update actions but the users token is. [#8139](https://github.com/scalableminds/webknossos/pull/8139)
- Fixed that the skeleton search did not automatically expand groups that contained the selected tree [#8129](https://github.com/scalableminds/webknossos/pull/8129)
- Fixed a bug that zarr streaming version 3 returned the shape of mag (1, 1, 1) / the finest mag for all mags. [#8116](https://github.com/scalableminds/webknossos/pull/8116)
- Fixed sorting of mags in outbound zarr streaming. [#8125](https://github.com/scalableminds/webknossos/pull/8125)
Expand Down
2 changes: 1 addition & 1 deletion frontend/javascripts/admin/admin_rest_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2035,7 +2035,7 @@ export function computeAdHocMesh(
},
},
);
const neighbors = Utils.parseMaybe(headers.neighbors) || [];
const neighbors = (Utils.parseMaybe(headers.neighbors) as number[] | null) || [];
return {
buffer,
neighbors,
Expand Down
35 changes: 26 additions & 9 deletions frontend/javascripts/admin/api/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { location } from "libs/window";
import Request from "libs/request";
import * as Utils from "libs/utils";

const MAX_TOKEN_RETRY_ATTEMPTS = 3;

let tokenPromise: Promise<string>;

let tokenRequestPromise: Promise<string> | null;
let shouldUseURLToken: boolean = true;
MichaelBuessemeyer marked this conversation as resolved.
Show resolved Hide resolved
Comment on lines +5 to +10
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Consider thread-safe state management for token source.

While the constant MAX_TOKEN_RETRY_ATTEMPTS is a good addition, the mutable shouldUseURLToken flag could lead to race conditions in concurrent requests. Consider using a more thread-safe approach:

-let shouldUseURLToken: boolean = true;
+class TokenSourceManager {
+  private static instance: TokenSourceManager;
+  private useURLToken: boolean = true;
+  
+  private constructor() {}
+  
+  static getInstance(): TokenSourceManager {
+    if (!TokenSourceManager.instance) {
+      TokenSourceManager.instance = new TokenSourceManager();
+    }
+    return TokenSourceManager.instance;
+  }
+
+  shouldUseURLToken(): boolean {
+    return this.useURLToken;
+  }
+
+  disableURLToken(): void {
+    this.useURLToken = false;
+  }
+}

Committable suggestion was skipped due to low confidence.


function requestUserToken(): Promise<string> {
if (tokenRequestPromise) {
Expand Down Expand Up @@ -33,22 +36,36 @@ export function getSharingTokenFromUrlParameters(): string | null | undefined {
return null;
}

export function doWithToken<T>(fn: (token: string) => Promise<T>, tries: number = 1): Promise<any> {
const sharingToken = getSharingTokenFromUrlParameters();
export async function doWithToken<T>(
fn: (token: string) => Promise<T>,
tries: number = 1,
useURLTokenIfAvailable: boolean = true,
): Promise<T> {
let token =
useURLTokenIfAvailable && shouldUseURLToken ? getSharingTokenFromUrlParameters() : null;

if (sharingToken != null) {
return fn(sharingToken);
if (token == null) {
tokenPromise = tokenPromise == null ? requestUserToken() : tokenPromise;
} else {
tokenPromise = Promise.resolve(token);
}

if (!tokenPromise) tokenPromise = requestUserToken();
return tokenPromise.then(fn).catch((error) => {
return tokenPromise.then(fn).catch(async (error) => {
if (error.status === 403) {
console.warn("Token expired. Requesting new token...");
console.warn(
`Token expired (attempt ${tries}/${MAX_TOKEN_RETRY_ATTEMPTS}). Requesting new token...`,
);
tokenPromise = requestUserToken();

// If three new tokens did not fix the 403, abort, otherwise we'll get into an endless loop here
if (tries < 3) {
return doWithToken(fn, tries + 1);
if (tries < MAX_TOKEN_RETRY_ATTEMPTS) {
// If using the url sharing token failed, we try the user specific token instead.
const result = await doWithToken(fn, tries + 1, false);
// Upon successful retry with own token, discard the url token.
if (useURLTokenIfAvailable) {
shouldUseURLToken = false;
}
return result;
Comment on lines +53 to +68
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance error handling and logging for better debuggability.

While the retry logic is sound, the error handling and logging could be more comprehensive to aid debugging.

 return tokenPromise.then(fn).catch(async (error) => {
   if (error.status === 403) {
     console.warn(
       `Token expired (attempt ${tries}/${MAX_TOKEN_RETRY_ATTEMPTS}). Requesting new token...`,
     );
     tokenPromise = requestUserToken();

     if (tries < MAX_TOKEN_RETRY_ATTEMPTS) {
       const result = await doWithToken(fn, tries + 1, false);
       if (useURLTokenIfAvailable) {
+        console.debug(
+          "Request succeeded with user token, disabling URL token for future requests"
+        );
         shouldUseURLToken = false;
       }
       return result;
     }
+  } else {
+    console.error(
+      "Request failed with non-403 error:",
+      error.status,
+      error.message
+    );
   }

   throw error;
 });

Also consider adding error context to help diagnose issues:

-throw error;
+const enhancedError = new Error(
+  `Request failed after ${tries} attempts: ${error.message}`
+);
+enhancedError.cause = error;
+throw enhancedError;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return tokenPromise.then(fn).catch(async (error) => {
if (error.status === 403) {
console.warn("Token expired. Requesting new token...");
console.warn(
`Token expired (attempt ${tries}/${MAX_TOKEN_RETRY_ATTEMPTS}). Requesting new token...`,
);
tokenPromise = requestUserToken();
// If three new tokens did not fix the 403, abort, otherwise we'll get into an endless loop here
if (tries < 3) {
return doWithToken(fn, tries + 1);
if (tries < MAX_TOKEN_RETRY_ATTEMPTS) {
// If using the url sharing token failed, we try the user specific token instead.
const result = await doWithToken(fn, tries + 1, false);
// Upon successful retry with own token, discard the url token.
if (useURLTokenIfAvailable) {
shouldUseURLToken = false;
}
return result;
return tokenPromise.then(fn).catch(async (error) => {
if (error.status === 403) {
console.warn(
`Token expired (attempt ${tries}/${MAX_TOKEN_RETRY_ATTEMPTS}). Requesting new token...`,
);
tokenPromise = requestUserToken();
// If three new tokens did not fix the 403, abort, otherwise we'll get into an endless loop here
if (tries < MAX_TOKEN_RETRY_ATTEMPTS) {
// If using the url sharing token failed, we try the user specific token instead.
const result = await doWithToken(fn, tries + 1, false);
// Upon successful retry with own token, discard the url token.
if (useURLTokenIfAvailable) {
console.debug(
"Request succeeded with user token, disabling URL token for future requests"
);
shouldUseURLToken = false;
}
return result;
}
} else {
console.error(
"Request failed with non-403 error:",
error.status,
error.message
);
}
const enhancedError = new Error(
`Request failed after ${tries} attempts: ${error.message}`
);
enhancedError.cause = error;
throw enhancedError;

}
}

Expand Down
12 changes: 10 additions & 2 deletions frontend/javascripts/libs/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,15 +311,23 @@ class Request {
...message,
key: json.status.toString(),
}));
if (showErrorToast) Toast.messages(messages);
if (showErrorToast) {
Toast.messages(messages); // Note: Toast.error internally logs to console
} else {
console.error(messages);
}
// Check whether the error chain mentions an url which belongs
// to a datastore. Then, ping the datastore
pingMentionedDataStores(text);

/* eslint-disable-next-line prefer-promise-reject-errors */
return Promise.reject({ ...json, url: requestedUrl });
} catch (_jsonError) {
if (showErrorToast) Toast.error(text);
if (showErrorToast) {
Toast.error(text); // Note: Toast.error internally logs to console
} else {
console.error(`Request failed for ${requestedUrl}:`, text);
}

/* eslint-disable-next-line prefer-promise-reject-errors */
return Promise.reject({
Expand Down
3 changes: 3 additions & 0 deletions frontend/javascripts/oxalis/model/sagas/save_saga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ export function* sendRequestToServer(
method: "POST",
data: compactedSaveQueue,
compress: process.env.NODE_ENV === "production",
// Suppressing error toast, as the doWithToken retry with personal token functionality should not show an error.
// Instead the error is logged and toggleErrorHighlighting should take care of showing an error to the user.
showErrorToast: false,
},
);
const endTime = Date.now();
Expand Down
3 changes: 3 additions & 0 deletions frontend/javascripts/test/sagas/save_saga.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ test("SaveSaga should send request to server", (t) => {
method: "POST",
data: saveQueueWithVersions,
compress: false,
showErrorToast: false,
}),
);
});
Expand All @@ -147,6 +148,7 @@ test("SaveSaga should retry update actions", (t) => {
method: "POST",
data: saveQueueWithVersions,
compress: false,
showErrorToast: false,
},
);
const saga = sendRequestToServer(TRACING_TYPE, tracingId);
Expand Down Expand Up @@ -187,6 +189,7 @@ test("SaveSaga should escalate on permanent client error update actions", (t) =>
method: "POST",
data: saveQueueWithVersions,
compress: false,
showErrorToast: false,
}),
);
saga.throw({
Expand Down