Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor: use state param instead of session storage (#6657)

Liu Ji7938b06cb80c
diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.ts
index 34e988eaf1..56b9621c8e 100644
--- a/frontend/src/types/oauth.ts
+++ b/frontend/src/types/oauth.ts
@@ -1,3 +1,4 @@
+import { stringify } from "qs";
import {
ExternalVersionControl_Type,
externalVersionControl_TypeToJSON,
@@ -9,7 +10,6 @@ export type OAuthWindowEventPayload = {
error: string;
code: string;
};
-
export function redirectUrl(): string {
return `${window.location.origin}/oauth/callback`;
}
@@ -23,45 +23,58 @@ export type OAuthType =
| "bb.oauth.link-vcs-repository"
| "bb.oauth.unknown";
+export type OAuthState = {
+ event: string;
+ popup?: boolean;
+ redirect?: string;
+};
+
export function openWindowForOAuth(
endpoint: string,
applicationId: string,
type: OAuthType,
vcsType: ExternalVersionControl_Type
): Window | null {
- // we use type to determine oauth type when receiving the callback
- const stateQueryParameter = `${type}.${externalVersionControl_TypeToJSON(
- vcsType
- )}-${applicationId}`;
- sessionStorage.setItem(OAuthStateSessionKey, stateQueryParameter);
+ const state: OAuthState = {
+ // we use type to determine oauth type when receiving the callback
+ event: `${type}.${externalVersionControl_TypeToJSON(
+ vcsType
+ )}-${applicationId}`,
+ popup: true,
+ };
+
+ const endpointQueryParams: Record<string, string> = {
+ client_id: applicationId,
+ state: stringify(state),
+ response_type: "code",
+ redirect_uri: redirectUrl(),
+ };
+
+ // Set proper popup window size for different VCS types
+ let windowOpenOptions = "";
if (vcsType == ExternalVersionControl_Type.GITHUB) {
// GitHub OAuth App scopes: https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps
// We need the workflow scope to update GitHub action files.
- return window.open(
- `${endpoint}?client_id=${applicationId}&redirect_uri=${encodeURIComponent(
- redirectUrl()
- )}&state=${stateQueryParameter}&response_type=code&scope=api,repo,workflow`,
- "oauth",
- "location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes"
- );
+
+ endpointQueryParams["scope"] = "api,repo,workflow";
+ windowOpenOptions =
+ "location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes";
} else if (vcsType == ExternalVersionControl_Type.BITBUCKET) {
// Bitbucket OAuth App scopes: https://developer.atlassian.com/cloud/bitbucket/rest/intro/#authentication
- return window.open(
- `${endpoint}?client_id=${applicationId}&redirect_uri=${encodeURIComponent(
- redirectUrl()
- )}&state=${stateQueryParameter}&response_type=code&scope=account%20repository:write%20webhook`,
- "oauth",
- "location=yes,left=200,top=200,height=640,width=720,scrollbars=yes,status=yes"
- );
+ // Do not call `encodeURIComponent` here, will be encoded later.
+ endpointQueryParams["scope"] = "account repository:write webhook";
+ windowOpenOptions =
+ "location=yes,left=200,top=200,height=640,width=720,scrollbars=yes,status=yes";
+ } else {
+ // GITLAB
+ // GitLab OAuth App scopes: https://docs.gitlab.com/ee/integration/oauth_provider.html#authorized-applications
+ endpointQueryParams["scope"] = "api";
+ windowOpenOptions =
+ "location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes";
}
- // GITLAB
- // GitLab OAuth App scopes: https://docs.gitlab.com/ee/integration/oauth_provider.html#authorized-applications
- return window.open(
- `${endpoint}?client_id=${applicationId}&redirect_uri=${encodeURIComponent(
- redirectUrl()
- )}&state=${stateQueryParameter}&response_type=code&scope=api`,
- "oauth",
- "location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes"
- );
+
+ const fullEndpointURL = `${endpoint}?${stringify(endpointQueryParams)}`;
+
+ return window.open(fullEndpointURL, "oauth", windowOpenOptions);
}
diff --git a/frontend/src/utils/sso.ts b/frontend/src/utils/sso.ts
index 5bd7269884..2005d335ec 100644
--- a/frontend/src/utils/sso.ts
+++ b/frontend/src/utils/sso.ts
@@ -1,10 +1,12 @@
import axios from "axios";
import { trimEnd, uniq } from "lodash-es";
-import { OAuthStateSessionKey } from "@/types";
+import { stringify } from "qs";
+
import {
IdentityProvider,
IdentityProviderType,
} from "@/types/proto/v1/idp_service";
+import { OAuthState } from "@/types";
export const SSOConfigSessionKey = "sso-config";
@@ -13,36 +15,35 @@ const defaultOIDCScopes = ["openid", "profile", "email"];
export async function openWindowForSSO(
identityProvider: IdentityProvider,
- openAsPopup = true,
+ popup = true,
redirect = ""
) {
- const stateQueryParameter = `bb.oauth.signin.${identityProvider.name}`;
- sessionStorage.setItem(OAuthStateSessionKey, stateQueryParameter);
- // Set SSO config in session storage so that we can use it in the callback page.
- sessionStorage.setItem(
- SSOConfigSessionKey,
- JSON.stringify({
- identityProviderName: identityProvider.name,
- openAsPopup,
- redirect,
- })
- );
+ const state: OAuthState = {
+ // we use type to determine oauth type when receiving the callback
+ event: `bb.oauth.signin.${identityProvider.name}`,
+ popup,
+ redirect,
+ };
+
+ const uri = {
+ basePath: "",
+ query: {
+ state: stringify(state),
+ response_type: "code",
+ } as Record<string, string>,
+ };
- let authUrl = "";
if (identityProvider.type === IdentityProviderType.OAUTH2) {
const oauth2Config = identityProvider.config?.oauth2Config;
if (!oauth2Config) {
return null;
}
-
- const redirectUrl = encodeURIComponent(
- `${window.location.origin}/oauth/callback`
- );
- authUrl = `${oauth2Config.authUrl}?client_id=${
- oauth2Config.clientId
- }&redirect_uri=${redirectUrl}&state=${stateQueryParameter}&response_type=code&scope=${encodeURIComponent(
- oauth2Config.scopes.join(" ")
- )}`;
+ uri.basePath = oauth2Config.authUrl;
+ Object.assign(uri.query, {
+ client_id: oauth2Config.clientId,
+ scope: oauth2Config.scopes.join(" "),
+ redirect_uri: `${window.location.origin}/oauth/callback`,
+ });
} else if (identityProvider.type === IdentityProviderType.OIDC) {
const oidcConfig = identityProvider.config?.oidcConfig;
if (!oidcConfig) {
@@ -62,24 +63,25 @@ export async function openWindowForSSO(
}
oidcConfig.scopes = uniq([...oidcConfig.scopes, ...defaultOIDCScopes]);
- const redirectUrl = encodeURIComponent(
- `${window.location.origin}/oidc/callback`
- );
- authUrl = `${openidConfig.authorization_endpoint}?client_id=${
- oidcConfig.clientId
- }&redirect_uri=${redirectUrl}&state=${stateQueryParameter}&response_type=code&scope=${encodeURIComponent(
- oidcConfig.scopes.join(" ")
- )}`;
+ uri.basePath = openidConfig.authorization_endpoint;
+ Object.assign(uri.query, {
+ client_id: oidcConfig.clientId,
+ scope: oidcConfig.scopes.join(" "),
+ redirect_uri: `${window.location.origin}/oidc/callback`,
+ });
} else {
throw new Error(
`identity provider type ${identityProvider.type.toString()} is not supported`
);
}
+ const authUrl = `${uri.basePath}?${stringify(uri.query)}`;
+
if (!authUrl) {
throw new Error("Invalid authentication URL");
}
- if (openAsPopup) {
+
+ if (popup) {
window.open(
authUrl,
"oauth",
diff --git a/frontend/src/views/OAuthCallback.vue b/frontend/src/views/OAuthCallback.vue
index 4499547c50..ae0a5909d3 100644
--- a/frontend/src/views/OAuthCallback.vue
+++ b/frontend/src/views/OAuthCallback.vue
@@ -3,7 +3,7 @@
<div>{{ state.message }}</div>
<div v-if="state.hasError" class="mt-2">
<button
- v-if="state.openAsPopup"
+ v-if="state.oAuthState?.popup"
type="button"
class="btn-normal"
@click="window.close()"
@@ -18,26 +18,28 @@
</template>
<script lang="ts" setup>
-import { useAuthStore } from "@/store";
-import { SSOConfigSessionKey } from "@/utils/sso";
import { onMounted, reactive } from "vue";
-import { useRouter } from "vue-router";
-import { OAuthWindowEventPayload, OAuthStateSessionKey } from "../types";
+import { useRoute, useRouter } from "vue-router";
+import { parse } from "qs";
+
+import { useAuthStore } from "@/store";
+import { OAuthState, OAuthWindowEventPayload } from "../types";
interface LocalState {
message: string;
hasError: boolean;
- openAsPopup: boolean;
+ oAuthState: OAuthState | undefined;
payload: OAuthWindowEventPayload;
}
const router = useRouter();
+const route = useRoute();
const authStore = useAuthStore();
const state = reactive<LocalState>({
message: "",
hasError: false,
- openAsPopup: true,
+ oAuthState: undefined,
payload: {
error: "",
code: "",
@@ -45,21 +47,30 @@ const state = reactive<LocalState>({
});
onMounted(() => {
- const sessionState = sessionStorage.getItem(OAuthStateSessionKey);
- if (!sessionState || sessionState !== router.currentRoute.value.query.state) {
+ const queryState = parse((route.query.state as string) || "");
+
+ if (queryState.event) {
+ state.oAuthState = {
+ event: queryState.event as string,
+ popup: queryState.popup === "true" ? true : false,
+ redirect: (queryState.redirect as string) || "",
+ };
+ state.hasError = false;
+ state.message = "Successfully authorized. Redirecting back to Bytebase...";
+ state.payload.code = (route.query.code as string) || "";
+ } else {
state.hasError = true;
state.message =
"Failed to authorize. Invalid state passed to the oauth callback.";
- state.payload.error = state.message;
- } else {
- state.message = "Successfully authorized. Redirecting back to Bytebase...";
- state.payload.code = router.currentRoute.value.query.code as string;
+ state.oAuthState = undefined;
}
+
triggerAuthCallback();
});
const triggerAuthCallback = async () => {
- if (state.hasError) {
+ const { oAuthState, hasError } = state;
+ if (hasError || !oAuthState) {
window.opener.dispatchEvent(
new CustomEvent("bb.oauth.unknown", {
detail: state.payload,
@@ -68,13 +79,10 @@ const triggerAuthCallback = async () => {
return;
}
- const eventName = sessionStorage.getItem(OAuthStateSessionKey) || "";
+ const eventName = oAuthState.event;
const eventType = eventName.slice(0, eventName.lastIndexOf("."));
if (eventName.startsWith("bb.oauth.signin")) {
- const ssoConfig = JSON.parse(
- sessionStorage.getItem(SSOConfigSessionKey) || "{}"
- );
- if (ssoConfig.openAsPopup) {
+ if (oAuthState.popup) {
window.opener.dispatchEvent(
new CustomEvent(eventName, {
detail: state.payload,
@@ -83,7 +91,7 @@ const triggerAuthCallback = async () => {
window.close();
} else {
const mfaTempToken = await authStore.login({
- idpName: ssoConfig.identityProviderName,
+ idpName: eventName.split(".").pop()!,
idpContext: {
oauth2Context: {
code: state.payload.code,
@@ -91,17 +99,16 @@ const triggerAuthCallback = async () => {
},
web: true,
});
- state.openAsPopup = false;
if (mfaTempToken) {
router.push({
name: "auth.mfa",
query: {
mfaTempToken,
- redirect: ssoConfig.redirect || "",
+ redirect: oAuthState.redirect || "",
},
});
} else {
- router.push(ssoConfig.redirect || "/");
+ router.push(oAuthState.redirect || "/");
}
}
} else if (
diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vue
index 0b364f7347..b0de900f8b 100644
--- a/frontend/src/views/auth/Signin.vue
+++ b/frontend/src/views/auth/Signin.vue
@@ -229,7 +229,7 @@ const trySigninWithIdentityProvider = async (
) => {
await openWindowForSSO(
identityProvider,
- false,
+ false /* !popup */,
route.query.redirect as string
);
};