forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-domain.js
More file actions
326 lines (297 loc) · 9.85 KB
/
Copy pathcreate-domain.js
File metadata and controls
326 lines (297 loc) · 9.85 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
import { GraphQLNonNull, GraphQLList, GraphQLID, GraphQLBoolean, GraphQLString } from 'graphql'
import { mutationWithClientMutationId, fromGlobalId } from 'graphql-relay'
import { t } from '@lingui/macro'
import { createDomainUnion } from '../unions'
import { Domain } from '../../scalars'
import { logActivity } from '../../audit-logs/mutations/log-activity'
import { AssetStateEnums } from '../../enums'
import { headers } from 'nats'
export const createDomain = new mutationWithClientMutationId({
name: 'CreateDomain',
description: 'Mutation used to create a new domain for an organization.',
inputFields: () => ({
orgId: {
type: new GraphQLNonNull(GraphQLID),
description: 'The global id of the organization you wish to assign this domain to.',
},
domain: {
type: new GraphQLNonNull(Domain),
description: 'Url that you would like to be added to the database.',
},
tags: {
description: 'List of labelled tags users have applied to the domain.',
type: new GraphQLList(GraphQLString),
},
archived: {
description: 'Value that determines if the domain is excluded from the scanning process.',
type: GraphQLBoolean,
},
assetState: {
description: 'Value that determines how the domain relates to the organization.',
type: new GraphQLNonNull(AssetStateEnums),
},
}),
outputFields: () => ({
result: {
type: createDomainUnion,
description: '`CreateDomainUnion` returning either a `Domain`, or `CreateDomainError` object.',
resolve: (payload) => payload,
},
}),
mutateAndGetPayload: async (
args,
{
i18n,
request,
query,
collections,
transaction,
userKey,
publish,
auth: { checkPermission, saltedHash, userRequired, tfaRequired, verifiedRequired },
loaders: { loadDomainByDomain, loadOrgByKey, loadTagByTagId },
validators: { cleanseInput },
},
) => {
// Get User
const user = await userRequired()
verifiedRequired({ user })
tfaRequired({ user })
// Cleanse input
const { type: _orgType, id: orgId } = fromGlobalId(cleanseInput(args.orgId))
const domain = cleanseInput(args.domain)
let tags
if (typeof args.tags !== 'undefined') {
tags = await loadTagByTagId.loadMany(
args.tags.map((tag) => {
return cleanseInput(tag)
}),
)
tags = tags
.filter(({ visible, ownership, organizations }) => {
// Filter out tags that are not visible or do not belong to the org
return visible && (ownership === 'global' || organizations.some((org) => org._id === orgId))
})
.map((tag) => tag.tagId)
} else {
tags = []
}
let archived
if (typeof args.archived !== 'undefined') {
archived = args.archived
} else {
archived = false
}
let assetState
if (typeof args.assetState !== 'undefined') {
assetState = cleanseInput(args.assetState)
} else {
assetState = ''
}
// Check to see if org exists
const org = await loadOrgByKey.load(orgId)
if (typeof org === 'undefined') {
console.warn(`User: ${userKey} attempted to create a domain to an organization: ${orgId} that does not exist.`)
return {
_type: 'error',
code: 400,
description: i18n._(t`Unable to create domain in unknown organization.`),
}
}
// Check to see if user belongs to org
const permission = await checkPermission({ orgId: org._id })
if (!['admin', 'owner', 'super_admin'].includes(permission)) {
console.warn(
`User: ${userKey} attempted to create a domain in: ${org.slug}, however they do not have permission to do so.`,
)
return {
_type: 'error',
code: 400,
description: i18n._(t`Permission Denied: Please contact organization user for help with creating domain.`),
}
}
const insertDomain = {
domain: domain.toLowerCase(),
lastRan: null,
hash: saltedHash(domain.toLowerCase()),
status: {
certificates: 'info',
ciphers: 'info',
curves: 'info',
dkim: 'info',
dmarc: 'info',
hsts: 'info',
https: 'info',
protocols: 'info',
spf: 'info',
ssl: 'info',
},
archived: archived,
ignoreRua: false,
}
// Check to see if domain already belongs to same org
let checkDomainCursor
try {
checkDomainCursor = await query`
WITH claims, domains, organizations
LET domainIds = (FOR domain IN domains FILTER domain.domain == ${insertDomain.domain} RETURN { id: domain._id })
FOR domainId IN domainIds
LET domainEdges = (FOR v, e IN 1..1 ANY domainId.id claims RETURN { _from: e._from })
FOR domainEdge IN domainEdges
LET org = DOCUMENT(domainEdge._from)
FILTER org._key == ${org._key}
RETURN MERGE({ _id: org._id, _key: org._key, _rev: org._rev }, TRANSLATE(${request.language}, org.orgDetails))
`
} catch (err) {
console.error(`Database error occurred while running check to see if domain already exists in an org: ${err}`)
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
let checkOrgDomain
try {
checkOrgDomain = await checkDomainCursor.next()
} catch (err) {
console.error(`Cursor error occurred while running check to see if domain already exists in an org: ${err}`)
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
if (typeof checkOrgDomain !== 'undefined') {
console.warn(
`User: ${userKey} attempted to create a domain for: ${org.slug}, however that org already has that domain claimed.`,
)
return {
_type: 'error',
code: 400,
description: i18n._(t`Unable to create domain, organization has already claimed it.`),
}
}
// Setup Transaction
const trx = await transaction(collections)
let domainCursor
try {
domainCursor = await trx.step(
() =>
query`
UPSERT { domain: ${insertDomain.domain} }
INSERT ${insertDomain}
UPDATE { }
IN domains
RETURN NEW
`,
)
} catch (err) {
console.error(`Transaction step error occurred for user: ${userKey} when inserting new domain: ${err}`)
await trx.abort()
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
let insertedDomain
try {
insertedDomain = await domainCursor.next()
} catch (err) {
console.error(`Cursor error occurred for user: ${userKey} when inserting new domain: ${err}`)
await trx.abort()
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
try {
await trx.step(
() =>
query`
WITH claims
INSERT {
_from: ${org._id},
_to: ${insertedDomain._id},
tags: ${tags},
assetState: ${assetState},
firstSeen: ${new Date().toISOString()},
} INTO claims
`,
)
} catch (err) {
console.error(`Transaction step error occurred for user: ${userKey} when inserting new domain edge: ${err}`)
await trx.abort()
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
try {
await trx.commit()
} catch (err) {
console.error(`Transaction commit error occurred while user: ${userKey} was creating domain: ${err}`)
await trx.abort()
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
// Clear dataloader incase anything was updated or inserted into domain
await loadDomainByDomain.clear(insertDomain.domain)
const returnDomain = await loadDomainByDomain.load(insertDomain.domain)
console.info(`User: ${userKey} successfully created ${returnDomain.domain} in org: ${org.slug}.`)
const updatedProperties = []
if (typeof tags !== 'undefined' && tags.length > 0) {
updatedProperties.push({
name: 'tags',
oldValue: [],
newValue: tags,
})
}
if (typeof assetState !== 'undefined') {
updatedProperties.push({
name: 'assetState',
oldValue: null,
newValue: assetState,
})
}
await logActivity({
transaction,
collections,
query,
initiatedBy: {
id: user._key,
userName: user.userName,
role: permission,
ipAddress: request.ip,
},
action: 'add',
target: {
resource: insertDomain.domain,
updatedProperties,
organization: {
id: org._key,
name: org.name,
}, // name of resource being acted upon
resourceType: 'domain', // user, org, domain
},
})
const hdrs = headers()
hdrs.set('priority', 'high')
try {
await publish({
channel: 'scans.requests_priority',
msg: {
domain: returnDomain.domain,
domain_key: returnDomain._key,
hash: returnDomain.hash,
user_key: null, // only used for One Time Scans
shared_id: null, // only used for One Time Scans
},
options: {
headers: hdrs,
},
})
} catch (err) {
console.error(`Error publishing to NATS for domain ${returnDomain._key}: ${err}`)
}
try {
await publish({
channel: 'scans.add_domain_to_easm',
msg: {
domain: returnDomain.domain,
domain_key: returnDomain._key,
hash: returnDomain.hash,
user_key: null, // only used for One Time Scans
shared_id: null, // only used for One Time Scans
},
})
} catch (err) {
console.error(`Error publishing to NATS for domain ${returnDomain._key}: ${err}`)
}
return {
...returnDomain,
claimTags: tags,
}
},
})