Skip to content

Commit 5d87b50

Browse files
committed
Fix relative IRI resolution in Turtle/SPARQL parsing
RDFTurtle.ParseURI rejected virtually every non-absolute <IRI> reference, which made the W3C SPARQL 1.1 test suite (built almost entirely on relative IRIs) unrunnable against this parser.
1 parent b78198e commit 5d87b50

3 files changed

Lines changed: 146 additions & 19 deletions

File tree

‎RDFSharp.Test/Model/Serializers/RDFTurtleTest.cs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2239,6 +2239,31 @@ public void ShouldThrowExceptionOnDeserializingGraphWithSPOTripleBecauseEmptyDir
22392239
Assert.ThrowsExactly<RDFModelException>(() => RDFTurtle.Deserialize(new MemoryStream(stream.ToArray()), null));
22402240
}
22412241

2242+
[TestMethod]
2243+
public void ShouldThrowExceptionOnDeserializingGraphWithSPOTripleBecauseIriReferenceContainsIllegalCharacter()
2244+
{
2245+
//IRIREF grammar forbids a raw, unescaped '{' inside '<...>': an unterminated/garbled reference must be
2246+
//rejected explicitly rather than relying on it accidentally failing Uri well-formedness downstream
2247+
MemoryStream stream = new MemoryStream();
2248+
using (StreamWriter writer = new StreamWriter(stream))
2249+
writer.WriteLine("<http://subj/{bad}> <http://pred/> <http://obj/>.");
2250+
Assert.ThrowsExactly<RDFModelException>(() => RDFTurtle.Deserialize(new MemoryStream(stream.ToArray()), null));
2251+
}
2252+
2253+
[TestMethod]
2254+
public void ShouldDeserializeGraphWithSPOTripleUsingDotSegmentRelativeIri()
2255+
{
2256+
//Relative references are resolved via RFC 3986 §5.3 (dot-segment removal), not naive string concatenation
2257+
MemoryStream stream = new MemoryStream();
2258+
using (StreamWriter writer = new StreamWriter(stream))
2259+
writer.WriteLine($"@base <http://example.org/a/b/c>.{Environment.NewLine}<../sibling> <http://pred/> <http://obj/>.");
2260+
RDFGraph graph = RDFTurtle.Deserialize(new MemoryStream(stream.ToArray()), null);
2261+
2262+
Assert.IsNotNull(graph);
2263+
Assert.AreEqual(1, graph.TriplesCount);
2264+
Assert.IsTrue(graph.ContainsTriple(new RDFTriple(new RDFResource("http://example.org/a/sibling"), new RDFResource("http://pred/"), new RDFResource("http://obj/"))));
2265+
}
2266+
22422267
[TestMethod]
22432268
public void ShouldThrowExceptionOnDeserializingGraphWithSPOTripleBecauseUnrecognizedDirective()
22442269
{

‎RDFSharp.Test/Query/Parser/Grammar/RDFQueryParser.PrefixedNamesTest.cs‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,74 @@ public void ShouldResolveRelativeIriReferenceAgainstBase()
115115
Assert.AreEqual("http://example.org/test", PatternsOf(query).Single().Predicate.ToString());
116116
}
117117

118+
[TestMethod]
119+
public void ShouldResolveSameDocumentRelativeIriReferenceAgainstBase()
120+
{
121+
//An empty relative reference '<>' (RFC 3986 same-document reference) resolves to the base IRI itself
122+
RDFSelectQuery query = RDFSelectQuery.FromString(
123+
"BASE <http://example.org/base> SELECT * WHERE { ?s <> ?o }");
124+
125+
Assert.AreEqual("http://example.org/base", PatternsOf(query).Single().Predicate.ToString());
126+
}
127+
128+
[TestMethod]
129+
public void ShouldResolveFragmentOnlyRelativeIriReferenceAgainstBase()
130+
{
131+
//A fragment-only relative reference '<#frag>' keeps the base path and replaces only the fragment
132+
RDFSelectQuery query = RDFSelectQuery.FromString(
133+
"BASE <http://example.org/base> SELECT * WHERE { ?s <#frag> ?o }");
134+
135+
Assert.AreEqual("http://example.org/base#frag", PatternsOf(query).Single().Predicate.ToString());
136+
}
137+
138+
[TestMethod]
139+
public void ShouldResolveAbsolutePathRelativeIriReferenceAgainstBase()
140+
{
141+
//An absolute-path reference '</other>' keeps scheme+authority and replaces the whole path
142+
RDFSelectQuery query = RDFSelectQuery.FromString(
143+
"BASE <http://example.org/some/deep/path> SELECT * WHERE { ?s </other> ?o }");
144+
145+
Assert.AreEqual("http://example.org/other", PatternsOf(query).Single().Predicate.ToString());
146+
}
147+
148+
[TestMethod]
149+
public void ShouldResolveNetworkPathRelativeIriReferenceAgainstBase()
150+
{
151+
//A network-path reference '<//other.org/path>' keeps the scheme and replaces authority+path
152+
RDFSelectQuery query = RDFSelectQuery.FromString(
153+
"BASE <http://example.org/base/> SELECT * WHERE { ?s <//other.org/path> ?o }");
154+
155+
Assert.AreEqual("http://other.org/path", PatternsOf(query).Single().Predicate.ToString());
156+
}
157+
158+
[TestMethod]
159+
public void ShouldResolveDotSegmentRelativeIriReferenceAgainstBase()
160+
{
161+
//A relative reference with '..' is resolved via RFC 3986 dot-segment removal, not string concatenation
162+
RDFSelectQuery query = RDFSelectQuery.FromString(
163+
"BASE <http://example.org/a/b/c> SELECT * WHERE { ?s <../sibling> ?o }");
164+
165+
Assert.AreEqual("http://example.org/a/sibling", PatternsOf(query).Single().Predicate.ToString());
166+
}
167+
168+
[TestMethod]
169+
public void ShouldResolveQueryOnlyRelativeIriReferenceAgainstBase()
170+
{
171+
//A query-only reference '<?new=2>' keeps the base path and replaces only the query string
172+
RDFSelectQuery query = RDFSelectQuery.FromString(
173+
"BASE <http://example.org/base?old=1> SELECT * WHERE { ?s <?new=2> ?o }");
174+
175+
Assert.AreEqual("http://example.org/base?new=2", PatternsOf(query).Single().Predicate.ToString());
176+
}
177+
178+
[TestMethod]
179+
public void ShouldThrowOnRelativeIriReferenceWithoutAnyBase()
180+
{
181+
//No BASE was declared and none was supplied externally: a relative reference has nothing to resolve against
182+
Assert.ThrowsExactly<RDFQueryException>(() =>
183+
RDFSelectQuery.FromString("SELECT * WHERE { ?s <test> ?o }"));
184+
}
185+
118186
[TestMethod]
119187
public void ShouldResolveDefaultPrefixedNameAgainstBase()
120188
{

‎RDFSharp/Model/Serializers/RDFTurtle.cs‎

Lines changed: 53 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -766,7 +766,7 @@ internal static void ParseBase(RDFTurtleContext turtleContext, RDFGraph result)
766766
}
767767

768768
/// <summary>
769-
/// Parses the Turtle data in order to detect a valid Uri
769+
/// Parses an IRIREF ("&lt;...&gt;"), resolving it against the current base Uri if relative
770770
/// </summary>
771771
internal static Uri ParseURI(RDFTurtleContext turtleContext)
772772
{
@@ -783,13 +783,12 @@ internal static Uri ParseURI(RDFTurtleContext turtleContext)
783783
if (bufChar == '>')
784784
break;
785785

786-
switch (bufChar)
787-
{
788-
case -1:
789-
throw new RDFModelException("Unexpected end of Turtle file" + GetTurtleContextCoordinates(turtleContext));
790-
case ' ':
791-
throw new RDFModelException("Uri included an unencoded space: '" + bufChar + "'" + GetTurtleContextCoordinates(turtleContext));
792-
}
786+
if (bufChar == -1)
787+
throw new RDFModelException("Unexpected end of Turtle file" + GetTurtleContextCoordinates(turtleContext));
788+
789+
//Control chars (space included) and '<"{}|^`' are illegal unescaped inside an IRIREF
790+
if (bufChar <= 0x20 || bufChar == '<' || bufChar == '"' || bufChar == '{' || bufChar == '}' || bufChar == '|' || bufChar == '^' || bufChar == '`')
791+
throw new RDFModelException("Uri included an illegal character: '" + char.ConvertFromUtf32(bufChar) + "'" + GetTurtleContextCoordinates(turtleContext));
793792

794793
AppendCodePoint(uriBuf, bufChar);
795794

@@ -807,17 +806,52 @@ internal static Uri ParseURI(RDFTurtleContext turtleContext)
807806
}
808807

809808
string uriString = DecodeString(turtleContext, uriBuf.ToString());
810-
//Absolute: use as found
811-
if (Uri.IsWellFormedUriString(uriString, UriKind.Absolute))
812-
return new Uri(uriString);
813-
//Relative: append to base IRI
814-
if (Uri.IsWellFormedUriString(uriString, UriKind.Relative))
815-
return new Uri(string.Concat(turtleContext.Resolver.BaseUri, uriString));
816-
//PureFragment: append to base IRI
817-
return uriString.Equals("#")
818-
? new Uri(string.Concat(turtleContext.Resolver.BaseUri.TrimEnd('#'), uriString))
819-
//Error: not well-formed, so throw exception
820-
: throw new RDFModelException("Uri is not well-formed" + GetTurtleContextCoordinates(turtleContext));
809+
810+
//An IRI reference is absolute per RFC 3986 iff it opens with a genuine "scheme:" prefix
811+
if (HasSchemePrefix(uriString))
812+
{
813+
//Uri.TryCreate(..., UriKind.Absolute) alone is not enough here: it also accepts scheme-less
814+
//OS-style paths like "/x" or "//host/x" by silently assigning them an implicit "file" scheme
815+
if (!Uri.TryCreate(uriString, UriKind.Absolute, out Uri absoluteUri))
816+
throw new RDFModelException("Uri is not well-formed" + GetTurtleContextCoordinates(turtleContext));
817+
return absoluteUri;
818+
}
819+
820+
//No scheme: it is a relative reference, resolvable only against a base Uri
821+
if (string.IsNullOrEmpty(turtleContext.Resolver.BaseUri)
822+
|| !Uri.TryCreate(turtleContext.Resolver.BaseUri, UriKind.Absolute, out Uri baseUri))
823+
throw new RDFModelException("Found relative Uri reference '" + uriString + "' with no usable base Uri to resolve it against" + GetTurtleContextCoordinates(turtleContext));
824+
825+
//The two-argument Uri resolution already implements RFC 3986 §5.3 (dot-segment removal, '#'/'?'/'/'/'//' references, ...)
826+
if (!Uri.TryCreate(baseUri, uriString, out Uri resolvedUri))
827+
throw new RDFModelException("Uri is not well-formed" + GetTurtleContextCoordinates(turtleContext));
828+
return resolvedUri;
829+
830+
#region Utilities
831+
//True iff the string opens with an RFC 3986 scheme ("ALPHA *(ALPHA / DIGIT / '+' / '-' / '.') ':'")
832+
bool HasSchemePrefix(string candidateUriString)
833+
{
834+
int colonIndex = candidateUriString.IndexOf(':');
835+
if (colonIndex <= 0)
836+
return false;
837+
838+
//First scheme character must be a letter
839+
char firstChar = candidateUriString[0];
840+
if ((firstChar < 'a' || firstChar > 'z') && (firstChar < 'A' || firstChar > 'Z'))
841+
return false;
842+
843+
//The rest may also contain digits, '+', '-', '.'
844+
for (int i = 1; i < colonIndex; i++)
845+
{
846+
char c = candidateUriString[i];
847+
bool isSchemeChar = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
848+
|| c == '+' || c == '-' || c == '.';
849+
if (!isSchemeChar)
850+
return false;
851+
}
852+
return true;
853+
}
854+
#endregion
821855
}
822856

823857
/// <summary>

0 commit comments

Comments
 (0)