Wednesday, September 30, 2009

Security via SPARQL Expression Parsing

Some common questions that often arise in the context of wanting to secure a SPARQL service are:

  • How do I prevent the execution of SPARQL INSERT and DELETE commands?
  • How do I protect certain graphs in model from being accessed?

An easy way to implement application level security in your services is to parse the incoming SPARQL query into an expression tree and interrogate it and either reject the query or modify it before allowing it to be executed. This is accomplished in the Semantics.SDK by using the SparqlExpression class.

The code snip below shows how to prevent INSERT and DELETE queries from being executed by first parsing a SPARQL query string and then examining its command type.

using Intellidimension.Sparql;

SparqlExpression expr = SparqlExpression.Parse(
    "delete from <data> {?s ?p ?o} from <data> where {?s ?p ?o}");

if (expr.Command is CommandDelete || expr.Command is CommandInsert)
    throw new Exception("Access denied!");


Access to a particular graph can be prevented by checking the graphs that are specified in the FROM or FROM NAMED clause of a SPARQL query. This can be accomplished using an expression by testing both the DefaultGraphs and NamedGraphs collections on the command.

SparqlExpression expr = SparqlExpression.Parse(
    "select ?s ?p ?o from <admin> where {?s ?p ?o}");

if (expr.Command.DefaultGraphs.Contains("admin") || 
    expr.Command.NamedGraphs.Contains("admin"))
    throw new Exception("Access denied!");
Expression parsing has uses outside of security such a dynamically building SPARQL queries or modifying existing ones. For example, its often used by services to set a default graph when none is specified in a query. This is done by modifying the expression object and then calling its ToString method to produce a SPARQL query string.
I find myself using the SparqlExpression class in almost every application I write.