Ejemplo n.º 1
0
        private IList <EndpointProbe> GetEndpointProbeList(TestResources resources, TestConfig config)
        {
            BlockingCollection <EndpointProbe> list = new BlockingCollection <EndpointProbe>();

            var test = Defaults.HttpMethods.Intersect(config.TestMethods, StringComparer.OrdinalIgnoreCase);

            Parallel.ForEach(
                resources.SwaggerDocument.Paths,
                new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount
            },
                path =>
            {
                if (CheckIfPathAllowed(path.Key, config))
                {
                    Parallel.ForEach(
                        Defaults.HttpMethods.Intersect(config.TestMethods, StringComparer.OrdinalIgnoreCase),
                        new ParallelOptions {
                        MaxDegreeOfParallelism = Environment.ProcessorCount
                    },
                        method =>
                    {
                        CosmoOperation methodInfo = path.Value
                                                    .GetType()
                                                    .GetProperty(method)
                                                    .GetValue(path.Value) as CosmoOperation;

                        if (methodInfo != null)
                        {
                            dynamic payload = GetEndpointPayload(path.Key, method, resources.PayloadDictionary);
                            list.Add(
                                new EndpointProbe
                            {
                                Endpoint                 = path.Key,
                                Method                   = new HttpMethod(method),
                                AuthToken                = GetEndpointAuthToken(path.Key, resources.AuthDictionary),
                                Payload                  = payload,
                                PayloadMIMEType          = GetPayloadType(path.Key, methodInfo.Consumes, payload),
                                ExpectedResponseMIMEType = GetResponseType(path.Key, methodInfo.Produces)
                            }
                                );
                        }
                    });
                }
            });

            list.CompleteAdding();

            return(list.ToList());
        }
Ejemplo n.º 2
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("GetAccess message received");

            try
            {
                log.Info("Reading body message");

                UserCredentials userCredentials = JsonConvert.DeserializeObject <UserCredentials>(await req.Content.ReadAsStringAsync());
                if (userCredentials == null || string.IsNullOrWhiteSpace(userCredentials.Login) || string.IsNullOrWhiteSpace(userCredentials.Password))
                {
                    return(req.CreateResponse(HttpStatusCode.Unauthorized, "Missing credentials"));
                }

                log.Info("Getting User");
                CosmoOperation cosmoOperation = await CosmosDBOperations.QueryDBAsync(new CosmoOperation()
                {
                    Collection = Environment.GetEnvironmentVariable(Config.COSMOS_COLLECTION),
                    Database   = Environment.GetEnvironmentVariable(Config.COSMOS_DATABASE),
                    Payload    = $"SELECT * FROM c WHERE c.type = 'User' AND c.login = '******' AND c.password = '******'"
                });

                if (cosmoOperation.Results == null || cosmoOperation.Results.Length == 0)
                {
                    return(req.CreateResponse(HttpStatusCode.Unauthorized, "Invalid credentials"));
                }

                if (cosmoOperation.Results.Length > 1)
                {
                    throw new Exception("More than one user has found");
                }

                Dictionary <string, object> user = JsonConvert.DeserializeObject <Dictionary <string, object> >(cosmoOperation.Results[0].ToString());
                string token = JwtTokenCreator.CreateJwtToken(
                    (string)user["name"],
                    (string)user["id"],
                    new Dictionary <string, string>()
                {
                    { "user", JsonConvert.SerializeObject(user) }
                });

                return(await Task.Factory.StartNew(() => req.CreateResponse(HttpStatusCode.OK, token)));
            }
            catch (Exception ex)
            {
                log.Error("Erro: ", ex);
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Ejemplo n.º 3
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("InsertIntentContent message received");

            try
            {
                //Utils.ValidateAuthorizationHeader(req.Headers?.Authorization);

                string json = await req.Content.ReadAsStringAsync();

                if (string.IsNullOrWhiteSpace(json))
                {
                    throw new Exception("Missing body");
                }

                IntentContent intentContent = JsonConvert.DeserializeObject <IntentContent>(json);

                log.Info("Creating intentContent Id");
                if (string.IsNullOrWhiteSpace(intentContent.id))
                {
                    intentContent.id = Guid.NewGuid().ToString();
                }

                log.Info("Creating intentContent Partition key");
                if (string.IsNullOrWhiteSpace(intentContent.partitionKey))
                {
                    intentContent.partitionKey = Utils.CreatePartitionKey(intentContent.type.Replace(" ", ""), intentContent.id);
                }

                CosmoOperation cosmoOperation = await CosmosDBOperations.UpsertDocumentAsync(new CosmoOperation()
                {
                    Collection = Environment.GetEnvironmentVariable(Config.COSMOS_COLLECTION),
                    Database   = Environment.GetEnvironmentVariable(Config.COSMOS_DATABASE),
                    Payload    = intentContent
                });

                return(req.CreateResponse(HttpStatusCode.OK, cosmoOperation.Results as object));
            }
            catch (UnauthorizedAccessException ex)
            {
                log.Error("Unauthorized");
                return(req.CreateResponse(HttpStatusCode.Unauthorized, ex.Message));
            }
            catch (Exception ex)
            {
                log.Error($"Error: {ex.Message} ", ex);
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("GetIntentAnswer message received");
            try
            {
                string intentName = req.GetQueryNameValuePairs()
                                    .FirstOrDefault(q => string.Compare(q.Key, "intent", true) == 0)
                                    .Value;

                string profile = req.GetQueryNameValuePairs()
                                 .FirstOrDefault(q => string.Compare(q.Key, "profile", true) == 0)
                                 .Value;

                string entity = req.GetQueryNameValuePairs()
                                .FirstOrDefault(q => string.Compare(q.Key, "entity", true) == 0)
                                .Value;

                string whereCondition = "WHERE d.type = 'IntentContent'";
                if (!string.IsNullOrWhiteSpace(intentName))
                {
                    whereCondition = $"{whereCondition} AND d.intent = '{intentName}'";
                }

                if (!string.IsNullOrWhiteSpace(entity))
                {
                    whereCondition = $"{whereCondition} AND e['value'] = '{entity}'";
                }

                if (!string.IsNullOrWhiteSpace(profile))
                {
                    whereCondition = $"{whereCondition} AND p.id = '{profile}'";
                }

                CosmoOperation cosmoOperation = await CosmosDBOperations.QueryDBAsync(new CosmoOperation()
                {
                    Collection = Environment.GetEnvironmentVariable(Config.COSMOS_COLLECTION),
                    Database   = Environment.GetEnvironmentVariable(Config.COSMOS_DATABASE),
                    Payload    = $"SELECT d as document FROM Data d JOIN e IN d.entities JOIN p IN e.profiles {whereCondition}"
                });

                return(req.CreateResponse(HttpStatusCode.OK, cosmoOperation.Results as object));
            }
            catch (Exception ex)
            {
                log.Error("Error: ", ex);
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Ejemplo n.º 5
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("InsertIntentContent message received");
            try
            {
                string body = await req.Content.ReadAsStringAsync();

                if (string.IsNullOrWhiteSpace(body))
                {
                    throw new Exception("Missing body");
                }

                Dictionary <string, string> data = JsonConvert.DeserializeObject <Dictionary <string, string> >(body);
                if (!data.TryGetValue("id", out string id) || string.IsNullOrWhiteSpace(id))
                {
                    throw new Exception("Missing Id");
                }

                if (!data.TryGetValue("partitionKey", out string partitionKey) || string.IsNullOrWhiteSpace(partitionKey))
                {
                    throw new Exception("Missing partitionKey");
                }

                log.Info($"Deleting document with Id: {id}\tparitionKey: {partitionKey}");
                CosmoOperation cosmoOperation = await CosmosDBOperations.DeleteDocumentAsync(new CosmoOperation()
                {
                    Collection = Environment.GetEnvironmentVariable(Config.COSMOS_COLLECTION),
                    Database   = Environment.GetEnvironmentVariable(Config.COSMOS_DATABASE),
                    Payload    = new { id, partitionKey }
                });

                return(req.CreateResponse(HttpStatusCode.OK, cosmoOperation.Results as object));
            }
            catch (UnauthorizedAccessException ex)
            {
                log.Error("Unauthorized");
                return(req.CreateResponse(HttpStatusCode.Unauthorized, ex.Message));
            }
            catch (Exception ex)
            {
                log.Error($"Error: {ex.Message} ", ex);
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Ejemplo n.º 6
0
        public ConcurrentDictionary <string, ConcurrentDictionary <string, dynamic> > GeneratePayloadDictionary(
            TestConfig config, SwaggerDocument swaggerDoc)
        {
            ConcurrentDictionary <string, ConcurrentDictionary <string, dynamic> > dict =
                new ConcurrentDictionary <string, ConcurrentDictionary <string, dynamic> >(Environment.ProcessorCount, 20);

            if (!config.DataFiles.Any())
            {
                return(dict);
            }

            if (!File.Exists(config.DataFiles.First()))
            {
                Errors.Add(
                    new SetupError
                {
                    Severity = ErrorLevel.Fatal,
                    Type     = InitialiserErrorType.PayloadDictionarySetup,
                    Message  = InitialiserErrorMessages.PayloadDictionary_NoDataFile
                               .Replace("[[File]]", config.DataFiles.First())
                });

                return(dict);
            }

            IList <EndpointData> endpointData = new List <EndpointData>();

            try
            {
                using (StreamReader file = File.OpenText(config.DataFiles.First()))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    endpointData = (IList <EndpointData>)serializer
                                   .Deserialize(file, typeof(IList <EndpointData>));
                }
            }
            catch (Exception ex)
            {
                Errors.Add(
                    new SetupError
                {
                    Severity = ErrorLevel.Fatal,
                    Type     = InitialiserErrorType.PayloadDictionarySetup,
                    Message  = InitialiserErrorMessages.PayloadDictionary_DataFileParseError
                               .Replace("[[File]]", config.DataFiles.First())
                               .Replace("[[Message]]", ex.Message)
                });

                return(dict);
            }

            Parallel.ForEach(
                swaggerDoc.Paths,
                new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount
            },
                path =>
            {
                Parallel.ForEach(
                    Defaults.HttpMethods,
                    new ParallelOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                },
                    method =>
                {
                    CosmoOperation methodInfo = path.Value
                                                .GetType()
                                                .GetProperty(method)
                                                .GetValue(path.Value) as CosmoOperation;

                    if (methodInfo != null)
                    {
                        ConcurrentDictionary <string, dynamic> methodDataDictionary =
                            new ConcurrentDictionary <string, dynamic>(Environment.ProcessorCount, 2);

                        dynamic methodData =
                            endpointData.Where(x =>
                                               x.URL == path.Key &&
                                               x.Method.ToLower() == method.ToLower())
                            .FirstOrDefault()?.Data;

                        methodDataDictionary.TryAdd(method, methodData);

                        dict.AddOrUpdate(
                            path.Key,
                            methodDataDictionary,
                            ((key, val) => val.TryAdd(method, methodData)));
                    }
                }
                    );
            });

            return(dict);
        }