-
Notifications
You must be signed in to change notification settings - Fork 308
Expand file tree
/
Copy pathacl-checker.js
More file actions
216 lines (197 loc) · 7.73 KB
/
Copy pathacl-checker.js
File metadata and controls
216 lines (197 loc) · 7.73 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
'use strict'
const rdf = require('rdflib')
const debug = require('./debug').ACL
const HTTPError = require('./http-error')
const aclCheck = require('@solid/acl-check')
const { URL } = require('url')
const { promisify } = require('util')
const fs = require('fs')
const Url = require('url')
const httpFetch = require('node-fetch')
const DEFAULT_ACL_SUFFIX = '.acl'
const ACL = rdf.Namespace('http://www.w3.org/ns/auth/acl#')
// An ACLChecker exposes the permissions on a specific resource
class ACLChecker {
constructor (resource, options = {}) {
this.resource = resource
this.resourceUrl = new URL(resource)
this.agentOrigin = options.strictOrigin && options.agentOrigin ? rdf.sym(options.agentOrigin) : null
this.fetch = options.fetch
this.fetchGraph = options.fetchGraph
this.trustedOrigins = options.strictOrigin && options.trustedOrigins ? options.trustedOrigins.map(trustedOrigin => rdf.sym(trustedOrigin)) : null
this.suffix = options.suffix || DEFAULT_ACL_SUFFIX
this.aclCached = {}
this.messagesCached = {}
this.requests = {}
}
// Returns a fulfilled promise when the user can access the resource
// in the given mode, or rejects with an HTTP error otherwise
async can (user, mode) {
const cacheKey = `${mode}-${user}`
if (this.aclCached[cacheKey]) {
return this.aclCached[cacheKey]
}
this.messagesCached[cacheKey] = this.messagesCached[cacheKey] || []
const acl = await this.getNearestACL().catch(err => {
this.messagesCached[cacheKey].push(new HTTPError(err.status || 500, err.message || err))
})
if (!acl) {
this.aclCached[cacheKey] = Promise.resolve(false)
return this.aclCached[cacheKey]
}
let resource = rdf.sym(this.resource)
if (this.resource.endsWith('/' + this.suffix)) {
resource = rdf.sym(ACLChecker.getDirectory(this.resource))
}
// If this is an ACL, Control mode must be present for any operations
if (this.isAcl(this.resource)) {
mode = 'Control'
resource = rdf.sym(this.resource.substring(0, this.resource.length - this.suffix.length))
}
const directory = acl.isContainer ? rdf.sym(ACLChecker.getDirectory(acl.acl)) : null
const aclFile = rdf.sym(acl.acl)
const agent = user ? rdf.sym(user) : null
const modes = [ACL(mode)]
const agentOrigin = this.agentOrigin
const trustedOrigins = this.trustedOrigins
let originTrustedModes = []
try {
this.fetch(aclFile.doc().value)
originTrustedModes = await aclCheck.getTrustedModesForOrigin(acl.graph, resource, directory, aclFile, agentOrigin, (uriNode) => {
return this.fetch(uriNode.doc().value, acl.graph)
})
} catch (e) {
// FIXME: https://github.com/solid/acl-check/issues/23
// console.error(e.message)
}
const accessDenied = aclCheck.accessDenied(acl.graph, resource, directory, aclFile, agent, modes, agentOrigin, trustedOrigins, originTrustedModes)
if (accessDenied && user) {
this.messagesCached[cacheKey].push(HTTPError(403, accessDenied))
} else if (accessDenied) {
this.messagesCached[cacheKey].push(HTTPError(401, 'Unauthenticated'))
}
this.aclCached[cacheKey] = Promise.resolve(!accessDenied)
return this.aclCached[cacheKey]
}
async getError (user, mode) {
const cacheKey = `${mode}-${user}`
this.aclCached[cacheKey] = this.aclCached[cacheKey] || this.can(user, mode)
const isAllowed = await this.aclCached[cacheKey]
return isAllowed ? null : this.messagesCached[cacheKey].reduce((prevMsg, msg) => msg.status > prevMsg.status ? msg : prevMsg, { status: 0 })
}
static getDirectory (aclFile) {
const parts = aclFile.split('/')
parts.pop()
return `${parts.join('/')}/`
}
// Gets the ACL that applies to the resource
async getNearestACL () {
const { resource } = this
let isContainer = false
const possibleACLs = this.getPossibleACLs()
const acls = [...possibleACLs]
let returnAcl = null
while (possibleACLs.length > 0 && !returnAcl) {
const acl = possibleACLs.shift()
let graph
try {
this.requests[acl] = this.requests[acl] || this.fetch(acl)
graph = await this.requests[acl]
} catch (err) {
if (err && (err.code === 'ENOENT' || err.status === 404)) {
isContainer = true
continue
}
debug(err)
throw err
}
const relative = resource.replace(acl.replace(/[^/]+$/, ''), './')
debug(`Using ACL ${acl} for ${relative}`)
returnAcl = { acl, graph, isContainer }
}
if (!returnAcl) {
throw new HTTPError(500, `No ACL found for ${resource}, searched in \n- ${acls.join('\n- ')}`)
}
const groupNodes = returnAcl.graph.statementsMatching(null, ACL('agentGroup'), null)
const groupUrls = groupNodes.map(node => node.object.value.split('#')[0])
await Promise.all(groupUrls.map(groupUrl => {
this.requests[groupUrl] = this.requests[groupUrl] || this.fetch(groupUrl, returnAcl.graph)
return this.requests[groupUrl]
}))
return returnAcl
}
// Gets all possible ACL paths that apply to the resource
getPossibleACLs () {
// Obtain the resource URI and the length of its base
let { resource: uri, suffix } = this
const [{ length: base }] = uri.match(/^[^:]+:\/*[^/]+/)
// If the URI points to a file, append the file's ACL
const possibleAcls = []
if (!uri.endsWith('/')) {
possibleAcls.push(uri.endsWith(suffix) ? uri : uri + suffix)
}
// Append the ACLs of all parent directories
for (let i = lastSlash(uri); i >= base; i = lastSlash(uri, i - 1)) {
possibleAcls.push(uri.substr(0, i + 1) + suffix)
}
return possibleAcls
}
isAcl (resource) {
return resource.endsWith(this.suffix)
}
static createFromLDPAndRequest (resource, ldp, req) {
const trustedOrigins = ldp.getTrustedOrigins(req)
return new ACLChecker(resource, {
agentOrigin: req.get('origin'),
// host: req.get('host'),
fetch: fetchLocalOrRemote(ldp.resourceMapper, ldp.serverUri),
fetchGraph: (uri, options) => {
// first try loading from local fs
return ldp.getGraph(uri, options.contentType)
// failing that, fetch remote graph
.catch(() => ldp.fetchGraph(uri, options))
},
suffix: ldp.suffixAcl,
strictOrigin: ldp.strictOrigin,
trustedOrigins
})
}
}
/**
* Returns a fetch document handler used by the ACLChecker to fetch .acl
* resources up the inheritance chain.
* The `fetch(uri, callback)` results in the callback, with either:
* - `callback(err, graph)` if any error is encountered, or
* - `callback(null, graph)` with the parsed RDF graph of the fetched resource
* @return {Function} Returns a `fetch(uri, callback)` handler
*/
function fetchLocalOrRemote (mapper, serverUri) {
return async function fetch (url, graph = rdf.graph()) {
// Convert the URL into a filename
let body, path, contentType
if (Url.parse(url).host.includes(Url.parse(serverUri).host)) {
// Fetch the acl from local
try {
({ path, contentType } = await mapper.mapUrlToFile({ url }))
} catch (err) {
throw new HTTPError(404, err)
}
// Read the file from disk
body = await promisify(fs.readFile)(path, { 'encoding': 'utf8' })
} else {
// Fetch the acl from the internet
const response = await httpFetch(url)
body = await response.text()
contentType = response.headers.get('content-type')
}
// Parse the file as Turtle
rdf.parse(body, graph, url, contentType)
return graph
}
}
// Returns the index of the last slash before the given position
function lastSlash (string, pos = string.length) {
return string.lastIndexOf('/', pos)
}
module.exports = ACLChecker
module.exports.DEFAULT_ACL_SUFFIX = DEFAULT_ACL_SUFFIX