-
Notifications
You must be signed in to change notification settings - Fork 18
/
Iri.scala
334 lines (295 loc) · 12.1 KB
/
Iri.scala
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
/*
* Copyright © 2021 - 2023 Swiss National Data and Service Center for the Humanities and/or DaSCH Service Platform contributors.
* SPDX-License-Identifier: Apache-2.0
*/
package dsp.valueobjects
import com.google.gwt.safehtml.shared.UriUtils.encodeAllowEscapes
import org.apache.commons.lang3.StringUtils
import org.apache.commons.validator.routines.UrlValidator
import zio.json.JsonDecoder
import zio.json.JsonEncoder
import zio.prelude.Validation
import scala.util.Try
import dsp.errors.BadRequestException
import dsp.errors.ValidationException
trait Iri {
val value: String
}
object Iri {
type IRI = String
// A validator for URLs
val urlValidator =
new UrlValidator(
Array("http", "https"), // valid URL schemes
UrlValidator.ALLOW_LOCAL_URLS // local URLs are URL-encoded IRIs as part of the whole URL
)
object KnoraInternal {
// The start and end of an internal Knora ontology IRI.
val InternalOntologyStart = "http://www.knora.org/ontology"
}
val KnoraAdminOntologyLabel: String = "knora-admin"
val KnoraAdminOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + KnoraAdminOntologyLabel
val KnoraAdminPrefixExpansion: IRI = KnoraAdminOntologyIri + "#"
val SystemProject: IRI = KnoraAdminPrefixExpansion + "SystemProject"
val DefaultSharedOntologiesProject: IRI = KnoraAdminPrefixExpansion + "DefaultSharedOntologiesProject"
// Characters that are escaped in strings that will be used in SPARQL.
private val SparqlEscapeInput = Array("\\", "\"", "'", "\t", "\n")
// Escaped characters as they are used in SPARQL.
private val SparqlEscapeOutput = Array("\\\\", "\\\"", "\\'", "\\t", "\\n")
/**
* Returns `true` if a string is an IRI.
*
* @param s the string to be checked.
* @return `true` if the string is an IRI.
*/
def isIri(s: String): Boolean =
urlValidator.isValid(s)
/**
* Returns `true` if an IRI string looks like a Knora list IRI.
*
* @param iri the IRI to be checked.
*/
def isListIri(iri: IRI): Boolean =
isIri(iri) && iri.startsWith("http://rdfh.ch/lists/")
/**
* Returns `true` if an IRI string looks like a Knora role IRI.
*
* @param iri the IRI to be checked.
*/
private def isRoleIri(iri: IRI): Boolean =
isIri(iri) && iri.startsWith("http://rdfh.ch/roles/")
/**
* Returns `true` if an IRI string looks like a Knora user IRI.
*
* @param iri the IRI to be checked.
*/
def isUserIri(iri: IRI): Boolean =
isIri(iri) && iri.startsWith("http://rdfh.ch/users/")
/**
* Returns `true` if an IRI string looks like a Knora group IRI.
*
* @param iri the IRI to be checked.
*/
def isGroupIri(iri: IRI): Boolean =
isIri(iri) && iri.startsWith("http://rdfh.ch/groups/")
/**
* Returns `true` if an IRI string looks like a Knora project IRI
*
* @param iri the IRI to be checked.
*/
def isProjectIri(iri: IRI): Boolean =
iri.startsWith("http://rdfh.ch/projects/") || isBuiltInProjectIri(iri)
/**
* Returns `true` if an IRI string looks like a Knora built-in IRI:
* - http://www.knora.org/ontology/knora-admin#SystemProject
* - http://www.knora.org/ontology/knora-admin#SharedOntologiesProject
*
* @param iri the IRI to be checked.
*/
private def isBuiltInProjectIri(iri: IRI): Boolean = {
val builtInProjects = Seq(SystemProject, DefaultSharedOntologiesProject)
isIri(iri) && builtInProjects.contains(iri)
}
/**
* Returns `true` if an IRI string looks like a Knora permission IRI.
*
* @param iri the IRI to be checked.
*/
def isPermissionIri(iri: IRI): Boolean =
isIri(iri) && iri.startsWith("http://rdfh.ch/permissions/")
/**
* Makes a string safe to be entered in the triplestore by escaping special chars.
*
* @param s a string.
* @return the same string escaped
* [[None]] if the string is empty or contains a carriage return (`\r`).
*/
def toSparqlEncodedString(s: String): Option[String] =
if (s.isEmpty || s.contains("\r")) None
else Some(StringUtils.replaceEach(s, SparqlEscapeInput, SparqlEscapeOutput))
/**
* Unescapes a string that has been escaped for SPARQL.
*
* @param s the string to be unescaped.
* @return the unescaped string.
*/
def fromSparqlEncodedString(s: String): String =
StringUtils.replaceEach(s, SparqlEscapeOutput, SparqlEscapeInput)
// TODO-mpro: Findings about fromSparqlEncodedString method:
// - there is more cases to handle according to docs (https://www.w3.org/TR/rdf-sparql-query#grammarEscapes) - we use 1.1 version right?
// - `'` doesn't appear on that list, but this method escapes it
// - why `\r` throws error instead of being escaped?
// - fun fact is that if I remove StringUtils.replaceEach, for example `\t` passes unescaped, why?
/**
* Checks that a string represents a valid IRI.
* Also encodes the IRI, preserving existing %-escapes.
*
* @param s the string to be checked.
* @return A validated and escaped IRI.
*/
def validateAndEscapeIri(s: String): Validation[ValidationException, String] =
Validation
.fromTry(Try(encodeAllowEscapes(s)).filter(urlValidator.isValid))
.mapError(_ => ValidationException(s"Invalid IRI: $s"))
/**
* Check that the supplied IRI represents a valid project IRI.
*
* @param iri the string to be checked.
* @return the same string but escaped.
*/
def validateAndEscapeProjectIri(iri: IRI): Option[IRI] =
if (isProjectIri(iri)) toSparqlEncodedString(iri)
else None
/**
* Check that the supplied IRI represents a valid user IRI.
*
* @param iri the string to be checked.
* @return the same string but escaped.
*/
def validateAndEscapeUserIri(iri: IRI): Option[String] =
if (isUserIri(iri)) toSparqlEncodedString(iri)
else None
/**
* GroupIri value object.
*/
sealed abstract case class GroupIri private (value: String) extends Iri
object GroupIri { self =>
def make(value: String): Validation[Throwable, GroupIri] =
if (value.isEmpty) Validation.fail(BadRequestException(IriErrorMessages.GroupIriMissing))
else {
val isUuid: Boolean = UuidUtil.hasValidLength(value.split("/").last)
if (!isGroupIri(value))
Validation.fail(BadRequestException(IriErrorMessages.GroupIriInvalid))
else if (isUuid && !UuidUtil.hasSupportedVersion(value))
Validation.fail(BadRequestException(IriErrorMessages.UuidVersionInvalid))
else
validateAndEscapeIri(value)
.mapError(_ => BadRequestException(IriErrorMessages.GroupIriInvalid))
.map(new GroupIri(_) {})
}
def make(value: Option[String]): Validation[Throwable, Option[GroupIri]] =
value match {
case Some(v) => self.make(v).map(Some(_))
case None => Validation.succeed(None)
}
}
/**
* ListIri value object.
*/
sealed abstract case class ListIri private (value: String) extends Iri
object ListIri { self =>
def make(value: String): Validation[Throwable, ListIri] =
if (value.isEmpty) Validation.fail(BadRequestException(IriErrorMessages.ListIriMissing))
else {
val isUuid: Boolean = UuidUtil.hasValidLength(value.split("/").last)
if (!isListIri(value))
Validation.fail(BadRequestException(IriErrorMessages.ListIriInvalid))
else if (isUuid && !UuidUtil.hasSupportedVersion(value))
Validation.fail(BadRequestException(IriErrorMessages.UuidVersionInvalid))
else
validateAndEscapeIri(value)
.mapError(_ => BadRequestException(IriErrorMessages.ListIriInvalid))
.map(new ListIri(_) {})
}
def make(value: Option[String]): Validation[Throwable, Option[ListIri]] =
value match {
case Some(v) => self.make(v).map(Some(_))
case None => Validation.succeed(None)
}
}
/**
* Base64Uuid value object.
* This is base64 encoded UUID version without paddings.
*
* @param value to validate.
*/
sealed abstract case class Base64Uuid private (value: String)
object Base64Uuid {
def make(value: String): Validation[ValidationException, Base64Uuid] =
if (value.isEmpty) {
Validation.fail(ValidationException(IriErrorMessages.UuidMissing))
} else if (!UuidUtil.hasValidLength(value)) {
Validation.fail(ValidationException(IriErrorMessages.UuidInvalid(value)))
} else if (!UuidUtil.hasSupportedVersion(value)) {
Validation.fail(ValidationException(IriErrorMessages.UuidVersionInvalid))
} else Validation.succeed(new Base64Uuid(value) {})
}
/**
* RoleIri value object.
*/
sealed abstract case class RoleIri private (value: String) extends Iri
object RoleIri {
def make(value: String): Validation[Throwable, RoleIri] =
if (value.isEmpty) Validation.fail(BadRequestException(IriErrorMessages.RoleIriMissing))
else {
val isUuid: Boolean = UuidUtil.hasValidLength(value.split("/").last)
if (!isRoleIri(value))
Validation.fail(BadRequestException(IriErrorMessages.RoleIriInvalid(value)))
else if (isUuid && !UuidUtil.hasSupportedVersion(value))
Validation.fail(BadRequestException(IriErrorMessages.UuidVersionInvalid))
else
validateAndEscapeIri(value)
.mapError(_ => BadRequestException(IriErrorMessages.RoleIriInvalid(value)))
.map(new RoleIri(_) {})
}
}
/**
* UserIri value object.
*/
sealed abstract case class UserIri private (value: String) extends Iri
object UserIri {
implicit val decoder: JsonDecoder[UserIri] =
JsonDecoder[String].mapOrFail(value => UserIri.make(value).toEitherWith(e => e.head.getMessage))
implicit val encoder: JsonEncoder[UserIri] = JsonEncoder[String].contramap((userIri: UserIri) => userIri.value)
def make(value: String): Validation[Throwable, UserIri] =
if (value.isEmpty) Validation.fail(BadRequestException(IriErrorMessages.UserIriMissing))
else {
val isUuid: Boolean = UuidUtil.hasValidLength(value.split("/").last)
if (!isUserIri(value))
Validation.fail(BadRequestException(IriErrorMessages.UserIriInvalid(value)))
else if (isUuid && !UuidUtil.hasSupportedVersion(value))
Validation.fail(BadRequestException(IriErrorMessages.UuidVersionInvalid))
else
Validation
.fromOption(validateAndEscapeUserIri(value))
.mapError(_ => BadRequestException(IriErrorMessages.UserIriInvalid(value)))
.map(new UserIri(_) {})
}
}
/**
* PropertyIri value object.
*/
sealed abstract case class PropertyIri private (value: String) extends Iri
object PropertyIri {
def make(value: String): Validation[Throwable, PropertyIri] =
if (value.isEmpty) {
Validation.fail(BadRequestException(IriErrorMessages.PropertyIriMissing))
} else {
// TODO all the following needs to be checked when validating a property iri (see string formatter for the implementations of these methods)
// if (
// !(propertyIri.isKnoraApiV2EntityIri &&
// propertyIri.getOntologySchema.contains(ApiV2Complex) &&
// propertyIri.getOntologyFromEntity == externalOntologyIri)
// ) {
// throw BadRequestException(s"Invalid property IRI: $propertyIri")
// }
Validation.succeed(new PropertyIri(value) {})
}
}
}
object IriErrorMessages {
val GroupIriMissing = "Group IRI cannot be empty."
val GroupIriInvalid = "Group IRI is invalid."
val ListIriMissing = "List IRI cannot be empty."
val ListIriInvalid = "List IRI is invalid"
val ProjectIriMissing = "Project IRI cannot be empty."
val ProjectIriInvalid = "Project IRI is invalid."
val RoleIriMissing = "Role IRI cannot be empty."
val RoleIriInvalid = (iri: String) => s"Role IRI: $iri is invalid."
val UserIriMissing = "User IRI cannot be empty."
val UserIriInvalid = (iri: String) => s"User IRI: $iri is invalid."
val UuidMissing = "UUID cannot be empty"
val UuidInvalid = (uuid: String) => s"'$uuid' is not a UUID"
val UuidVersionInvalid = "Invalid UUID used to create IRI. Only versions 4 and 5 are supported."
val PropertyIriMissing = "Property IRI cannot be empty."
}