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 all 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
6 changes: 3 additions & 3 deletions .secrets.baseline
Original file line number Diff line number Diff line change
Expand Up @@ -253,16 +253,16 @@
"filename": "src/testUtils/factories/authFactories.ts",
"hashed_secret": "d15e5a27160ace913d22871497c05a7e5bbbe2ef",
"is_verified": false,
"line_number": 157
"line_number": 158
},
{
"type": "Hex High Entropy String",
"filename": "src/testUtils/factories/authFactories.ts",
"hashed_secret": "ff998abc1ce6d8f01a675fa197368e44c8916e9c",
"is_verified": false,
"line_number": 172
"line_number": 173
}
]
},
"generated_at": "2024-06-11T00:08:01Z"
"generated_at": "2024-06-20T16:25:50Z"
}
1 change: 0 additions & 1 deletion eslint-local-rules/persistBackgroundData.txt
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,6 @@
./src/starterBricks/factory.ts
./src/starterBricks/helpers.ts
./src/starterBricks/menuItemExtension.ts
./src/starterBricks/panelExtension.ts
./src/starterBricks/quickBarExtension.tsx
./src/starterBricks/quickBarProviderExtension.tsx
./src/starterBricks/quickbarQueryReader.ts
Expand Down
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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.35.0",
"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
2 changes: 2 additions & 0 deletions src/__mocks__/@/background/messenger/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,5 @@ export const performConfiguredRequestInBackground = getMethod(
) => Promise<RemoteResponse<TData>>;

export const clearServiceCache = jest.fn();

export const removeOAuth2Token = jest.fn();
62 changes: 39 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 { removeOAuth2Token } from "@/background/messenger/api";

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,29 @@ 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
> {
const storageValue = await partnerTokenStorage.get();
if (storageValue == null) {
return undefined;
}

// Backwards compatibility with old, looser type -- just clear the bad data and let the user log in again
if (!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 +123,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> {
// Old code that clears all cached auth tokens
// There is an issue with this api in Edge: https://github.com/w3c/webextensions/issues/648
// See: https://developer.chrome.com/docs/extensions/reference/identity/#method-clearAllCachedAuthTokens
// await chromeP.identity.clearAllCachedAuthTokens();

const partnerAuthData = await partnerTokenStorage.get();
if (partnerAuthData?.token) {
console.debug(
"Clearing partner auth for authId: " + partnerAuthData.authId,
);
await removeOAuth2Token(partnerAuthData.token);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Maybe leave a comment as to why we want this instead of clearAllCachedAuthTokens which we used previously

}

await partnerTokenStorage.remove();
}

/**
Expand All @@ -139,7 +161,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 +175,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 @@
/*
* 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
6 changes: 3 additions & 3 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 All @@ -38,7 +38,7 @@ const subscribe = (callback: () => void) => {
* Use the current partner auth data. Automatically listens for changes and updates the state.
* @see getPartnerAuthData
*/
function usePartnerAuthData(): AsyncState<Partial<PartnerAuthData>> {
function usePartnerAuthData(): AsyncState<PartnerAuthData | undefined> {
return useAsyncExternalStore(subscribe, getPartnerAuthData);
}

Expand Down
7 changes: 3 additions & 4 deletions src/auth/useRequiredPartnerAuth.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ import {
mockAuthenticatedMeApiResponse,
} from "@/testUtils/userMock";
import {
meWithPartnerApiResponseFactory,
meApiResponseFactory,
meOrganizationApiResponseFactory,
meWithPartnerApiResponseFactory,
partnerAuthDataFactory,
} from "@/testUtils/factories/authFactories";
import { renderHook } from "@/pageEditor/testHelpers";
import { integrationConfigFactory } from "@/testUtils/factories/integrationFactories";
Expand Down Expand Up @@ -188,9 +189,7 @@ describe("useRequiredPartnerAuth", () => {

test("has required partner integration", async () => {
usePartnerAuthDataMock.mockReturnValue(
valueToAsyncState({
token: "NOTAREALTOKEN",
}),
valueToAsyncState(partnerAuthDataFactory()),
);

await mockAuthenticatedMeApiResponse(
Expand Down
5 changes: 5 additions & 0 deletions src/background/auth/authStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { type UUID } from "@/types/stringTypes";
import { expectContext } from "@/utils/expectContext";
import { type AuthData } from "@/integrations/integrationTypes";
import { oauth2Storage } from "@/auth/authConstants";
import chromeP from "webext-polyfill-kinda";

/**
* Set the cached auth data for the given integration configId
Expand Down Expand Up @@ -94,3 +95,7 @@ export async function deleteCachedAuthData(configId: UUID): Promise<void> {
);
}
}

export async function removeOAuth2Token(token: string) {
await chromeP.identity.removeCachedAuthToken({ token });
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ import {
CONTROL_ROOM_OAUTH_INTEGRATION_ID,
CONTROL_ROOM_TOKEN_INTEGRATION_ID,
} from "@/integrations/constants";
import { readRawConfigurations } from "@/integrations/registry";
import { registry } from "@/background/messenger/api";
import { type RegistryId } from "@/types/registryTypes";
import { readRawConfigurations } from "@/integrations/util/readRawConfigurations";

jest.mock("@/integrations/registry", () => {
const actual = jest.requireActual("@/integrations/registry");
Expand All @@ -57,6 +57,7 @@ jest.mocked(registry.find).mockImplementation(async (id: RegistryId) => {
} as any;
});

jest.mock("@/integrations/util/readRawConfigurations");
const readRawConfigurationsMock = jest.mocked(readRawConfigurations);

describe("getPartnerPrincipals", () => {
Expand Down
Loading
Loading