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

#6656 Partner refresh tokens #8650

Merged
merged 36 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
0e2061b
update api client architecture and add partner auth token refresh int…
Jun 19, 2024
8599674
add tests for refresh function
Jun 20, 2024
5b3cc37
Merge branch 'main' into feature/6656-partner-refresh-tokens-take-2
Jun 20, 2024
15e05f5
naming
Jun 20, 2024
4d56476
another test case + cleanup
Jun 20, 2024
dc0b8ec
fix tests
Jun 20, 2024
f461ae4
fix lint
Jun 20, 2024
006aec0
fixes and strict null checks cleanup
Jun 20, 2024
c41a05b
auto add strict null checks files
Jun 20, 2024
2cfbf06
fix required partner auth test
Jun 20, 2024
3e95961
fix error message in test
Jun 20, 2024
3d98c2a
strict null check the test file
Jun 20, 2024
c374008
remove expectContext check and add tests for launchAuthIntegration. A…
Jun 21, 2024
c6de227
cleanup
Jun 21, 2024
73298ee
fix gsheets tests
Jun 21, 2024
d79ab2c
fix lint and strict null checks
Jun 21, 2024
54bacf3
add file to strict null checks
Jun 21, 2024
820df01
remove unused factory
Jun 21, 2024
f304991
fix package-lock
Jun 21, 2024
841f65e
Merge branch 'main' into feature/6656-partner-refresh-tokens-take-2
Jun 21, 2024
65f3bc4
fix package-lock after merge
Jun 21, 2024
9f010de
remove deleted file
Jun 21, 2024
b60ea33
Merge branch 'main' into feature/6656-partner-refresh-tokens-take-2
Jun 21, 2024
89b5816
Merge branch 'main' into feature/6656-partner-refresh-tokens-take-2
Jun 24, 2024
2b90fb9
fix package lock
Jun 24, 2024
87fd635
revert new chrome api call because we can't test it
Jun 27, 2024
333ce91
Merge branch 'main' into feature/6656-partner-refresh-tokens-take-2
Jun 27, 2024
c368fe0
fix strict null checks, fix grant_type, fix logic around client_id
Jun 27, 2024
184251c
fix test
Jun 27, 2024
6727165
fix issue with storage being cleared when it doesn't need to be cleared
Jun 27, 2024
7ec0db8
Merge branch 'main' into feature/6656-partner-refresh-tokens-take-2
Jun 27, 2024
77d013b
use helper function
Jun 27, 2024
0f7bfbe
add test button and fix bugs
Jun 27, 2024
20fc5c5
fix weird storage logic and move chrome.identity function to the back…
Jun 27, 2024
276e999
fix tests
Jun 28, 2024
f1089fa
Merge branch 'main' into feature/6656-partner-refresh-tokens-take-2
Jun 28, 2024
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
7,714 changes: 2,806 additions & 4,908 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"ace-builds": "^1.34.2",
"autocompleter": "^9.2.1",
"axios": "^0.28.1",
"axios-auth-refresh": "^3.3.6",
"batched-function": "^2.0.1",
"bootstrap": "^4.6.0",
"bootstrap-icons": "^1.11.3",
Expand Down
65 changes: 42 additions & 23 deletions src/auth/authStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,17 @@ import {
} from "./authTypes";
import { isExtensionContext } from "webext-detect-page";
import { expectContext } from "@/utils/expectContext";
import { isEmpty, omit } from "lodash";
import { omit } from "lodash";
import { syncRemotePackages } from "@/registry/memoryRegistry";
import { StorageItem } from "webext-storage";
import { SimpleEventTarget } from "@/utils/SimpleEventTarget";
import { ReusableAbortController } from "abort-utils";
import chromeP from "webext-polyfill-kinda";

const extensionKeyStorage = new StorageItem("extensionKey", {
defaultValue: {} as Partial<TokenAuthData>,
});
const partnerTokenStorage = new StorageItem("partnerToken", {
defaultValue: {} as Partial<PartnerAuthData>,
});
const partnerTokenStorage = new StorageItem<PartnerAuthData>("partnerToken");

type AuthListener = (auth: Partial<TokenAuthData | PartnerAuthData>) => void;

Expand All @@ -48,11 +47,11 @@ const authChanges = new SimpleEventTarget<
>();

// Use listeners to allow inversion of control and avoid circular dependency with error reporter.
export function addListener(handler: AuthListener): void {
export function addAuthListener(handler: AuthListener): void {
authChanges.add(handler, { signal: controller.signal });
}

export function removeListener(handler: AuthListener): void {
export function removeAuthListener(handler: AuthListener): void {
authChanges.remove(handler);
}

Expand Down Expand Up @@ -93,17 +92,32 @@ export async function getExtensionToken(): Promise<string | undefined> {
return token;
}

export async function getPartnerAuthData(): Promise<Partial<PartnerAuthData>> {
return partnerTokenStorage.get();
export async function getPartnerAuthData(): Promise<
PartnerAuthData | undefined
> {
let isError = false;
let storageValue: PartnerAuthData | undefined;
try {
storageValue = await partnerTokenStorage.get();
} catch {
isError = true;
}

// Backwards compatibility with old, looser type
if (isError || !storageValue?.authId || !storageValue?.token) {
await clearPartnerAuthData();
return undefined;
}

return storageValue;
}

/**
* Set authentication data when using the partner JWT to authenticate.
*
* @see clearPartnerAuth
*/
export async function setPartnerAuthData(data: PartnerAuthData): Promise<void> {
if (!isEmpty(data.authId) && isEmpty(data.token)) {
// Backwards compatibility with old, looser type
if (data.token == null) {
// Should use clearPartnerAuth for clearing the partner integration JWT
throw new Error("Received null/blank token for partner integration");
}
Expand All @@ -112,12 +126,23 @@ export async function setPartnerAuthData(data: PartnerAuthData): Promise<void> {
}

/**
* Clear authentication data when using the partner JWT to authenticate.
*
* @see setPartnerAuthData
* Clear all partner OAuth2 tokens and reset api query caches
*/
export async function clearPartnerAuth(): Promise<void> {
return partnerTokenStorage.set({});
export async function clearPartnerAuthData(): Promise<void> {
// // https://developer.chrome.com/docs/extensions/reference/identity/#method-clearAllCachedAuthTokens
// await chromeP.identity.clearAllCachedAuthTokens();
BLoe marked this conversation as resolved.
Show resolved Hide resolved

const partnerAuthData = await partnerTokenStorage.get();
if (partnerAuthData?.token) {
console.debug(
"Clearing partner auth for authId: " + partnerAuthData.authId,
);
await chromeP.identity.removeCachedAuthToken({
token: partnerAuthData.token,
});
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I need to test this some more to make sure it works properly, but I think we might be able to get away with only clearing the partner token from the identity cache, so that other oauth2 sessions are not invalidated also, like a gsuite login for ex.


await partnerTokenStorage.remove();
}

/**
Expand All @@ -139,7 +164,7 @@ export async function getAuthHeaders(): Promise<UnknownObject | null> {
};
}

if (partnerAuth?.token) {
if (partnerAuth) {
return {
...partnerAuth.extraHeaders,
// Put Authorization second to avoid overriding Authorization header. (Is defensive for now, currently
Expand All @@ -153,12 +178,6 @@ export async function getAuthHeaders(): Promise<UnknownObject | null> {

/**
* Return `true` if the extension is linked to the API. I.e., that the user is "logged in".
*
* NOTE: do not use this as a check before making an authenticated API call. Instead, use `maybeGetLinkedApiClient`
* which avoids a race condition between the time the check is made and underlying `getExtensionToken` call to get
* the token.
*
* @see maybeGetLinkedApiClient
*/
export async function isLinked(): Promise<boolean> {
return (await getAuthHeaders()) != null;
Expand Down
20 changes: 17 additions & 3 deletions src/auth/authTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,21 +117,35 @@ export type PartnerAuthData = {
/**
* The service auth configuration for authenticating with the PixieBrix API.
*/
authId: UUID | null;
authId: UUID;
/**
* The JWT bearer token corresponding to the authId.
*/
token: string | null;
token: string;
/**
* The refresh token, if `offline_access` was included in scope.
* @since 1.7.15
*/
refreshToken: string | null;

/**
* Extra HTTP headers to send with every request.
*/
extraHeaders: Record<string, string> | null;

/**
* The refresh request URL
* @since 2.0.3
*/
refreshUrl: string | null;
/**
* The refresh request param payload
* @since 2.0.3
*/
refreshParamPayload: Record<string, string> | null;
/**
* The refresh request extra headers
*/
refreshExtraHeaders: Record<string, string> | null;
};

export type OrganizationAuthState = {
Expand Down
2 changes: 1 addition & 1 deletion src/auth/featureFlagStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { CachedFunction } from "webext-storage-cache";
import { expectContext } from "@/utils/expectContext";
import { fetchFeatureFlagsInBackground } from "@/background/messenger/api";
import { getMe } from "@/data/service/backgroundApi";
import { addListener as addAuthStorageListener } from "@/auth/authStorage";
import { addAuthListener as addAuthStorageListener } from "@/auth/authStorage";

/**
* Fetch the latest feature flags from the server.
Expand Down
48 changes: 48 additions & 0 deletions src/auth/isAuthenticationAxiosError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*

Check failure on line 1 in src/auth/isAuthenticationAxiosError.ts

View workflow job for this annotation

GitHub Actions / strictNullChecks

strictNullChecks

src/auth/isAuthenticationAxiosError.ts was not found in tsconfig.strictNullChecks.json
* Copyright (C) 2024 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import type { AxiosError } from "axios";
import { isObject } from "@/utils/objectUtils";

const UNAUTHORIZED_STATUS_CODES = new Set([401, 403]);

export function isAuthenticationAxiosError(
error: Pick<AxiosError, "response">,
): boolean {
// Response should be an object
if (!isObject(error.response)) {
return false;
}

// Technically 403 is an authorization error and re-authenticating as the same user won't help. However, there is
// a case where the user just needs an updated JWT that contains the most up-to-date entitlements
if (UNAUTHORIZED_STATUS_CODES.has(error.response.status)) {
return true;
}

// Handle Automation Anywhere's Control Room expired JWT response. They'll return this from any endpoint instead
// of a proper error code.
if (
error.response.status === 400 &&
isObject(error.response.data) &&
error.response.data.message === "Access Token has expired"
) {
return true;
}

return false;
}
4 changes: 2 additions & 2 deletions src/auth/useLinkState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
*/

import {
addListener as addAuthListener,
removeListener as removeAuthListener,
addAuthListener,
removeAuthListener,
isLinked,
} from "@/auth/authStorage";
import useAsyncExternalStore from "@/hooks/useAsyncExternalStore";
Expand Down
4 changes: 2 additions & 2 deletions src/auth/usePartnerAuthData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
*/

import {
addListener as addAuthListener,
addAuthListener,
getPartnerAuthData,
removeListener as removeAuthListener,
removeAuthListener,
} from "@/auth/authStorage";
import useAsyncExternalStore from "@/hooks/useAsyncExternalStore";
import type { AsyncState } from "@/types/sliceTypes";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*

Check failure on line 1 in src/background/auth/partnerIntegrations/launchAuthIntegration.test.ts

View workflow job for this annotation

GitHub Actions / strictNullChecks

strictNullChecks

src/background/auth/partnerIntegrations/launchAuthIntegration.test.ts was not found in tsconfig.strictNullChecks.json
* Copyright (C) 2024 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { registry } from "@/background/messenger/api";
import oauth2IntegrationDefinition from "@contrib/integrations/automation-anywhere-oauth2.yaml";

jest.mocked(registry.find).mockResolvedValue({
id: (oauth2IntegrationDefinition!.metadata as any).id,
config: oauth2IntegrationDefinition,
} as any);

describe("launchAuthIntegration", () => {
it("throws error if no local auths are found", async () => {});
});
Loading
Loading