๐Ÿ“ฆ Kong / insomnia

๐Ÿ“„ cloud-service-credentials.tsx ยท 272 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272import React, { useEffect, useState } from 'react';
import { Button, Menu, MenuItem, MenuTrigger, Popover } from 'react-aria-components';

import { useRootLoaderData } from '~/root';
import { useDeleteCloudCredentialActionFetcher } from '~/routes/cloud-credentials.$cloudCredentialId.delete';

import { EXTERNAL_VAULT_PLUGIN_NAME } from '../../../common/constants';
import {
  type CloudProviderCredential,
  type CloudProviderName,
  getProviderDisplayName,
} from '../../../models/cloud-credential';
import { executePluginMainAction } from '../../../plugins';
import { getBundlePlugins } from '../../../plugins';
import { usePlanData } from '../../hooks/use-plan';
import { Icon } from '../icon';
import { showError, showModal } from '../modals';
import { AskModal } from '../modals/ask-modal';
import { CloudCredentialModal } from '../modals/cloud-credential-modal/cloud-credential-modal';
import { SvgIcon } from '../svg-icon';
import { Tooltip } from '../tooltip';
import { UpgradeNotice } from '../upgrade-notice';
import { NumberSetting } from './number-setting';

interface createCredentialItemType {
  name: string;
  id: CloudProviderName;
  icon: JSX.Element;
}
const createCredentialItemList: createCredentialItemType[] = [
  {
    id: 'aws',
    name: getProviderDisplayName('aws'),
    icon: <i className="fa-brands fa-aws ml-1" />,
  },
  {
    id: 'gcp',
    name: getProviderDisplayName('gcp'),
    icon: <SvgIcon icon="gcp-logo" className="ml-1" />,
  },
  {
    id: 'hashicorp',
    name: getProviderDisplayName('hashicorp'),
    icon: <SvgIcon icon="hashicorp" className="ml-1" />,
  },
  {
    id: 'azure',
    name: getProviderDisplayName('azure'),
    icon: <SvgIcon icon="azure-logo" className="ml-1" />,
  },
];
const buttonClassName =
  'disabled:opacity-50 h-7 aspect-square aria-pressed:bg-(--hl-sm) rounded-xs text-(--color-font) hover:bg-(--hl-xs) transition-all text-sm py-1 px-2';

export const CloudServiceCredentialList = () => {
  const { isOwner, isEnterprisePlan } = usePlanData();
  const { cloudCredentials } = useRootLoaderData()!;
  const [modalState, setModalState] = useState<{
    show: boolean;
    provider: CloudProviderName;
    credential?: CloudProviderCredential;
    authUrl?: string;
  }>();
  const [isVaultPluginInstalled, setIsVaultPluginInstalled] = useState(false);
  const deleteCredentialFetcher = useDeleteCloudCredentialActionFetcher();
  useEffect(() => {
    const checkVaultPlugin = async () => {
      const plugins = await getBundlePlugins();
      const vaultPlugin = plugins.find(p => p.name === EXTERNAL_VAULT_PLUGIN_NAME);
      setIsVaultPluginInstalled(!!vaultPlugin);
    };
    checkVaultPlugin();
  }, []);

  const handleDeleteItem = (id: string, name: string) => {
    showModal(AskModal, {
      title: 'Delete Cloud Credential?',
      message: `Are you sure to delete ${name}?`,
      onDone: async (isYes: boolean) => {
        if (isYes) {
          deleteCredentialFetcher.submit({
            cloudCredentialId: id,
          });
        }
      },
    });
  };

  const hideModal = () => {
    setModalState(prevState => {
      const newState = {
        show: false,
        provider: prevState!.provider,
        credentials: undefined,
      };
      return newState;
    });
  };

  const handleCreateCloudServiceCredential = async (key: CloudProviderName) => {
    if (key === 'azure') {
      const { authUrl, error } = await executePluginMainAction({
        pluginName: EXTERNAL_VAULT_PLUGIN_NAME,
        actionName: 'openAuthUrl',
        params: { provider: 'azure' },
      });
      // show error modal if no authUrl generated
      if (!authUrl) {
        console.error('Failed to open Azure auth url', error);
        showError({
          title: 'Azure Authorization Failed',
          message: error || 'Failed to get Azure authentication url',
        });
      } else {
        setModalState({ show: true, provider: key as CloudProviderName, authUrl });
      }
    } else {
      setModalState({ show: true, provider: key as CloudProviderName });
    }
  };

  if (!isEnterprisePlan) {
    return <UpgradeNotice isOwner={isOwner} featureName="Cloud Credentials feature" newPlan="enterprise" />;
  }
  if (!isVaultPluginInstalled) {
    return (
      <div className="notice pad info flex flex-col items-center justify-center gap-2">
        <p>External vault feature could not be enabled because the required module is missing.</p>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-end justify-between">
        <h2 className="z-10 bg-(--color-bg) text-lg font-bold">Service Provider Credential List</h2>
        <MenuTrigger>
          <Button
            aria-label="Create Credential"
            className="flex h-full items-center justify-center gap-2 rounded-xs bg-(--hl-xxs) px-4 py-2 text-sm text-(--color-font) ring-1 ring-transparent transition-all hover:bg-(--hl-xs) focus:ring-(--hl-md) focus:ring-inset aria-pressed:bg-(--hl-sm)"
          >
            <Icon icon="plus-circle" /> Add Credential
          </Button>
          <Popover className="min-w-max" placement="bottom right">
            <Menu
              aria-label="Create cloud service credential actions"
              selectionMode="single"
              onAction={key => handleCreateCloudServiceCredential(key as CloudProviderName)}
              items={createCredentialItemList}
              className="max-h-[85vh] min-w-max overflow-y-auto rounded-md border border-solid border-(--hl-sm) bg-(--color-bg) py-2 text-sm shadow-lg select-none focus:outline-hidden"
            >
              {item => (
                <MenuItem
                  key={item.id}
                  id={item.id}
                  className="flex h-(--line-height-xxs) w-full items-center gap-2 bg-transparent px-(--padding-md) whitespace-nowrap text-(--color-font) transition-colors hover:bg-(--hl-sm) focus:bg-(--hl-xs) focus:outline-hidden disabled:cursor-not-allowed aria-selected:font-bold"
                  aria-label={item.name}
                >
                  {item.icon}
                  <span>{item.name}</span>
                </MenuItem>
              )}
            </Menu>
          </Popover>
        </MenuTrigger>
      </div>
      {cloudCredentials.length === 0 ? (
        <div className="faint pad text-center italic">No cloud service provider credentials found</div>
      ) : (
        <table className="table--fancy table--striped table--valign-middle margin-top margin-bottom">
          <thead>
            <tr>
              <th className="normal-case">Name</th>
              <th className="normal-case">Service Provider</th>
              <th className="normal-case">Action</th>
            </tr>
          </thead>
          <tbody>
            {cloudCredentials.map(cloudCred => {
              const { _id, name, provider, credentials } = cloudCred;
              let isAzureTokenExpired = !credentials;
              if (credentials && provider === 'azure') {
                const tokenExpiresOn = 'expiresOn' in credentials ? credentials.expiresOn : null;
                if (tokenExpiresOn && new Date() >= new Date(tokenExpiresOn)) {
                  isAzureTokenExpired = true;
                }
              }
              const credentialItem = createCredentialItemList.find(item => item.id === provider);
              return (
                <tr key={_id}>
                  <td>
                    {name}
                    {provider === 'azure' && isAzureTokenExpired && (
                      <Tooltip message="Token is expired" position="top">
                        <i className="fa fa-exclamation-circle ml-1 text-(--color-warning)" />
                      </Tooltip>
                    )}
                  </td>
                  <td className="w-36">
                    {credentialItem && (
                      <div className="flex items-center gap-2">
                        {credentialItem.icon}
                        <span>{credentialItem.name}</span>
                      </div>
                    )}
                  </td>
                  <td className="w-52 whitespace-nowrap">
                    <div className="flex gap-2">
                      {provider !== 'azure' && (
                        <Button
                          className={`${buttonClassName} w-16`}
                          onPress={() => setModalState({ show: true, provider: provider!, credential: cloudCred })}
                        >
                          <Icon icon="edit" />
                          &nbsp;&nbsp;Edit
                        </Button>
                      )}
                      {provider === 'azure' && isAzureTokenExpired && (
                        <Button
                          className={`${buttonClassName} w-20`}
                          onPress={() => handleCreateCloudServiceCredential('azure')}
                        >
                          <Icon icon="rotate" /> Renew
                        </Button>
                      )}
                      <Button className={`${buttonClassName} w-20`} onPress={() => handleDeleteItem(_id, name)}>
                        <Icon icon="trash" />
                        &nbsp;&nbsp;Delete
                      </Button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      )}
      <div>
        <h2 className="z-10 bg-(--color-bg) pt-5 pb-2 text-lg font-bold">Cloud Secret Config</h2>
        <div className="form-row items-end justify-between">
          <NumberSetting
            label="Secret Cache Duration(min)"
            setting="vaultSecretCacheDuration"
            help="Enter the amount of time in minutes external vault secrets are cached in Insomnia. Enter 0 to disable cache. Click the Reset Cache button to clear all cache."
            min={0}
            max={720}
          />
          <button
            className="pointer mb-(--padding-sm) ml-(--padding-sm) flex h-(--line-height-xs) w-32 items-center gap-2 rounded-md border border-solid border-(--hl-lg) px-(--padding-md) hover:bg-(--hl-xs)"
            onClick={async () =>
              await executePluginMainAction({
                pluginName: EXTERNAL_VAULT_PLUGIN_NAME,
                actionName: 'clearCache',
              })
            }
          >
            Reset Cache
          </button>
        </div>
      </div>
      {modalState && modalState.show && (
        <CloudCredentialModal
          provider={modalState.provider}
          providerCredential={modalState.credential}
          authUrl={modalState.authUrl}
          onClose={hideModal}
        />
      )}
    </div>
  );
};