Add more CLI tests
[oweals/peertube.git] / server / helpers / audit-logger.ts
1 import * as path from 'path'
2 import * as express from 'express'
3 import { diff } from 'deep-object-diff'
4 import { chain } from 'lodash'
5 import * as flatten from 'flat'
6 import * as winston from 'winston'
7 import { jsonLoggerFormat, labelFormatter } from './logger'
8 import { User, VideoAbuse, VideoChannel, VideoDetails, VideoImport } from '../../shared'
9 import { VideoComment } from '../../shared/models/videos/video-comment.model'
10 import { CustomConfig } from '../../shared/models/server/custom-config.model'
11 import { CONFIG } from '../initializers/config'
12
13 function getAuditIdFromRes (res: express.Response) {
14   return res.locals.oauth.token.User.username
15 }
16
17 enum AUDIT_TYPE {
18   CREATE = 'create',
19   UPDATE = 'update',
20   DELETE = 'delete'
21 }
22
23 const colors = winston.config.npm.colors
24 colors.audit = winston.config.npm.colors.info
25
26 winston.addColors(colors)
27
28 const auditLogger = winston.createLogger({
29   levels: { audit: 0 },
30   transports: [
31     new winston.transports.File({
32       filename: path.join(CONFIG.STORAGE.LOG_DIR, 'peertube-audit.log'),
33       level: 'audit',
34       maxsize: 5242880,
35       maxFiles: 5,
36       format: winston.format.combine(
37         winston.format.timestamp(),
38         labelFormatter,
39         winston.format.splat(),
40         jsonLoggerFormat
41       )
42     })
43   ],
44   exitOnError: true
45 })
46
47 function auditLoggerWrapper (domain: string, user: string, action: AUDIT_TYPE, entity: EntityAuditView, oldEntity: EntityAuditView = null) {
48   let entityInfos: object
49   if (action === AUDIT_TYPE.UPDATE && oldEntity) {
50     const oldEntityKeys = oldEntity.toLogKeys()
51     const diffObject = diff(oldEntityKeys, entity.toLogKeys())
52     const diffKeys = Object.entries(diffObject).reduce((newKeys, entry) => {
53       newKeys[`new-${entry[0]}`] = entry[1]
54       return newKeys
55     }, {})
56     entityInfos = { ...oldEntityKeys, ...diffKeys }
57   } else {
58     entityInfos = { ...entity.toLogKeys() }
59   }
60   auditLogger.log('audit', JSON.stringify({
61     user,
62     domain,
63     action,
64     ...entityInfos
65   }))
66 }
67
68 function auditLoggerFactory (domain: string) {
69   return {
70     create (user: string, entity: EntityAuditView) {
71       auditLoggerWrapper(domain, user, AUDIT_TYPE.CREATE, entity)
72     },
73     update (user: string, entity: EntityAuditView, oldEntity: EntityAuditView) {
74       auditLoggerWrapper(domain, user, AUDIT_TYPE.UPDATE, entity, oldEntity)
75     },
76     delete (user: string, entity: EntityAuditView) {
77       auditLoggerWrapper(domain, user, AUDIT_TYPE.DELETE, entity)
78     }
79   }
80 }
81
82 abstract class EntityAuditView {
83   constructor (private keysToKeep: Array<string>, private prefix: string, private entityInfos: object) { }
84   toLogKeys (): object {
85     return chain(flatten(this.entityInfos, { delimiter: '-', safe: true }))
86       .pick(this.keysToKeep)
87       .mapKeys((value, key) => `${this.prefix}-${key}`)
88       .value()
89   }
90 }
91
92 const videoKeysToKeep = [
93   'tags',
94   'uuid',
95   'id',
96   'uuid',
97   'createdAt',
98   'updatedAt',
99   'publishedAt',
100   'category',
101   'licence',
102   'language',
103   'privacy',
104   'description',
105   'duration',
106   'isLocal',
107   'name',
108   'thumbnailPath',
109   'previewPath',
110   'nsfw',
111   'waitTranscoding',
112   'account-id',
113   'account-uuid',
114   'account-name',
115   'channel-id',
116   'channel-uuid',
117   'channel-name',
118   'support',
119   'commentsEnabled',
120   'downloadEnabled'
121 ]
122 class VideoAuditView extends EntityAuditView {
123   constructor (private video: VideoDetails) {
124     super(videoKeysToKeep, 'video', video)
125   }
126 }
127
128 const videoImportKeysToKeep = [
129   'id',
130   'targetUrl',
131   'video-name'
132 ]
133 class VideoImportAuditView extends EntityAuditView {
134   constructor (private videoImport: VideoImport) {
135     super(videoImportKeysToKeep, 'video-import', videoImport)
136   }
137 }
138
139 const commentKeysToKeep = [
140   'id',
141   'text',
142   'threadId',
143   'inReplyToCommentId',
144   'videoId',
145   'createdAt',
146   'updatedAt',
147   'totalReplies',
148   'account-id',
149   'account-uuid',
150   'account-name'
151 ]
152 class CommentAuditView extends EntityAuditView {
153   constructor (private comment: VideoComment) {
154     super(commentKeysToKeep, 'comment', comment)
155   }
156 }
157
158 const userKeysToKeep = [
159   'id',
160   'username',
161   'email',
162   'nsfwPolicy',
163   'autoPlayVideo',
164   'role',
165   'videoQuota',
166   'createdAt',
167   'account-id',
168   'account-uuid',
169   'account-name',
170   'account-followingCount',
171   'account-followersCount',
172   'account-createdAt',
173   'account-updatedAt',
174   'account-avatar-path',
175   'account-avatar-createdAt',
176   'account-avatar-updatedAt',
177   'account-displayName',
178   'account-description',
179   'videoChannels'
180 ]
181 class UserAuditView extends EntityAuditView {
182   constructor (private user: User) {
183     super(userKeysToKeep, 'user', user)
184   }
185 }
186
187 const channelKeysToKeep = [
188   'id',
189   'uuid',
190   'name',
191   'followingCount',
192   'followersCount',
193   'createdAt',
194   'updatedAt',
195   'avatar-path',
196   'avatar-createdAt',
197   'avatar-updatedAt',
198   'displayName',
199   'description',
200   'support',
201   'isLocal',
202   'ownerAccount-id',
203   'ownerAccount-uuid',
204   'ownerAccount-name',
205   'ownerAccount-displayedName'
206 ]
207 class VideoChannelAuditView extends EntityAuditView {
208   constructor (private channel: VideoChannel) {
209     super(channelKeysToKeep, 'channel', channel)
210   }
211 }
212
213 const videoAbuseKeysToKeep = [
214   'id',
215   'reason',
216   'reporterAccount',
217   'video-id',
218   'video-name',
219   'video-uuid',
220   'createdAt'
221 ]
222 class VideoAbuseAuditView extends EntityAuditView {
223   constructor (private videoAbuse: VideoAbuse) {
224     super(videoAbuseKeysToKeep, 'abuse', videoAbuse)
225   }
226 }
227
228 const customConfigKeysToKeep = [
229   'instance-name',
230   'instance-shortDescription',
231   'instance-description',
232   'instance-terms',
233   'instance-defaultClientRoute',
234   'instance-defaultNSFWPolicy',
235   'instance-customizations-javascript',
236   'instance-customizations-css',
237   'services-twitter-username',
238   'services-twitter-whitelisted',
239   'cache-previews-size',
240   'cache-captions-size',
241   'signup-enabled',
242   'signup-limit',
243   'signup-requiresEmailVerification',
244   'admin-email',
245   'user-videoQuota',
246   'transcoding-enabled',
247   'transcoding-threads',
248   'transcoding-resolutions'
249 ]
250 class CustomConfigAuditView extends EntityAuditView {
251   constructor (customConfig: CustomConfig) {
252     const infos: any = customConfig
253     const resolutionsDict = infos.transcoding.resolutions
254     const resolutionsArray = []
255     Object.entries(resolutionsDict).forEach(([resolution, isEnabled]) => {
256       if (isEnabled) resolutionsArray.push(resolution)
257     })
258     Object.assign({}, infos, { transcoding: { resolutions: resolutionsArray } })
259     super(customConfigKeysToKeep, 'config', infos)
260   }
261 }
262
263 export {
264   getAuditIdFromRes,
265
266   auditLoggerFactory,
267   VideoImportAuditView,
268   VideoChannelAuditView,
269   CommentAuditView,
270   UserAuditView,
271   VideoAuditView,
272   VideoAbuseAuditView,
273   CustomConfigAuditView
274 }