-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathacl.js
More file actions
369 lines (321 loc) · 10 KB
/
acl.js
File metadata and controls
369 lines (321 loc) · 10 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
exports.allow = allow
var path = require('path')
var $rdf = require('rdflib')
var S = require('string')
var url = require('url')
var async = require('async')
var debug = require('./debug').ACL
var utils = require('./utils.js')
var rdfVocab = require('./vocab/rdf.js')
// TODO should this be set?
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
function match (graph, s, p, o) {
var matches = graph.statementsMatching(
s ? $rdf.sym(s) : undefined,
p ? $rdf.sym(p) : undefined,
o ? $rdf.sym(o) : undefined)
return matches
}
function ACL (opts) {
var self = this
opts = opts || {}
self.fetch = opts.fetch
self.match = opts.match || match
self.suffix = opts.suffix || '.acl'
}
ACL.prototype.isAcl = function (resource) {
return !!S(resource).endsWith(this.suffix)
}
ACL.prototype.can = function (user, mode, resource, callback, options) {
debug('Can ' + (user || 'an agent') + ' ' + mode + ' ' + resource + '?')
var self = this
var accessType = 'accessTo'
var acls = possibleACLs(resource, self.suffix)
options = options || {}
// If it is an ACL, only look for control this resource
if (self.isAcl(resource)) {
mode = 'Control'
}
async.eachSeries(
acls,
// Looks for ACL, if found, looks for a rule
function (acl, next) {
debug('Check if acl exist: ' + acl)
// Let's see if there is a file..
self.fetch(acl, function (err, graph) {
if (err || !graph || graph.statements.length === 0) {
// TODO
// If no file is found and we want to Control,
// we should not be able to do that!
// Control is only to Read and Write the current file!
// if (mode === 'Control') {
// return next(new Error('You can\'t Control an unexisting file'))
// }
if (err) debug('Error: ' + err)
accessType = 'defaultForNew'
return next()
}
self.findRule(
graph, // The ACL graph
user, // The webId of the user
mode, // Read/Write/Append
resource, // The resource we want to access
accessType, // accessTo or defaultForNew
acl, // The current Acl file!
function (err) {
return next(!err || err)
}, options)
})
},
function (err) {
if (err === false || err === null) {
debug('No ACL resource found - access not allowed')
err = new Error('No Access Control Policy found')
}
if (err === true) {
debug('ACL policy found')
err = null
}
if (err) {
debug('Error: ' + err.message)
if (!user || user.length === 0) {
debug('Authentication required')
err.status = 401
err.message = 'Access to ' + resource + ' requires authorization'
} else {
debug(mode + ' access denied for: ' + user)
err.status = 403
err.message = 'Access denied for ' + user
}
}
return callback(err)
})
}
ACL.prototype.findAgentClass = function (graph, user, mode, resource, acl, callback) {
var self = this
// Agent class statement
var agentClassStatements = self.match(
graph,
acl,
'http://www.w3.org/ns/auth/acl#agentClass',
undefined)
if (agentClassStatements.length === 0) {
return callback(false)
}
async.some(agentClassStatements, function (agentClassTriple, found) {
// Check for FOAF groups
debug('Found agentClass policy')
if (agentClassTriple.object.uri === 'http://xmlns.com/foaf/0.1/Agent') {
debug(mode + ' allowed access as FOAF agent')
return found(true)
}
return found(false)
}, callback)
}
ACL.prototype.findRule = function (graph, user, mode, resource, accessType, acl, callback, options) {
var self = this
// TODO check if this is necessary
if (graph.statements.length === 0) {
debug('ACL ' + acl + ' is empty')
return callback(new Error('No policy found'))
}
debug('Found policies in ' + acl)
// Check for mode
var statements = self.getMode(graph, mode)
if (mode === 'Append') {
statements = statements
.concat(self.getMode(graph, 'Write'))
}
async.some(
statements,
function (statement, done) {
var statementSubject = statement.subject.uri
// Check for origin
var matchOrigin = self.matchOrigin(graph, statementSubject, options.origin)
if (!matchOrigin) {
debug('The request does not match the origin')
return done(false)
}
// Check for accessTo/defaultForNew
if (!self.isAcl(resource) || accessType === 'defaultForNew') {
debug('Checking for accessType:' + accessType)
var accesses = self.matchAccessType(graph, statementSubject, accessType, resource)
if (!accesses) {
debug('Cannot find accessType ' + accessType)
return done(false)
}
}
// Check for Agent
var agentStatements = []
if (user) {
agentStatements = self.match(
graph,
statementSubject,
'http://www.w3.org/ns/auth/acl#agent',
user)
}
if (agentStatements.length) {
debug(mode + ' access allowed (as agent) for: ' + user)
return done(true)
}
debug('Inspect agentClass')
// Check for AgentClass
return self.findAgentClass(graph, user, mode, resource, statementSubject, done)
},
function (found) {
if (!found) {
return callback(new Error('Acl found but policy not found'))
}
return callback(null)
})
}
// TODO maybe these functions can be integrated in the code
ACL.prototype.getMode = function getMode (graph, mode) {
var self = this
return self.match(
graph,
undefined,
'http://www.w3.org/ns/auth/acl#mode',
'http://www.w3.org/ns/auth/acl#' + mode)
}
ACL.prototype.matchAccessType = function matchAccessType (graph, rule, accessType, uri) {
var self = this
var matches = self.match(
graph,
rule,
'http://www.w3.org/ns/auth/acl#' + accessType,
undefined)
return matches.some(function (match) {
return S(uri).startsWith(match.object.uri)
})
}
ACL.prototype.matchOrigin = function getOrigins (graph, rule, origin) {
var self = this
var origins = self.match(
graph,
rule,
'http://www.w3.org/ns/auth/acl#origin',
undefined)
if (origins.length) {
return origins.some(function (triple) {
return triple.object.uri === origin
})
}
return true
}
function possibleACLs (uri, suffix) {
var first = S(uri).endsWith(suffix) ? uri : uri + suffix
var urls = [first]
var parsedUri = url.parse(uri)
var baseUrl = (parsedUri.protocol ? parsedUri.protocol + '//' : '') + (parsedUri.host || '')
if (baseUrl + '/' === uri) {
return urls
}
var times = parsedUri.pathname.split('/').length
for (var i = 0; i < times - 1; i++) {
uri = path.dirname(uri)
urls.push(uri + (uri[uri.length - 1] === '/' ? suffix : '/' + suffix))
}
return urls
}
function fetchDocument (host, ldp, baseUri) {
return function (uri, callback) {
var graph = $rdf.graph()
async.waterfall([
function (cb) {
// URL is local
var newPath = S(uri).chompLeft(baseUri).s
// TODO prettify this
var root = !ldp.idp ? ldp.root : ldp.root + host + '/'
var documentPath = utils.uriToFilename(newPath, root)
var documentUri = url.parse(documentPath)
documentPath = documentUri.pathname
return ldp.readFile(documentPath, cb)
},
function (body, cb) {
try {
$rdf.parse(body, graph, uri, 'text/turtle')
} catch (err) {
return cb(err, graph)
}
return cb(null, graph)
}
], callback)
}
}
function getUserId (req, callback) {
var onBehalfOf = req.get('On-Behalf-Of')
if (!onBehalfOf) {
return callback(null, req.session.userId)
}
var delegator = rdfVocab.debrack(onBehalfOf)
verifyDelegator(req.hostname, delegator, req.session.userId, function (err, res) {
if (err) {
err.status = 500
return callback(err)
}
if (res) {
debug('Request User ID (delegation) :' + delegator)
return callback(null, delegator)
}
return callback(null, req.session.userId)
})
}
function verifyDelegator (host, ldp, baseUri, delegator, delegatee, callback) {
fetchDocument(host, ldp, baseUri)(delegator, function (err, delegatorGraph) {
// TODO handle error
if (err) {
err.status = 500
return callback(err)
}
var delegatesStatements = delegatorGraph
.each(delegatorGraph.sym(delegator),
delegatorGraph.sym('http://www.w3.org/ns/auth/acl#delegates'),
undefined)
for (var delegateeIndex in delegatesStatements) {
var delegateeValue = delegatesStatements[delegateeIndex]
if (rdfVocab.debrack(delegateeValue.toString()) === delegatee) {
callback(null, true)
}
}
// TODO check if this should be false
return callback(null, false)
})
}
/**
* Callback used by verifyDelegator.
* @callback ACL~verifyDelegator_cb
* @param {Object} err Error occurred when reading the acl file
* @param {Number} err.status Status code of the error (HTTP way)
* @param {String} err.message Reason of the error
* @param {Boolean} result verification has passed or not
*/
function allow (mode) {
return function (req, res, next) {
var ldp = req.app.locals.ldp
if (!ldp.webid) {
return next()
}
var baseUri = utils.uriBase(req)
var acl = new ACL({
fetch: fetchDocument(req.hostname, ldp, baseUri),
match: match,
suffix: ldp.suffixAcl
})
getUserId(req, function (err, userId) {
if (err) return next(err)
var reqPath = res && res.locals && res.locals.path ? res.locals.path : req.path
ldp.exists(req.hostname, reqPath, function (err, stat) {
if (reqPath[reqPath.length - 1] !== '/' &&
!err &&
stat.isDirectory()) {
reqPath += '/'
}
var options = {
origin: req.get('origin')
}
return acl.can(userId, mode, baseUri + reqPath, next, options)
})
})
}
}