Skip to content

Commit 4c0a55b

Browse files
authored
Add VT API Token Rotation (#52)
1 parent 7b2b683 commit 4c0a55b

2 files changed

Lines changed: 24 additions & 7 deletions

File tree

src/api.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ import { InfluxDB, Point } from '@influxdata/influxdb-client'
1212

1313
const debug = createDebug('app:api')
1414

15+
// const vtClient = new VTApi(process.env.VT_API_KEY)
16+
const vtClient = process.env.VT_API_KEY ? new VTApi(process.env.VT_API_KEY) : null
17+
1518
const redisUrl = process.env.REDIS_URL || 'redis://redis:6379'
1619
console.log(`REDIS_URL: ${redisUrl}`)
1720
// NOTE: Increase connectTimeout for Render, consider using reconnectStrategy...
@@ -210,12 +213,11 @@ export async function getVTStats(hash) {
210213
return cached
211214
}
212215
debug(`-- CACHE MISS: ${key}`)
213-
const vt = new VTApi(process.env.VT_API_KEY)
214216
let stats, epoch, data
215217
if (hash.endsWith('==')) {
216218
debug('DEPRECATED - getAnalysis') // TODO: Deprecated
217219
try {
218-
data = await vt.getAnalysis(hash)
220+
data = await vtClient.getAnalysis(hash)
219221
} catch (error) {
220222
await cacheError(key, `Error ${error.status}`)
221223
}
@@ -224,7 +226,7 @@ export async function getVTStats(hash) {
224226
epoch = data?.data?.attributes?.date
225227
} else {
226228
try {
227-
data = await vt.getReport(hash)
229+
data = await vtClient.getReport(hash)
228230
} catch (error) {
229231
await cacheError(key, `Error ${error.status}`)
230232
}

src/virustotal.js

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,28 @@ const debug = createDebug('app:api')
55

66
export class VTApi {
77
/**
8-
* GitHub Api
9-
* @param {string} token
8+
* VirusTotal API
9+
* @param {string} tokens - CSV of API tokens
1010
*/
11-
constructor(token) {
11+
constructor(tokens) {
12+
this.tokens = tokens
13+
.split(',')
14+
.map((t) => t.trim())
15+
.filter(Boolean)
16+
// debug('this.tokens:', this.tokens)
17+
console.log(`Loaded ${this.tokens.length} VT API Keys`)
18+
19+
this.idx = 0
20+
1221
this.client = axios.create({
1322
baseURL: 'https://www.virustotal.com/api/v3/',
14-
headers: { 'X-APIKey': token },
23+
})
24+
25+
this.client.interceptors.request.use((config) => {
26+
config.headers['X-APIKey'] = this.tokens[this.idx]
27+
this.idx = (this.idx + 1) % this.tokens.length
28+
debug('Using token index %d/%d', this.idx, this.tokens.length)
29+
return config
1530
})
1631
}
1732

0 commit comments

Comments
 (0)