Run format

This commit is contained in:
Senthamil Sindhu 2024-06-25 09:59:21 -07:00
parent d3fb5eabdb
commit a50108c375
4 changed files with 146 additions and 118 deletions

View File

@ -20,10 +20,11 @@ export const tokenProvider = async (requestInfo: Cosmos.RequestInfo) => {
const { verb, resourceId, resourceType, headers } = requestInfo; const { verb, resourceId, resourceType, headers } = requestInfo;
if (userContext.features.enableAadDataPlane || (userContext.dataPlaneRbacEnabled && userContext.apiType === "SQL")) { if (userContext.features.enableAadDataPlane || (userContext.dataPlaneRbacEnabled && userContext.apiType === "SQL")) {
if(!userContext.aadToken) if (!userContext.aadToken) {
{ logConsoleError(
logConsoleError(`AAD token does not exist. Please use "Login for Entra ID" prior to performing Entra ID RBAC operations`); `AAD token does not exist. Please use "Login for Entra ID" prior to performing Entra ID RBAC operations`,
return; );
return null;
} }
const AUTH_PREFIX = `type=aad&ver=1.0&sig=`; const AUTH_PREFIX = `type=aad&ver=1.0&sig=`;
const authorizationToken = `${AUTH_PREFIX}${userContext.aadToken}`; const authorizationToken = `${AUTH_PREFIX}${userContext.aadToken}`;
@ -79,19 +80,29 @@ export const tokenProvider = async (requestInfo: Cosmos.RequestInfo) => {
if (userContext.masterKey) { if (userContext.masterKey) {
// TODO This SDK method mutates the headers object. Find a better one or fix the SDK. // TODO This SDK method mutates the headers object. Find a better one or fix the SDK.
await Cosmos.setAuthorizationTokenHeaderUsingMasterKey(verb, resourceId, resourceType, headers, userContext.masterKey); await Cosmos.setAuthorizationTokenHeaderUsingMasterKey(
verb,
resourceId,
resourceType,
headers,
userContext.masterKey,
);
return decodeURIComponent(headers.authorization); return decodeURIComponent(headers.authorization);
} } else {
else
{
const { databaseAccount: account, subscriptionId, resourceGroup } = userContext; const { databaseAccount: account, subscriptionId, resourceGroup } = userContext;
const keys: DatabaseAccountListKeysResult = await listKeys(subscriptionId, resourceGroup, account.name); const keys: DatabaseAccountListKeysResult = await listKeys(subscriptionId, resourceGroup, account.name);
if(keys.primaryMasterKey) { if (keys.primaryMasterKey) {
updateUserContext ({ masterKey: keys.primaryMasterKey}); updateUserContext({ masterKey: keys.primaryMasterKey });
// TODO This SDK method mutates the headers object. Find a better one or fix the SDK. // TODO This SDK method mutates the headers object. Find a better one or fix the SDK.
await Cosmos.setAuthorizationTokenHeaderUsingMasterKey(verb, resourceId, resourceType, headers, keys.primaryMasterKey); await Cosmos.setAuthorizationTokenHeaderUsingMasterKey(
return decodeURIComponent(headers.authorization); verb,
resourceId,
resourceType,
headers,
keys.primaryMasterKey,
);
return decodeURIComponent(headers.authorization);
} }
} }

View File

@ -38,11 +38,11 @@ import { stringToBlob } from "../Utils/BlobUtils";
import { isCapabilityEnabled } from "../Utils/CapabilityUtils"; import { isCapabilityEnabled } from "../Utils/CapabilityUtils";
import { fromContentUri, toRawContentUri } from "../Utils/GitHubUtils"; import { fromContentUri, toRawContentUri } from "../Utils/GitHubUtils";
import * as NotificationConsoleUtils from "../Utils/NotificationConsoleUtils"; import * as NotificationConsoleUtils from "../Utils/NotificationConsoleUtils";
import { logConsoleError, logConsoleInfo } from "../Utils/NotificationConsoleUtils"; import { logConsoleError, logConsoleInfo, logConsoleProgress } from "../Utils/NotificationConsoleUtils";
import { useSidePanel } from "../hooks/useSidePanel"; import { useSidePanel } from "../hooks/useSidePanel";
import { useTabs } from "../hooks/useTabs"; import { useTabs } from "../hooks/useTabs";
import "./ComponentRegisterer"; import "./ComponentRegisterer";
import { useDialog } from "./Controls/Dialog"; import { DialogProps, useDialog } from "./Controls/Dialog";
import { GalleryTab as GalleryTabKind } from "./Controls/NotebookGallery/GalleryViewerComponent"; import { GalleryTab as GalleryTabKind } from "./Controls/NotebookGallery/GalleryViewerComponent";
import { useCommandBar } from "./Menus/CommandBar/CommandBarComponentAdapter"; import { useCommandBar } from "./Menus/CommandBar/CommandBarComponentAdapter";
import * as FileSystemUtil from "./Notebook/FileSystemUtil"; import * as FileSystemUtil from "./Notebook/FileSystemUtil";
@ -67,6 +67,7 @@ import { ResourceTreeAdapter } from "./Tree/ResourceTreeAdapter";
import StoredProcedure from "./Tree/StoredProcedure"; import StoredProcedure from "./Tree/StoredProcedure";
import { useDatabases } from "./useDatabases"; import { useDatabases } from "./useDatabases";
import { useSelectedNode } from "./useSelectedNode"; import { useSelectedNode } from "./useSelectedNode";
import { update } from "Utils/arm/generatedClients/cosmos/databaseAccounts";
BindingHandlersRegisterer.registerBindingHandlers(); BindingHandlersRegisterer.registerBindingHandlers();
@ -256,7 +257,10 @@ export default class Explorer {
public async openLoginForEntraIDPopUp(): Promise<void> { public async openLoginForEntraIDPopUp(): Promise<void> {
if (userContext.databaseAccount.properties?.documentEndpoint) { if (userContext.databaseAccount.properties?.documentEndpoint) {
const hrefEndpoint = new URL(userContext.databaseAccount.properties.documentEndpoint).href.replace(/\/$/, "/.default"); const hrefEndpoint = new URL(userContext.databaseAccount.properties.documentEndpoint).href.replace(
/\/$/,
"/.default",
);
const msalInstance = await getMsalInstance(); const msalInstance = await getMsalInstance();
try { try {
@ -267,25 +271,28 @@ export default class Explorer {
localStorage.setItem("cachedTenantId", response.tenantId); localStorage.setItem("cachedTenantId", response.tenantId);
const cachedAccount = msalInstance.getAllAccounts()?.[0]; const cachedAccount = msalInstance.getAllAccounts()?.[0];
msalInstance.setActiveAccount(cachedAccount); msalInstance.setActiveAccount(cachedAccount);
let aadToken = await acquireTokenWithMsal(msalInstance, { const aadToken = await acquireTokenWithMsal(msalInstance, {
forceRefresh: true, forceRefresh: true,
scopes: [hrefEndpoint], scopes: [hrefEndpoint],
authority: `${configContext.AAD_ENDPOINT}${localStorage.getItem("cachedTenantId")}`, authority: `${configContext.AAD_ENDPOINT}${localStorage.getItem("cachedTenantId")}`,
}); });
updateUserContext({aadToken: aadToken}); updateUserContext({ aadToken: aadToken });
} catch (error) { } catch (error) {
if (error instanceof msal.AuthError && error.errorCode === msal.BrowserAuthErrorMessage.popUpWindowError.code) { if (error instanceof msal.AuthError && error.errorCode === msal.BrowserAuthErrorMessage.popUpWindowError.code) {
useDialog useDialog
.getState() .getState()
.showOkModalDialog( .showOkModalDialog(
"Pop up blocked", "Pop up blocked",
"We were unable to establish authorization for this account, due to pop-ups being disabled in the browser.\nPlease enable pop-ups for this site and try again", "We were unable to establish authorization for this account, due to pop-ups being disabled in the browser.\nPlease enable pop-ups for this site and try again",
); );
} else { } else {
const errorJson = JSON.stringify(error); const errorJson = JSON.stringify(error);
useDialog useDialog
.getState() .getState()
.showOkModalDialog("Failed to perform authorization", `We were unable to establish authorization for this account, due to the following error: \n${errorJson}`); .showOkModalDialog(
"Failed to perform authorization",
`We were unable to establish authorization for this account, due to the following error: \n${errorJson}`,
);
} }
} }
} }

View File

@ -15,7 +15,7 @@ import {
import * as Constants from "Common/Constants"; import * as Constants from "Common/Constants";
import { SplitterDirection } from "Common/Splitter"; import { SplitterDirection } from "Common/Splitter";
import { InfoTooltip } from "Common/Tooltip/InfoTooltip"; import { InfoTooltip } from "Common/Tooltip/InfoTooltip";
import { Platform, configContext } from "ConfigContext" import { Platform, configContext } from "ConfigContext";
import { useDatabases } from "Explorer/useDatabases"; import { useDatabases } from "Explorer/useDatabases";
import { import {
DefaultRUThreshold, DefaultRUThreshold,
@ -52,8 +52,9 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
const [enableDataPlaneRBACOption, setEnableDataPlaneRBACOption] = useState<string>( const [enableDataPlaneRBACOption, setEnableDataPlaneRBACOption] = useState<string>(
LocalStorageUtility.hasItem(StorageKey.DataPlaneRbacEnabled) LocalStorageUtility.hasItem(StorageKey.DataPlaneRbacEnabled)
? LocalStorageUtility.getEntryString(StorageKey.DataPlaneRbacEnabled) ? LocalStorageUtility.getEntryString(StorageKey.DataPlaneRbacEnabled)
: Constants.RBACOptions.setAutomaticRBACOption); : Constants.RBACOptions.setAutomaticRBACOption,
);
const [showDataPlaneRBACWarning, setShowDataPlaneRBACWarning] = useState<boolean>(false); const [showDataPlaneRBACWarning, setShowDataPlaneRBACWarning] = useState<boolean>(false);
const [ruThresholdEnabled, setRUThresholdEnabled] = useState<boolean>(isRUThresholdEnabled()); const [ruThresholdEnabled, setRUThresholdEnabled] = useState<boolean>(isRUThresholdEnabled());
@ -136,15 +137,18 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
LocalStorageUtility.setEntryNumber(StorageKey.CustomItemPerPage, customItemPerPage); LocalStorageUtility.setEntryNumber(StorageKey.CustomItemPerPage, customItemPerPage);
LocalStorageUtility.setEntryString(StorageKey.DataPlaneRbacEnabled, enableDataPlaneRBACOption); LocalStorageUtility.setEntryString(StorageKey.DataPlaneRbacEnabled, enableDataPlaneRBACOption);
if(enableDataPlaneRBACOption === Constants.RBACOptions.setTrueRBACOption || (enableDataPlaneRBACOption === Constants.RBACOptions.setAutomaticRBACOption && userContext.databaseAccount.properties.disableLocalAuth)) { if (
enableDataPlaneRBACOption === Constants.RBACOptions.setTrueRBACOption ||
(enableDataPlaneRBACOption === Constants.RBACOptions.setAutomaticRBACOption &&
userContext.databaseAccount.properties.disableLocalAuth)
) {
updateUserContext({ updateUserContext({
dataPlaneRbacEnabled: true dataPlaneRbacEnabled: true,
}); });
} } else {
else {
updateUserContext({ updateUserContext({
dataPlaneRbacEnabled: false, dataPlaneRbacEnabled: false,
}) });
} }
LocalStorageUtility.setEntryBoolean(StorageKey.RUThresholdEnabled, ruThresholdEnabled); LocalStorageUtility.setEntryBoolean(StorageKey.RUThresholdEnabled, ruThresholdEnabled);
@ -262,8 +266,10 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
): void => { ): void => {
setEnableDataPlaneRBACOption(option.key); setEnableDataPlaneRBACOption(option.key);
const shouldShowWarning = option.key === Constants.RBACOptions.setTrueRBACOption || const shouldShowWarning =
(option.key === Constants.RBACOptions.setAutomaticRBACOption && userContext.databaseAccount.properties.disableLocalAuth === true); option.key === Constants.RBACOptions.setTrueRBACOption ||
(option.key === Constants.RBACOptions.setAutomaticRBACOption &&
userContext.databaseAccount.properties.disableLocalAuth === true);
setShowDataPlaneRBACWarning(shouldShowWarning); setShowDataPlaneRBACWarning(shouldShowWarning);
}; };
@ -427,48 +433,56 @@ export const SettingsPane: FunctionComponent<{ explorer: Explorer }> = ({
</div> </div>
</div> </div>
)} )}
{(userContext.apiType === "SQL" && userContext.authType == AuthType.AAD) && ( {userContext.apiType === "SQL" && userContext.authType === AuthType.AAD && (
<> <>
<div className="settingsSection"> <div className="settingsSection">
<div className="settingsSectionPart"> <div className="settingsSectionPart">
<fieldset> <fieldset>
<legend id="enableDataPlaneRBACOptions" className="settingsSectionLabel legendLabel"> <legend id="enableDataPlaneRBACOptions" className="settingsSectionLabel legendLabel">
Enable Entra ID RBAC Enable Entra ID RBAC
</legend> </legend>
<TooltipHost <TooltipHost
content={ content={
<> <>
Choose Automatic to enable Entra ID RBAC automatically. True/False to force enable/disable Entra ID RBAC. Choose Automatic to enable Entra ID RBAC automatically. True/False to force enable/disable Entra
<a href="https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-setup-rbac#use-data-explorer" target="_blank" rel="noopener noreferrer"> Learn more </a> ID RBAC.
</> <a
} href="https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-setup-rbac#use-data-explorer"
> target="_blank"
<Icon iconName="Info" ariaLabel="Info tooltip" className="panelInfoIcon" tabIndex={0} /> rel="noopener noreferrer"
</TooltipHost> >
{(showDataPlaneRBACWarning && configContext.platform == Platform.Portal) && ( {" "}
<MessageBar Learn more{" "}
messageBarType={MessageBarType.warning} </a>
isMultiline={true} </>
onDismiss={() => setShowDataPlaneRBACWarning(false)} }
dismissButtonAriaLabel="Close" >
> <Icon iconName="Info" ariaLabel="Info tooltip" className="panelInfoIcon" tabIndex={0} />
Please click on "Login for Entra ID RBAC" prior to performing Entra ID RBAC operations </TooltipHost>
</MessageBar> {showDataPlaneRBACWarning && configContext.platform === Platform.Portal && (
)} <MessageBar
<ChoiceGroup messageBarType={MessageBarType.warning}
ariaLabelledBy="enableDataPlaneRBACOptions" isMultiline={true}
options={dataPlaneRBACOptionsList} onDismiss={() => setShowDataPlaneRBACWarning(false)}
styles={choiceButtonStyles} dismissButtonAriaLabel="Close"
selectedKey={enableDataPlaneRBACOption} >
onChange={handleOnDataPlaneRBACOptionChange} Please click on &quot;Login for Entra ID RBAC&quot; prior to performing Entra ID RBAC operations
/> </MessageBar>
</fieldset> )}
<ChoiceGroup
ariaLabelledBy="enableDataPlaneRBACOptions"
options={dataPlaneRBACOptionsList}
styles={choiceButtonStyles}
selectedKey={enableDataPlaneRBACOption}
onChange={handleOnDataPlaneRBACOptionChange}
/>
</fieldset>
</div>
</div> </div>
</div>
</> </>
)} )}
{(userContext.apiType === "SQL") && ( {userContext.apiType === "SQL" && (
<> <>
<div className="settingsSection"> <div className="settingsSection">
<div className="settingsSectionPart"> <div className="settingsSectionPart">
<div> <div>

View File

@ -255,7 +255,7 @@ async function configureHostedWithAAD(config: AAD): Promise<Explorer> {
const subscriptionId = accountResourceId && accountResourceId.split("subscriptions/")[1].split("/")[0]; const subscriptionId = accountResourceId && accountResourceId.split("subscriptions/")[1].split("/")[0];
const resourceGroup = accountResourceId && accountResourceId.split("resourceGroups/")[1].split("/")[0]; const resourceGroup = accountResourceId && accountResourceId.split("resourceGroups/")[1].split("/")[0];
let aadToken; let aadToken;
let keys: DatabaseAccountListKeysResult = {}; const keys: DatabaseAccountListKeysResult = {};
if (account.properties?.documentEndpoint) { if (account.properties?.documentEndpoint) {
const hrefEndpoint = new URL(account.properties.documentEndpoint).href.replace(/\/$/, "/.default"); const hrefEndpoint = new URL(account.properties.documentEndpoint).href.replace(/\/$/, "/.default");
const msalInstance = await getMsalInstance(); const msalInstance = await getMsalInstance();
@ -273,27 +273,25 @@ async function configureHostedWithAAD(config: AAD): Promise<Explorer> {
} }
} }
try { try {
if (userContext.apiType === "SQL") if (userContext.apiType === "SQL") {
{ if (LocalStorageUtility.hasItem(StorageKey.DataPlaneRbacEnabled)) {
if (LocalStorageUtility.hasItem(StorageKey.DataPlaneRbacEnabled)) { const isDataPlaneRbacSetting = LocalStorageUtility.getEntryString(StorageKey.DataPlaneRbacEnabled);
const isDataPlaneRbacSetting = LocalStorageUtility.getEntryString(StorageKey.DataPlaneRbacEnabled);
let dataPlaneRbacEnabled; let dataPlaneRbacEnabled;
if (isDataPlaneRbacSetting === Constants.RBACOptions.setAutomaticRBACOption) { if (isDataPlaneRbacSetting === Constants.RBACOptions.setAutomaticRBACOption) {
dataPlaneRbacEnabled = account.properties.disableLocalAuth; dataPlaneRbacEnabled = account.properties.disableLocalAuth;
} else { } else {
dataPlaneRbacEnabled = isDataPlaneRbacSetting === Constants.RBACOptions.setTrueRBACOption; dataPlaneRbacEnabled = isDataPlaneRbacSetting === Constants.RBACOptions.setTrueRBACOption;
} }
updateUserContext({ dataPlaneRbacEnabled }); updateUserContext({ dataPlaneRbacEnabled });
} }
} } else {
else { const keys: DatabaseAccountListKeysResult = await listKeys(subscriptionId, resourceGroup, account.name);
let keys: DatabaseAccountListKeysResult = await listKeys(subscriptionId, resourceGroup, account.name); updateUserContext({
updateUserContext({ masterKey: keys.primaryMasterKey,
masterKey: keys.primaryMasterKey });
}); }
}
} catch (e) { } catch (e) {
if (userContext.features.enableAadDataPlane) { if (userContext.features.enableAadDataPlane) {
console.warn(e); console.warn(e);
@ -474,25 +472,23 @@ async function configurePortal(): Promise<Explorer> {
const { databaseAccount: account, subscriptionId, resourceGroup } = userContext; const { databaseAccount: account, subscriptionId, resourceGroup } = userContext;
if (userContext.apiType === "SQL") if (userContext.apiType === "SQL") {
{ if (LocalStorageUtility.hasItem(StorageKey.DataPlaneRbacEnabled)) {
if (LocalStorageUtility.hasItem(StorageKey.DataPlaneRbacEnabled)) { const isDataPlaneRbacSetting = LocalStorageUtility.getEntryString(StorageKey.DataPlaneRbacEnabled);
const isDataPlaneRbacSetting = LocalStorageUtility.getEntryString(StorageKey.DataPlaneRbacEnabled);
let dataPlaneRbacEnabled; let dataPlaneRbacEnabled;
if (isDataPlaneRbacSetting === Constants.RBACOptions.setAutomaticRBACOption) { if (isDataPlaneRbacSetting === Constants.RBACOptions.setAutomaticRBACOption) {
dataPlaneRbacEnabled = account.properties.disableLocalAuth; dataPlaneRbacEnabled = account.properties.disableLocalAuth;
} else { } else {
dataPlaneRbacEnabled = isDataPlaneRbacSetting === Constants.RBACOptions.setTrueRBACOption; dataPlaneRbacEnabled = isDataPlaneRbacSetting === Constants.RBACOptions.setTrueRBACOption;
}
updateUserContext({ dataPlaneRbacEnabled });
} }
updateUserContext({ dataPlaneRbacEnabled });
} }
else { } else {
let keys: DatabaseAccountListKeysResult = await listKeys(subscriptionId, resourceGroup, account.name); const keys: DatabaseAccountListKeysResult = await listKeys(subscriptionId, resourceGroup, account.name);
updateUserContext({ updateUserContext({
masterKey: keys.primaryMasterKey masterKey: keys.primaryMasterKey,
}); });
} }