-
Notifications
You must be signed in to change notification settings - Fork 66.9k
Expand file tree
/
Copy pathindex.ts
More file actions
355 lines (316 loc) · 11.7 KB
/
index.ts
File metadata and controls
355 lines (316 loc) · 11.7 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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import path from 'path'
import { readCompressedJsonFileFallback } from '@/frame/lib/read-json-file'
import { getOpenApiVersion } from '@/versions/lib/all-versions'
import findPage from '@/frame/lib/find-page'
import type {
AuditLogEventT,
CategorizedEvents,
VersionedAuditLogData,
RawAuditLogEventT,
CategoryNotes,
AuditLogConfig,
} from '../types'
import config from './config.json'
export const AUDIT_LOG_DATA_DIR = 'src/audit-logs/data'
// cache of audit log data
const auditLogEventsCache = new Map<string, Map<string, AuditLogEventT[]>>()
const categorizedAuditLogEventsCache = new Map<string, Map<string, CategorizedEvents>>()
type PipelineConfig = {
sha: string
appendedDescriptions: Record<string, string>
}
// get category notes from config
export function getCategoryNotes(): CategoryNotes {
const auditLogConfig = config as AuditLogConfig
return auditLogConfig.categoryNotes || {}
}
type TitleResolutionContext = {
pages: Record<string, any>
redirects: Record<string, string>
}
// Resolves docs_reference_links URLs to page titles
async function resolveReferenceLinksToTitles(
docsReferenceLinks: string,
context: TitleResolutionContext,
): Promise<string> {
if (!docsReferenceLinks || docsReferenceLinks === 'N/A') {
return ''
}
// Handle multiple comma-separated or space-separated links
const links = docsReferenceLinks
.split(/[,\s]+/)
.map((link) => link.trim())
.filter((link) => link && link !== 'N/A')
const titles = []
for (const link of links) {
try {
const page = findPage(link, context.pages, context.redirects)
if (page) {
// Create a minimal context for rendering the title
const renderContext = {
currentLanguage: 'en',
currentVersion: 'free-pro-team@latest',
pages: context.pages,
redirects: context.redirects,
}
const title = await page.renderProp('title', renderContext, { textOnly: true })
titles.push(title)
} else {
// If we can't resolve the link, use the original URL
titles.push(link)
}
} catch (error) {
// If resolution fails, use the original URL
console.warn(
`Failed to resolve title for link: ${link}`,
error instanceof Error
? error instanceof Error
? error.message
: String(error)
: String(error),
)
titles.push(link)
}
}
return titles.join(', ')
}
// get audit log event data for the requested page and version
//
// returns an array of event objects that look like this:
//
// [
// {
// action: 'account.billing_date_change',
// description: 'event description',
// docs_reference_links: 'event reference links'
// },
// ]
export function getAuditLogEvents(page: string, version: string): AuditLogEventT[] {
const openApiVersion = getOpenApiVersion(version)
const auditLogFileName = path.join(AUDIT_LOG_DATA_DIR, openApiVersion, `${page}.json`)
// If the data isn't cached for an entire version or a particular page, read
// the data from the JSON file the first time around
if (!auditLogEventsCache.has(openApiVersion)) {
auditLogEventsCache.set(openApiVersion, new Map())
auditLogEventsCache.get(openApiVersion)?.set(page, [])
auditLogEventsCache
.get(openApiVersion)
?.set(page, readCompressedJsonFileFallback(auditLogFileName))
} else if (!auditLogEventsCache.get(openApiVersion)?.has(page)) {
auditLogEventsCache.get(openApiVersion)?.set(page, [])
auditLogEventsCache
.get(openApiVersion)
?.set(page, readCompressedJsonFileFallback(auditLogFileName))
}
const auditLogEvents = auditLogEventsCache.get(openApiVersion)?.get(page)
// If an event doesn't yet have a description (value will be empty string or
// "N/A"), then we don't show the event.
const filteredAuditLogEvents = auditLogEvents?.filter(
(event) => event.description !== 'N/A' && event.description !== '',
)
return filteredAuditLogEvents || []
}
// get categorized audit log event data for the requested page and version
//
// Events are grouped by category; the category is the first part of the event
// action (e.g. category is `repo` for the `repo.create` event) so we extract
// the categories and then group events under those categories and return an
// object that looks like this:
//
// {
// git: [ [Object], [Object] ],
// repo: [ [Object] ],
// user: [ [Object], [Object] ]
// }
export function getCategorizedAuditLogEvents(page: string, version: string): CategorizedEvents {
const events = getAuditLogEvents(page, version)
const openApiVersion = getOpenApiVersion(version)
if (!categorizedAuditLogEventsCache.get(openApiVersion)) {
categorizedAuditLogEventsCache.set(openApiVersion, new Map())
categorizedAuditLogEventsCache.get(openApiVersion)?.set(page, categorizeEvents(events))
} else if (!categorizedAuditLogEventsCache.get(openApiVersion)?.get(page)) {
categorizedAuditLogEventsCache.get(openApiVersion)?.set(page, categorizeEvents(events))
}
return categorizedAuditLogEventsCache.get(openApiVersion)?.get(page) || {}
}
// Filters audit log events based on allowlist values.
export async function filterByAllowlistValues({
eventsToCheck,
allowListValues,
currentEvents = [],
pipelineConfig,
titleContext,
}: {
eventsToCheck: RawAuditLogEventT[]
allowListValues: string | string[]
currentEvents?: AuditLogEventT[]
pipelineConfig: PipelineConfig
titleContext?: TitleResolutionContext
}) {
if (!Array.isArray(allowListValues)) allowListValues = [allowListValues]
if (!currentEvents) currentEvents = []
const seen = new Set(currentEvents.map((event) => event.action))
const minimalEvents = []
for (const event of eventsToCheck) {
const eventAllowlists = event._allowlists
if (eventAllowlists === null) continue
if (allowListValues.some((av) => eventAllowlists.includes(av))) {
if (seen.has(event.action)) continue
seen.add(event.action)
const minimal: AuditLogEventT = {
action: event.action,
description: processAndGetEventDescription(event, eventAllowlists, pipelineConfig),
docs_reference_links: event.docs_reference_links,
fields: event.fields,
}
// Resolve reference link titles if context is provided
if (titleContext && event.docs_reference_links && event.docs_reference_links !== 'N/A') {
try {
minimal.docs_reference_titles = await resolveReferenceLinksToTitles(
event.docs_reference_links,
titleContext,
)
} catch (error) {
console.warn(
`Failed to resolve titles for event ${event.action}:`,
error instanceof Error ? error.message : String(error),
)
}
}
minimalEvents.push(minimal)
}
}
return [...minimalEvents, ...currentEvents]
}
// Filters audit log events based on allowlist values and processes an
// event's supported GHES versions.
//
// * eventsToCheck: events to consider
// * allowListvalue: allowlist value to filter by
// * currentEvents: events already collected
// * pipelineConfig: audit log pipeline config data
// * auditLogPage: the audit log page the event belongs to
// * titleContext: optional context for resolving reference link titles
//
// Mutates `currentGhesEvents` and updates it with any new filtered for audit
// log events, the object maps GHES versions to page events for that version e.g.:
//
// {
// ghes-3.10': {
// organization: [...],
// enterprise: [...],
// user: [...],
// },
// ghes-3.11': {
// organization: [...],
// enterprise: [...],
// user: [...],
// },
// }
export async function filterAndUpdateGhesDataByAllowlistValues({
eventsToCheck,
allowListValue,
currentGhesEvents,
pipelineConfig,
auditLogPage,
titleContext,
}: {
eventsToCheck: RawAuditLogEventT[]
allowListValue: string
currentGhesEvents: VersionedAuditLogData
pipelineConfig: PipelineConfig
auditLogPage: string
titleContext?: TitleResolutionContext
}) {
if (!currentGhesEvents) currentGhesEvents = {}
const seenByGhesVersion = new Map()
for (const [ghesVersion, events] of Object.entries(currentGhesEvents)) {
if (!events[auditLogPage]) continue
const pageEvents = new Set(events[auditLogPage].map((e) => e.action))
seenByGhesVersion.set(ghesVersion, pageEvents)
}
for (const event of eventsToCheck) {
for (const ghesVersion of Object.keys(event.ghes)) {
const ghesVersionAllowlists = event.ghes[ghesVersion]._allowlists
const fullGhesVersion = `ghes-${ghesVersion}`
if (ghesVersionAllowlists === null) continue
if (seenByGhesVersion.get(fullGhesVersion)?.has(event.action)) continue
if (ghesVersionAllowlists.includes(allowListValue)) {
const minimal: AuditLogEventT = {
action: event.action,
description: processAndGetEventDescription(event, ghesVersionAllowlists, pipelineConfig),
docs_reference_links: event.docs_reference_links,
fields: event.ghes[ghesVersion].fields || event.fields,
}
// Resolve reference link titles if context is provided
if (titleContext && event.docs_reference_links && event.docs_reference_links !== 'N/A') {
try {
minimal.docs_reference_titles = await resolveReferenceLinksToTitles(
event.docs_reference_links,
titleContext,
)
} catch (error) {
console.warn(
`Failed to resolve titles for event ${event.action}:`,
error instanceof Error ? error.message : String(error),
)
}
}
// we need to initialize as we go to build up the `minimalEvents`
// object that we'll return which will contain the GHES events for
// each versions + page type combos e.g. when processing GHES events
// for the organization events page we'll end up with something like
// this:
//
// {
// 'ghes-3.10': { organization: [Array] },
// 'ghes-3.11': { organization: [Array] },
// 'ghes-3.8': { organization: [Array] },
// 'ghes-3.9': { organization: [Array] }
// }
if (!currentGhesEvents[fullGhesVersion]) {
currentGhesEvents[fullGhesVersion] = {}
currentGhesEvents[fullGhesVersion][auditLogPage] = []
} else {
if (!currentGhesEvents[fullGhesVersion][auditLogPage]) {
currentGhesEvents[fullGhesVersion][auditLogPage] = []
}
}
currentGhesEvents[fullGhesVersion][auditLogPage].push(minimal)
}
}
}
}
// Categorizes the given array of audit log events by event category
function categorizeEvents(events: AuditLogEventT[]) {
const categorizedEvents: CategorizedEvents = {}
events.forEach((event) => {
const [category] = event.action.split('.')
if (!Object.hasOwn(categorizedEvents, category)) {
categorizedEvents[category] = []
}
categorizedEvents[category].push(event)
})
return categorizedEvents
}
function processAndGetEventDescription(
event: AuditLogEventT,
allowlists: string[],
pipelineConfig: PipelineConfig,
) {
let description = event.description
// api.request is a unique event because it's an api_only event but is the only
// one of these events where the description we append isn't correct so we
// have to account for it separately. There's not yet anything in the schema
// we can hook onto to treat it differently.
if (
(allowlists.includes('org_api_only') || allowlists.includes('business_api_only')) &&
event.action !== 'api.request'
) {
description += ` ${pipelineConfig.appendedDescriptions.apiOnlyEvents}`
}
if (event.action === 'api.request') {
description += ` ${pipelineConfig.appendedDescriptions.apiRequestEvent}`
}
return description
}