示例#1
0
        public VariableValue Resolve(
            IResolverContext context,
            ScopedVariableNode variable,
            ITypeNode targetType)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            if (Resolvers.TryGetValue(variable.Scope.Value,
                                      out IScopedVariableResolver resolver))
            {
                return(resolver.Resolve(context, variable, targetType));
            }

            throw new QueryException(QueryError.CreateFieldError(
                                         string.Format(CultureInfo.InvariantCulture,
                                                       StitchingResources
                                                       .RootScopedVariableResolver_ScopeNotSupported,
                                                       variable.Scope.Value),
                                         context.Path,
                                         context.FieldSelection)
                                     .WithCode(ErrorCodes.ScopeNotDefined));
        }
示例#2
0
        public static IArgumentDescriptor Validate <T>(
            this IArgumentDescriptor argumentDescriptor,
            Func <T, bool> func)
        {
            Action <IDirectiveContext, FieldNode, string, object> validator = (d, n, a, o) =>
            {
                bool isValid = false;
                if (o is T t)
                {
                    isValid = func(t);
                }

                if (!isValid)
                {
                    throw new QueryException(QueryError.CreateArgumentError(
                                                 "Argument is not valid.",
                                                 d.Path,
                                                 n,
                                                 a));
                }
            };

            return(argumentDescriptor.Directive(
                       new ArgumentValidationDirective {
                Validator = validator
            }));
        }
        private static async Task AuthorizeAsync(
            IDirectiveContext context,
            DirectiveDelegate next)
        {
            AuthorizeDirective directive = context.Directive
                                           .ToObject <AuthorizeDirective>();

            ClaimsPrincipal principal = context
                                        .CustomProperty <ClaimsPrincipal>(nameof(ClaimsPrincipal));

            var allowed = IsInRoles(principal, directive.Roles);

#if !ASPNETCLASSIC
            if (allowed && NeedsPolicyValidation(directive))
            {
                allowed = await AuthorizeWithPolicyAsync(
                    context, directive, principal)
                          .ConfigureAwait(false);
            }
#endif
            if (allowed)
            {
                await next(context);
            }
            else if (context.Result == null)
            {
                context.Result = QueryError.CreateFieldError(
                    "The current user is not authorized to " +
                    "access this resource.",
                    context.Path,
                    context.FieldSelection);
            }
        }
        /// <summary>
        /// Initializes a new instance of the AstoriaQueryStreamValue class.
        /// </summary>
        /// <param name="type">The type of the value.</param>
        /// <param name="value">The value.</param>
        /// <param name="evaluationError">The evaluation error.</param>
        /// <param name="evaluationStrategy">The evaluation strategy.</param>
        public AstoriaQueryStreamValue(AstoriaQueryStreamType type, byte[] value, QueryError evaluationError, IQueryEvaluationStrategy evaluationStrategy)
            : base(evaluationError, evaluationStrategy)
        {
            ExceptionUtilities.CheckArgumentNotNull(type, "type");

            this.Type  = type;
            this.Value = value;
        }
示例#5
0
        private FaunaException ConstructStreamingException(Exception ex)
        {
            var queryError = new QueryError(null, "internal exception", ex.Message, null);
            var response   = new QueryErrorResponse(500, new List <QueryError> {
                queryError
            });

            return(new StreamingException(response));
        }
示例#6
0
        private static async Task <bool> AuthorizeWithPolicyAsync(
            IDirectiveContext context,
            AuthorizeDirective directive,
            ClaimsPrincipal principal)
        {
            IServiceProvider      services         = context.Service <IServiceProvider>();
            IAuthorizationService authorizeService =
                services.GetService <IAuthorizationService>();
            IAuthorizationPolicyProvider policyProvider =
                services.GetService <IAuthorizationPolicyProvider>();

            if (authorizeService == null || policyProvider == null)
            {
                return(string.IsNullOrWhiteSpace(directive.Policy));
            }

            AuthorizationPolicy policy = null;

            if (directive.Roles.Count == 0 &&
                string.IsNullOrWhiteSpace(directive.Policy))
            {
                policy = await policyProvider.GetDefaultPolicyAsync()
                         .ConfigureAwait(false);

                if (policy == null)
                {
                    context.Result = QueryError.CreateFieldError(
                        "The default authorization policy does not exist.",
                        context.FieldSelection);
                }
            }

            else if (!string.IsNullOrWhiteSpace(directive.Policy))
            {
                policy = await policyProvider.GetPolicyAsync(directive.Policy)
                         .ConfigureAwait(false);

                if (policy == null)
                {
                    context.Result = QueryError.CreateFieldError(
                        $"The `{directive.Policy}` authorization policy " +
                        "does not exist.",
                        context.FieldSelection);
                }
            }

            if (context.Result == null && policy != null)
            {
                AuthorizationResult result =
                    await authorizeService.AuthorizeAsync(principal, policy)
                    .ConfigureAwait(false);

                return(result.Succeeded);
            }

            return(false);
        }
示例#7
0
            /// <summary>
            /// Visits a LinqDistinctExpression. This expression is not supported in Linq to Astoria.
            /// </summary>
            /// <param name="expression">The expression.</param>
            /// <returns>The result of visiting this expression.</returns>
            public override QueryValue Visit(LinqDistinctExpression expression)
            {
                var source = this.EvaluateCollection(expression.Source);

                var sourceError = QueryError.GetErrorFromValues(source.Elements);
                var error       = QueryError.Combine(sourceError, new QueryError("This expression is not supported in Linq to Astoria."));

                return(expression.Source.ExpressionType.CreateErrorValue(error));
            }
示例#8
0
        public void Create_OnlyError_DataIsNull()
        {
            // arrange
            QueryError error = new QueryError("foo");

            // act
            var result = new QueryResult(error);

            // assert
            Assert.Null(result.Data);
        }
示例#9
0
        private FaunaException ConstructStreamingException(ObjectV value)
        {
            var code        = value.Get(CODE);
            var description = value.Get(DESCRIPTION);
            var queryError  = new QueryError(null, code, description, null);
            var response    = new QueryErrorResponse(500, new List <QueryError> {
                queryError
            });

            return(new StreamingException(response));
        }
示例#10
0
        public void Create_WithOneError_ContainsOneError()
        {
            // arrange
            QueryError error = new QueryError("foo");

            // act
            var result = new QueryResult(error);

            // assert
            Assert.Collection(result.Errors,
                              t => Assert.Equal(error, t));
        }
示例#11
0
        public PrestoQueryException(QueryError error, HttpStatusCode code) : base(error.Message, code)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }

            this.ErrorCode     = error.ErrorCode;
            this.ErrorLocation = error.ErrorLocation;
            this.ErrorName     = error.ErrorName;
            this.ErrorType     = error.ErrorType;
            this.FailureInfo   = error.FailureInfo;
        }
示例#12
0
 private static void DeserializeErrors(
     IQueryResult result,
     JObject serializedResult)
 {
     if (serializedResult.Property(_errors)?.Value is JArray array)
     {
         foreach (JObject error in array.Children().OfType <JObject>())
         {
             result.Errors.Add(
                 QueryError.FromDictionary(
                     DeserializeObject(error)));
         }
     }
 }
示例#13
0
        /// <summary>
        /// Compares the actual exception to expected error.
        /// </summary>
        /// <param name="expected">The expected error.</param>
        /// <param name="exception">The actual exception.</param>
        protected void CompareException(QueryError expected, Exception exception)
        {
            if (exception == null)
            {
                throw new TaupoInvalidOperationException(
                          string.Format(CultureInfo.InvariantCulture, "Expecting error: '{0}'. No exception was thrown.", expected.ToString()));
            }

            if (expected == null)
            {
                throw new TaupoInvalidOperationException("Got unexpected exception.", exception);
            }

            this.Logger.WriteLine(LogLevel.Verbose, "Got expected error: " + expected.ToString());
        }
示例#14
0
        public VariableValue Resolve(
            IResolverContext context,
            ScopedVariableNode variable,
            ITypeNode targetType)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            if (!ScopeNames.Arguments.Equals(variable.Scope.Value))
            {
                throw new ArgumentException(StitchingResources
                                            .ArgumentScopedVariableResolver_CannotHandleVariable,
                                            nameof(variable));
            }

            IInputField argument = context.Field.Arguments.FirstOrDefault(t =>
                                                                          t.Name.Value.EqualsOrdinal(variable.Name.Value));

            if (argument == null)
            {
                throw new QueryException(QueryError.CreateFieldError(
                                             string.Format(CultureInfo.InvariantCulture,
                                                           StitchingResources
                                                           .ArgumentScopedVariableResolver_InvalidArgumentName,
                                                           variable.Name.Value),
                                             context.Path,
                                             context.FieldSelection)
                                         .WithCode(ErrorCodes.ArgumentNotDefined));
            }

            return(new VariableValue
                   (
                       variable.ToVariableName(),
                       argument.Type.ToTypeNode(),
                       context.Argument <object>(variable.Name.Value),
                       argument.Type.IsNonNullType() &&
                       argument.DefaultValue.IsNull()
                    ? null
                    : argument.DefaultValue
                   ));
        }
示例#15
0
        internal static PrestoSqlException Create(QueryError error)
        {
            switch (error.errorType)
            {
            case "USER_ERROR": return(new PrestoSqlUserException(error));

            case "INTERNAL_ERROR": return(new PrestoSqlInternalException(error));

            case "INSUFFICIENT_RESOURCES": return(new PrestoSqlInsufficientResourceException(error));

            case "EXTERNAL": return(new PrestoSqlExternalException(error));

            default:
                return(new PrestoSqlException(error));
            }
        }
示例#16
0
        public VariableValue Resolve(
            IResolverContext context,
            ScopedVariableNode variable,
            ITypeNode targetType)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            if (!ScopeNames.Fields.Equals(variable.Scope.Value))
            {
                throw new ArgumentException(
                          StitchingResources
                          .FieldScopedVariableResolver_CannotHandleVariable,
                          nameof(variable));
            }

            if (context.ObjectType.Fields.TryGetField(variable.Name.Value,
                                                      out ObjectField field))
            {
                IReadOnlyDictionary <string, object> obj =
                    context.Parent <IReadOnlyDictionary <string, object> >();

                return(new VariableValue
                       (
                           variable.ToVariableName(),
                           field.Type.ToTypeNode(),
                           obj[field.Name],
                           null
                       ));
            }

            throw new QueryException(QueryError.CreateFieldError(
                                         string.Format(CultureInfo.InvariantCulture,
                                                       StitchingResources
                                                       .FieldScopedVariableResolver_InvalidFieldName,
                                                       variable.Name.Value),
                                         context.Path,
                                         context.FieldSelection)
                                     .WithCode(ErrorCodes.FieldNotDefined));
        }
      /// <summary>
      /// Auto-completes a query expression in response to user typing the first letter of
      /// a known model property or a LINQ method at the end of the expression.
      /// </summary>
      private void AutoComplete(ref string iQuery)
      {
         if (AutoCompleteCaption != "Auto-complete")
            AutoCompleteCaption = "Auto-complete";

         // If user isn't typing new letter, don't do auto-complete.
         if (Query != null && Query.Length > iQuery.Length)
            return;

         if (!IsQueryValid(iQuery))
         {
            if (QueryError.StartsWith("No property or field") && _errorPos == iQuery.Length - 1 && (_errorPos == 0 || iQuery[_errorPos - 1] != '.'))
            {
               var firstLetter = iQuery[_errorPos].ToString();
               var propertyName = _propertyNames.FirstOrDefault(i => i.StartsWith(firstLetter, StringComparison.InvariantCultureIgnoreCase));
               if (!String.IsNullOrEmpty(propertyName))
                  iQuery = iQuery.Remove(_errorPos).Insert(_errorPos, propertyName);
            }
            else if (QueryError.StartsWith("No property or field") && _errorPos > 0 && iQuery[_errorPos - 1] == '.')
            {
               var firstLetter = iQuery[_errorPos].ToString().ToUpper();
               if (firstLetter == "C")
                  iQuery = iQuery.Remove(_errorPos).Insert(_errorPos, "contains(\"\")");
               else if (firstLetter == "S")
                  iQuery = iQuery.Remove(_errorPos).Insert(_errorPos, "startsWith(\"\")");
               else if (firstLetter == "E")
                  iQuery = iQuery.Remove(_errorPos).Insert(_errorPos, "endsWith(\"\")");
               else if (firstLetter == "L")
                  iQuery = iQuery.Remove(_errorPos).Insert(_errorPos, "toLower()");
               else if (firstLetter == "U")
                  iQuery = iQuery.Remove(_errorPos).Insert(_errorPos, "toUpper()");
            }
            else if (QueryError.StartsWith("Identifier expected") && iQuery.Last() == '.')
            {
               AutoCompleteCaption = "Auto-complete: <b>c</b>ontains, <b>s</b>tartsWith, <b>e</b>ndsWith, to<b>L</b>ower, to<b>U</b>pper";
            }
            else if (QueryError.StartsWith("Syntax error") && _errorPos == iQuery.Length - 1)
            {
               var firstLetter = iQuery[_errorPos].ToString().ToUpper();
               if (firstLetter == "A")
                  iQuery = iQuery.Remove(_errorPos).Insert(_errorPos, "AND ");
               else if (firstLetter == "O")
                  iQuery = iQuery.Remove(_errorPos).Insert(_errorPos, "OR ");
            }
         }
      }
示例#18
0
 public QueryResultsV2(
     string id,
     Uri infoUri,
     Uri finalUri,
     Uri nextUri,
     bool nextUriDone,
     IEnumerable <Column> columns,
     IEnumerable <Uri> dataUris,
     Actions actions,
     QueryError error
     ) : base(id, infoUri, nextUri, columns, error)
 {
     this.FinalUri    = finalUri;
     this.NextUriDone = nextUriDone;
     this.DataUris    = dataUris;
     this.Actions     = actions;
 }
示例#19
0
        private void CompareClientOrEvaluationException(QueryValue expectedValue, ExpectedClientErrorBaseline clientExpectedException, Exception ex)
        {
            this.clientExceptionVerified = true;
            if (clientExpectedException != null)
            {
                this.ClientExpectedExceptionComparer.Compare(clientExpectedException, ex);
            }
            else if (ex != null)
            {
                QueryError queryError = null;
                if (expectedValue != null)
                {
                    queryError = expectedValue.EvaluationError;
                }

                this.CompareException(queryError, ex);
            }
        }
示例#20
0
            /// <summary>
            /// Determines if the source that is visiting a LinqQueryMethodExpression is a QueryCollection of Primitive or ComplexTypes
            /// and if it is it writes an error in, other wise it continues to evaluate this using the base Linq evaluator
            /// </summary>
            /// <param name="expression">The expression to evaluate.</param>
            /// <param name="entityCollectionVisitAction">Base expression to visit</param>
            /// <returns>Value of the expression.</returns>
            private QueryValue VisitCollectionElementPrimitiveOrComplexTypeError(LinqQueryMethodExpression expression, Func <QueryValue> entityCollectionVisitAction)
            {
                QueryValue queryValue = null;
                var        source     = this.EvaluateCollection(expression.Source);

                if (source.Type.ElementType is QueryComplexType || (source.Type.ElementType is QueryScalarType && !(source.Type.ElementType is QueryClrSpatialType)))
                {
                    var sourceError = QueryError.GetErrorFromValues(source.Elements);
                    var error       = QueryError.Combine(sourceError, new QueryError("This expression is not supported in Linq to Astoria."));

                    queryValue = expression.Source.ExpressionType.CreateErrorValue(error);
                }
                else
                {
                    queryValue = entityCollectionVisitAction();
                }

                return(queryValue);
            }
示例#21
0
        protected void CompareError(QueryError expected, Func <object> queryEvaluationFunc)
        {
            Exception exception = null;

            try
            {
                object result     = queryEvaluationFunc();
                var    enumerable = result as IEnumerable;
                if (enumerable != null)
                {
                    foreach (var obj in enumerable)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            this.CompareException(expected, exception);
        }
        /// <summary>
        /// Filters the specified source using given predicate.
        /// </summary>
        /// <typeparam name="TElement">The type of the element.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="predicate">The predicate.</param>
        /// <returns>
        /// Filtered collection (including elements where the predicate matches).
        /// </returns>
        /// <remarks>The value can be store-dependent w.r.t. handling of NULL values of the input collection
        /// and/or result of the predicate.</remarks>
        public QueryCollectionValue Filter(QueryCollectionValue source, Func <QueryValue, QueryScalarValue> predicate)
        {
            ExceptionUtilities.CheckArgumentNotNull(source, "source");

            IEnumerable <QueryValue> result = null;

            if (!source.IsNull)
            {
                result = source.Elements.Where(
                    c =>
                {
                    var evaluatedValue = predicate(c);
                    if (evaluatedValue.IsNull)
                    {
                        return(false);
                    }

                    return((bool)evaluatedValue.Value);
                });
            }

            return(new QueryCollectionValue(source.Type, this, QueryError.GetErrorFromValues(result), result, source.IsSorted));
        }
示例#23
0
        public Task Run(IMiddlewareContext context, FieldDelegate next)
        {
            var rootCtx = new FieldValidationContext(context.Field.Name);

            foreach (var inputField in context.Field.Arguments)
            {
                var directives = GetValidationDirectives(inputField.Directives);
                var value      = context.Argument <object>(inputField.Name);
                var ctx        = new FieldValidationContext(inputField.Name);
                HandleInput(value, inputField.Type, directives, ctx);
                rootCtx.AddErrored(ctx);
            }

            if (rootCtx.HasErrors())
            {
                var errorsProperty = new ErrorProperty("FieldValidationError", rootCtx);
                var error          = new QueryError("Invalid input data", errorsProperty);

                throw new QueryException(error);
            }

            return(next.Invoke(context));
        }
示例#24
0
        private static async Task AuthorizeAsync(
            IDirectiveContext context,
            DirectiveDelegate next)
        {
#if !ASPNETCLASSIC
            IAuthorizationService authorizeService = context
                                                     .Service <IAuthorizationService>();
#endif
            ClaimsPrincipal principal = context
                                        .CustomProperty <ClaimsPrincipal>(nameof(ClaimsPrincipal));
            AuthorizeDirective directive = context.Directive
                                           .ToObject <AuthorizeDirective>();
            bool allowed = IsInRoles(principal, directive.Roles);

#if !ASPNETCLASSIC
            if (allowed && !string.IsNullOrEmpty(directive.Policy))
            {
                AuthorizationResult result = await authorizeService
                                             .AuthorizeAsync(principal, directive.Policy);

                allowed = result.Succeeded;
            }
#endif

            if (allowed)
            {
                await next(context);
            }
            else
            {
                context.Result = QueryError.CreateFieldError(
                    "The current user is not authorized to " +
                    "access this resource.",
                    context.Path,
                    context.FieldSelection);
            }
        }
示例#25
0
        public QueryResultsV1(
            string id,
            Uri infoUri,
            Uri partialCancelUri,
            Uri nextUri,
            IEnumerable <Column> columns,
            IEnumerable <List <dynamic> > data,
            StatementStats stats,
            QueryError error,
            string updateType,
            long updateCount
            ) : base(id, infoUri, nextUri, columns, error)
        {
            if (data != null && columns == null)
            {
                throw new ArgumentException("Data present without columns");
            }

            this.PartialCancelUri = partialCancelUri;
            this.Data             = data;
            this.Stats            = stats ?? throw new ArgumentNullException("stats");
            this.UpdateType       = updateType;
            this.UpdateCount      = updateCount;
        }
示例#26
0
 internal PrestoSqlException(QueryError error) : base(error.message)
 {
     this.QueryError = error;
 }
示例#27
0
 internal PrestoSqlInsufficientResourceException(QueryError error) : base(error)
 {
 }
示例#28
0
 /// <summary>
 /// Initializes a new instance of the QueryEntityValue class.
 /// </summary>
 /// <param name="type">The type of the value.</param>
 /// <param name="isNull">If set to <c>true</c> the structural value is null.</param>
 /// <param name="evaluationError">The evaluation error.</param>
 /// <param name="evaluationStrategy">The evaluation strategy.</param>
 internal QueryEntityValue(QueryEntityType type, bool isNull, QueryError evaluationError, IQueryEvaluationStrategy evaluationStrategy)
     : base(type, isNull, evaluationError, evaluationStrategy)
 {
     this.navigateResultLookup = new Dictionary<AssociationType, Dictionary<AssociationEnd, QueryValue>>();
 }
 private MaskedQueryStructuralValue(QueryStructuralType type, bool isNull, QueryError evaluationError, IQueryEvaluationStrategy evaluationStrategy)
     : base(type, isNull, evaluationError, evaluationStrategy)
 {
 }
示例#30
0
 /// <summary>
 /// Creates the non-strongly typed error value.
 /// </summary>
 /// <param name="evaluationError">The evaluation error.</param>
 /// <returns>Created error value.</returns>
 protected override QueryValue CreateErrorValueInternal(QueryError evaluationError)
 {
     return this.CreateErrorValue(evaluationError);
 }
示例#31
0
 /// <summary>
 /// Creates the error value of this type.
 /// </summary>
 /// <param name="evaluationError">The evaluation error.</param>
 /// <returns>Created error value.</returns>
 public new QueryStructuralValue CreateErrorValue(QueryError evaluationError)
 {
     return new QueryStructuralValue(this, true, evaluationError, this.EvaluationStrategy);
 }
示例#32
0
 /// <summary>
 /// Creates error value
 /// </summary>
 /// <param name="evaluationError">evaluation error</param>
 /// <returns>Throws TaupoInvalidOperationException</returns>
 protected override QueryValue CreateErrorValueInternal(QueryError evaluationError)
 {
     throw new TaupoInvalidOperationException("Error Evaluation of Void is not allowed");
 }
示例#33
0
 /// <summary>
 /// Creates the non-strongly typed error value.
 /// </summary>
 /// <param name="evaluationError">The evaluation error.</param>
 /// <returns>Created error value.</returns>
 protected override QueryValue CreateErrorValueInternal(QueryError evaluationError)
 {
     return new QueryScalarValue(this, null, evaluationError, this.EvaluationStrategy);
 }
示例#34
0
 internal PrestoSqlExternalException(QueryError error) : base(error)
 {
 }
示例#35
0
 /// <summary>
 /// Creates the null value with error information attached.
 /// </summary>
 /// <param name="error">The error information.</param>
 /// <returns>Newly created value.</returns>
 public new QueryScalarValue CreateErrorValue(QueryError error)
 {
     return (QueryScalarValue)this.CreateErrorValueInternal(error);
 }
示例#36
0
 /// <summary>
 /// Creates the non-strongly typed error value.
 /// </summary>
 /// <param name="evaluationError">The evaluation error.</param>
 /// <returns>Created error value.</returns>
 protected override QueryValue CreateErrorValueInternal(QueryError evaluationError)
 {
     return(this.CreateErrorValue(evaluationError));
 }