-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathapi-token-store.ts
337 lines (302 loc) · 10.3 KB
/
api-token-store.ts
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import type { EventEmitter } from 'events';
import metricsHelper from '../util/metrics-helper';
import { DB_TIME } from '../metric-events';
import type { Logger, LogProvider } from '../logger';
import NotFoundError from '../error/notfound-error';
import type { IApiTokenStore } from '../types/stores/api-token-store';
import {
ApiTokenType,
type IApiToken,
type IApiTokenCreate,
isAllProjects,
} from '../types/models/api-token';
import { ALL_PROJECTS } from '../util/constants';
import type { Db } from './db';
import { inTransaction } from './transaction';
import type { IFlagResolver } from '../types';
const TABLE = 'api_tokens';
const API_LINK_TABLE = 'api_token_project';
const ALL = '*';
interface ITokenInsert {
id: number;
secret: string;
username: string;
type: ApiTokenType;
expires_at?: Date;
created_at: Date;
seen_at?: Date;
environment: string;
tokenName?: string;
}
interface ITokenRow extends ITokenInsert {
project: string;
}
const tokenRowReducer = (acc, tokenRow) => {
const { project, ...token } = tokenRow;
if (!acc[tokenRow.secret]) {
acc[tokenRow.secret] = {
secret: token.secret,
tokenName: token.token_name ? token.token_name : token.username,
type: token.type.toLowerCase(),
project: ALL,
projects: [ALL],
environment: token.environment ? token.environment : ALL,
expiresAt: token.expires_at,
createdAt: token.created_at,
alias: token.alias,
seenAt: token.seen_at,
username: token.token_name ? token.token_name : token.username,
};
}
const currentToken = acc[tokenRow.secret];
if (tokenRow.project) {
if (isAllProjects(currentToken.projects)) {
currentToken.projects = [];
}
currentToken.projects.push(tokenRow.project);
currentToken.project = currentToken.projects.join(',');
}
return acc;
};
const toRow = (newToken: IApiTokenCreate) => ({
username: newToken.tokenName ?? newToken.username,
token_name: newToken.tokenName ?? newToken.username,
secret: newToken.secret,
type: newToken.type,
environment:
newToken.environment === ALL ? undefined : newToken.environment,
expires_at: newToken.expiresAt,
alias: newToken.alias || null,
});
const toTokens = (rows: any[]): IApiToken[] => {
const tokens = rows.reduce(tokenRowReducer, {});
return Object.values(tokens);
};
export class ApiTokenStore implements IApiTokenStore {
private logger: Logger;
private timer: Function;
private db: Db;
private readonly flagResolver: IFlagResolver;
constructor(
db: Db,
eventBus: EventEmitter,
getLogger: LogProvider,
flagResolver: IFlagResolver,
) {
this.db = db;
this.logger = getLogger('api-tokens.js');
this.timer = (action: string) =>
metricsHelper.wrapTimer(eventBus, DB_TIME, {
store: 'api-tokens',
action,
});
this.flagResolver = flagResolver;
}
// helper function that we can move to utils
async withTimer<T>(timerName: string, fn: () => Promise<T>): Promise<T> {
const stopTimer = this.timer(timerName);
try {
return await fn();
} finally {
stopTimer();
}
}
async count(): Promise<number> {
return this.db(TABLE)
.count('*')
.then((res) => Number(res[0].count));
}
async countByType(): Promise<Map<string, number>> {
return this.db(TABLE)
.select('type')
.count('*')
.groupBy('type')
.then((res) => {
const map = new Map<string, number>();
res.forEach((row) => {
map.set(row.type.toString(), Number(row.count));
});
return map;
});
}
async getAll(): Promise<IApiToken[]> {
const stopTimer = this.timer('getAll');
const rows = await this.makeTokenProjectQuery();
stopTimer();
return toTokens(rows);
}
async getAllActive(): Promise<IApiToken[]> {
const stopTimer = this.timer('getAllActive');
const rows = await this.makeTokenProjectQuery()
.where('expires_at', 'IS', null)
.orWhere('expires_at', '>', 'now()');
stopTimer();
return toTokens(rows);
}
private makeTokenProjectQuery() {
return this.db<ITokenRow>(`${TABLE} as tokens`)
.leftJoin(
`${API_LINK_TABLE} as token_project_link`,
'tokens.secret',
'token_project_link.secret',
)
.select(
'tokens.secret',
'username',
'token_name',
'type',
'expires_at',
'created_at',
'alias',
'seen_at',
'environment',
'token_project_link.project',
);
}
async insert(newToken: IApiTokenCreate): Promise<IApiToken> {
const response = await inTransaction(this.db, async (tx) => {
const [row] = await tx<ITokenInsert>(TABLE).insert(
toRow(newToken),
['created_at'],
);
const updateProjectTasks = (newToken.projects || [])
.filter((project) => {
return project !== ALL_PROJECTS;
})
.map((project) => {
return tx.raw(
`INSERT INTO ${API_LINK_TABLE} VALUES (?, ?)`,
[newToken.secret, project],
);
});
await Promise.all(updateProjectTasks);
return {
...newToken,
username: newToken.tokenName,
alias: newToken.alias || null,
project: newToken.projects?.join(',') || '*',
createdAt: row.created_at,
};
});
return response;
}
destroy(): void {}
async exists(secret: string): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE secret = ?) AS present`,
[secret],
);
const { present } = result.rows[0];
return present;
}
async get(key: string): Promise<IApiToken> {
const stopTimer = this.timer('get-by-secret');
const row = await this.makeTokenProjectQuery().where(
'tokens.secret',
key,
);
stopTimer();
return toTokens(row)[0];
}
async delete(secret: string): Promise<void> {
return this.db<ITokenRow>(TABLE).where({ secret }).del();
}
async deleteAll(): Promise<void> {
return this.db<ITokenRow>(TABLE).del();
}
async setExpiry(secret: string, expiresAt: Date): Promise<IApiToken> {
const rows = await this.makeTokenProjectQuery()
.update({ expires_at: expiresAt })
.where({ secret })
.returning('*');
if (rows.length > 0) {
return toTokens(rows)[0];
}
throw new NotFoundError('Could not find api-token.');
}
async markSeenAt(secrets: string[]): Promise<void> {
const now = new Date();
try {
await this.db(TABLE)
.whereIn('secret', secrets)
.update({ seen_at: now });
} catch (err) {
this.logger.error('Could not update lastSeen, error: ', err);
}
}
async countDeprecatedTokens(): Promise<{
orphanedTokens: number;
activeOrphanedTokens: number;
legacyTokens: number;
activeLegacyTokens: number;
}> {
const allLegacyCount = this.withTimer('allLegacyCount', () =>
this.db<ITokenRow>(`${TABLE} as tokens`)
.where('tokens.secret', 'NOT LIKE', '%:%')
.count()
.first()
.then((res) => Number(res?.count) || 0),
);
const activeLegacyCount = this.withTimer('activeLegacyCount', () =>
this.db<ITokenRow>(`${TABLE} as tokens`)
.where('tokens.secret', 'NOT LIKE', '%:%')
.andWhereRaw("tokens.seen_at > NOW() - INTERVAL '3 MONTH'")
.count()
.first()
.then((res) => Number(res?.count) || 0),
);
const orphanedTokensQuery = this.db<ITokenRow>(`${TABLE} as tokens`)
.leftJoin(
`${API_LINK_TABLE} as token_project_link`,
'tokens.secret',
'token_project_link.secret',
)
.whereNull('token_project_link.project')
.andWhere('tokens.secret', 'NOT LIKE', '*:%') // Exclude intentionally wildcard tokens
.andWhere('tokens.secret', 'LIKE', '%:%') // Exclude legacy tokens
.andWhere((builder) => {
builder
.where('tokens.type', ApiTokenType.CLIENT)
.orWhere('tokens.type', ApiTokenType.FRONTEND);
});
const allOrphanedCount = this.withTimer('allOrphanedCount', () =>
orphanedTokensQuery
.clone()
.count()
.first()
.then((res) => Number(res?.count) || 0),
);
const activeOrphanedCount = this.withTimer('activeOrphanedCount', () =>
orphanedTokensQuery
.clone()
.andWhereRaw("tokens.seen_at > NOW() - INTERVAL '3 MONTH'")
.count()
.first()
.then((res) => Number(res?.count) || 0),
);
const [
orphanedTokens,
activeOrphanedTokens,
legacyTokens,
activeLegacyTokens,
] = await Promise.all([
allOrphanedCount,
activeOrphanedCount,
allLegacyCount,
activeLegacyCount,
]);
return {
orphanedTokens,
activeOrphanedTokens,
legacyTokens,
activeLegacyTokens,
};
}
async countProjectTokens(projectId: string): Promise<number> {
const count = await this.db(API_LINK_TABLE)
.where({ project: projectId })
.count()
.first();
return Number(count?.count ?? 0);
}
}