-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsecure-storage.ts
More file actions
204 lines (166 loc) · 7.17 KB
/
secure-storage.ts
File metadata and controls
204 lines (166 loc) · 7.17 KB
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
import { BadRequestError, InternalServerError , TooManyRequestsError } from 'errors/apps-sdk-error';
import { getGcpConnectionData, getGcpIdentityToken } from 'lib/gcp/gcp';
import { MONDAY_CODE_RESERVED_PRIMITIVES_KEY } from 'lib/secure-storage/secure-storage.consts';
import { RequestOptions } from 'types/fetch';
import { GcpConnectionData } from 'types/gcp';
import { JsonValue } from 'types/general';
import { isDefined } from 'types/guards';
import {
AppId,
ConnectionData,
ISecureStorageInstance,
Token,
VaultBaseResponse,
VaultGcpLoginResponse, VaultLookupResponse
} from 'types/secure-storage';
import { getMondayCodeContext, validateEnvironment } from 'utils/env';
import { fetchWrapper } from 'utils/fetch-wrapper';
import { Logger } from 'utils/logger';
import { TIME_IN_MILLISECOND } from 'utils/time-enum';
import { isObject } from 'utils/validations';
const logger = new Logger('SecureStorage', { mondayInternal: true });
const MIN_TOKEN_EXPIRE_TTL_HOURS = 0.05;
const secureStorageFetch = async <T>(path: string, connectionData: ConnectionData, options: RequestOptions): Promise<T | undefined> => {
const { method = 'GET', body } = options;
if (!isDefined(path)) {
throw new BadRequestError('`path` must be provided');
}
const { token, identityToken } = connectionData;
const fetchObj = {
headers: {
'Content-Type': 'application/json',
...(token && { 'X-Vault-Token': token }),
...(identityToken && { 'Authorization': `Bearer ${identityToken}` })
},
method,
body: body ? JSON.stringify(body) : undefined
};
let result: VaultBaseResponse | undefined;
try {
result = await fetchWrapper<VaultBaseResponse>(path, fetchObj);
} catch (error: unknown) {
if (error instanceof TooManyRequestsError) {
logger.warn('[secureStorageFetch] Rate limit exceeded while communicating with secure storage');
throw error;
}
logger.error('[secureStorageFetch] Unexpected error occurred while communicating with secure storage', { error: error as Error });
throw new InternalServerError('An issue occurred while accessing secure storage');
}
if (!isDefined(result)) {
return;
}
if (isDefined(result.errors)) {
logger.warn(`[secureStorageFetch] Errors occurred while communicating with secure storage.\nErrors: ${result.errors.join()}`);
throw new BadRequestError('Provided input is invalid');
}
if (!isDefined(result.data)) {
throw new InternalServerError('some thing went wrong when when communicating with secure storage');
}
return result.data as T;
};
const generateCrudPath = (path: string, id?: AppId) => {
const { secureStorageAddress } = getMondayCodeContext();
if (!isDefined(path)) {
throw new BadRequestError('Missing secret key');
}
if (!isDefined(id)) {
logger.error('[generateCrudPath] projectId is not defined');
throw new InternalServerError('An issue occurred while accessing secure storage');
}
const generalSecretPath = 'v1/kv/data';
const fullPath = `${secureStorageAddress}/${generalSecretPath}/${id}/${path}`;
return fullPath;
};
const getToken = async (gcpCredentials: GcpConnectionData, connectionData: ConnectionData): Promise<Token> => {
const { secureStorageAddress } = getMondayCodeContext();
const loginUrl = `${secureStorageAddress}/v1/auth/gcp/login`;
const body = JSON.stringify({
role: gcpCredentials.projectId,
jwt: gcpCredentials.token
});
const loginResponse = await fetchWrapper<VaultGcpLoginResponse>(loginUrl, {
method: 'POST',
body,
headers: { Authorization: `Bearer ${connectionData.identityToken}` }
});
if (!isDefined(loginResponse)) {
logger.error('[getToken] invalid gcp login response');
throw new InternalServerError('An error occurred while authenticating');
}
const token = loginResponse?.auth?.client_token;
return token;
};
const getTokenExpiry = async (connectionData: ConnectionData) => {
const { secureStorageAddress } = getMondayCodeContext();
const lookupUrl = `${secureStorageAddress}/v1/auth/token/lookup-self`;
const response = await secureStorageFetch<VaultLookupResponse>(lookupUrl, connectionData, { method: 'GET' });
if (!isDefined(response)) {
throw new InternalServerError('An error occurred while authenticating');
}
return response.expire_time;
};
const getConnectionData = async (connectionData: ConnectionData): Promise<ConnectionData> => {
const gcpCredentials = await getGcpConnectionData();
connectionData.token = await getToken(gcpCredentials, connectionData);
const expireTime = await getTokenExpiry(connectionData);
const { token, identityToken } = connectionData;
return { token, expireTime, id: gcpCredentials.projectId, identityToken };
};
const authenticate = async (connectionData: ConnectionData): Promise<ConnectionData> => {
validateEnvironment();
if (!isDefined(connectionData)) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
connectionData = {};
}
connectionData.identityToken = await getGcpIdentityToken(connectionData?.identityToken);
if (!isDefined(connectionData.token)) {
return await getConnectionData(connectionData);
}
const { expireTime, token, id, identityToken } = connectionData;
const tokenTtlInHours = ((new Date(expireTime)).getTime() - (new Date()).getTime()) / TIME_IN_MILLISECOND.HOUR;
const ttlPassedThreshold = tokenTtlInHours <= MIN_TOKEN_EXPIRE_TTL_HOURS;
if (ttlPassedThreshold) {
logger.info(`[authenticate] TTL PASSED ${JSON.stringify({ tokenTtlInHours, expireTime })}`);
return await getConnectionData(connectionData);
}
if (!isDefined(id)) {
logger.error('[authenticate] projectId is not defined');
throw new InternalServerError('An issue occurred while accessing secure storage');
}
return { token, expireTime, id, identityToken };
};
let connectionData: ConnectionData;
export class SecureStorage implements ISecureStorageInstance {
constructor() {
validateEnvironment();
}
async delete(key: string) {
connectionData = await authenticate(connectionData);
const fullPath = generateCrudPath(key, connectionData.id);
await secureStorageFetch<VaultBaseResponse>(fullPath, connectionData, { method: 'DELETE' });
return true;
}
async get<T>(key: string) {
connectionData = await authenticate(connectionData);
const fullPath = generateCrudPath(key, connectionData.id);
const result = await secureStorageFetch<VaultBaseResponse>(fullPath, connectionData, { method: 'GET' });
if (!isDefined(result) || !isDefined(result?.data)) {
return null;
}
if (result.data?.[MONDAY_CODE_RESERVED_PRIMITIVES_KEY]) {
return result.data[MONDAY_CODE_RESERVED_PRIMITIVES_KEY] as T;
}
return result.data as T;
}
async set<T extends JsonValue>(key: string, value: T) {
connectionData = await authenticate(connectionData);
const fullPath = generateCrudPath(key, connectionData.id);
const formalizedValue = isObject(value) ? value : { [MONDAY_CODE_RESERVED_PRIMITIVES_KEY]: value };
await secureStorageFetch<VaultBaseResponse>(fullPath, connectionData, {
method: 'PUT',
body: { data: formalizedValue }
});
return true;
}
}