Esempio n. 1
0
        public void ValidateTag(string tag, bool isValid)
        {
            var ev = new Event {
                Type = Event.KnownTypes.Error, Date = DateTimeOffset.Now
            };

            ev.Tags.Add(tag);

            var result = _validator.Validate(ev);

            Assert.Equal(isValid, result.IsValid);
        }
        public async Task <CoapMessage> PutAsync(CoapMessage message)
        {
            CoapUri             uri = new CoapUri(message.ResourceUri.ToString());
            ResponseMessageType rmt = message.MessageType == CoapMessageType.Confirmable ? ResponseMessageType.Acknowledgement : ResponseMessageType.NonConfirmable;

            //EventValidator.Validate(false, resourceUriString, Channel, graphManager, context).Validated
            //if (!await adapter.CanSubscribeAsync(uri.Resource, channel.IsEncrypted))
            if (EventValidator.Validate(false, uri.Resource, channel, graphManager).Validated)
            {
                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Unauthorized, message.Token));
            }

            if (coapObserved.ContainsKey(uri.Resource) || coapUnobserved.Contains(uri.Resource))
            {
                //resource previously subscribed
                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.NotAcceptable, message.Token));
            }

            //this point the resource is not being observed, so we can
            // #1 subscribe to it
            // #2 add to unobserved resources (means not coap observed)

            SubscriptionMetadata metadata = new SubscriptionMetadata()
            {
                IsEphemeral = true,
                Identity    = session.Identity,
                Indexes     = session.Indexes
            };

            string subscriptionUriString = await adapter.SubscribeAsync(uri.Resource, metadata);

            coapUnobserved.Add(uri.Resource);

            return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Created, message.Token));
        }
        public async Task <CoapMessage> ObserveAsync(CoapMessage message)
        {
            if (!message.Observe.HasValue)
            {
                //RST because GET needs to be observe/unobserve
                await logger?.LogWarningAsync($"CoAP observe received without Observe flag and will return RST for {session.Identity}");

                await logger?.LogDebugAsync($"Returning RST because GET needs to be observe/unobserve for {session.Identity}");

                return(new CoapResponse(message.MessageId, ResponseMessageType.Reset, ResponseCodeType.EmptyMessage));
            }

            CoapUri             uri = new CoapUri(message.ResourceUri.ToString());
            ResponseMessageType rmt = message.MessageType == CoapMessageType.Confirmable ? ResponseMessageType.Acknowledgement : ResponseMessageType.NonConfirmable;

            ValidatorResult result = EventValidator.Validate(false, uri.Resource, channel, graphManager);

            if (!result.Validated)
            {
                await logger?.LogErrorAsync($"{result.ErrorMessage} for {session.Identity}");

                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Unauthorized, message.Token));
            }

            if (!message.Observe.Value)
            {
                //unsubscribe
                await logger?.LogInformationAsync($"CoAP unobserve '{message.ResourceUri.ToString()}' for {session.Identity}.");

                await adapter.UnsubscribeAsync(uri.Resource);

                await logger?.LogDebugAsync($"CoAP unsubscribed '{message.ResourceUri.ToString()} for {session.Identity}'.");

                coapObserved.Remove(uri.Resource);
            }
            else
            {
                //subscribe
                SubscriptionMetadata metadata = new SubscriptionMetadata()
                {
                    IsEphemeral = true,
                    Identity    = session.Identity,
                    Indexes     = session.Indexes
                };

                await logger?.LogInformationAsync($"CoAP subscribed '{message.ResourceUri.ToString()}' for {session.Identity}");

                string subscriptionUriString = await adapter.SubscribeAsync(uri.Resource, metadata);


                if (!coapObserved.ContainsKey(uri.Resource)) //add resource to observed list
                {
                    coapObserved.Add(uri.Resource, message.Token);
                    await logger?.LogDebugAsync("Key added to observable resource.");
                }
            }

            return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Valid, message.Token));
        }
Esempio n. 4
0
        private async Task PublishAsync(PublishMessage message)
        {
            MessageAuditRecord record   = null;
            EventMetadata      metadata = null;

            try
            {
                MqttUri mqttUri = new MqttUri(message.Topic);
                metadata = await graphManager.GetPiSystemMetadataAsync(mqttUri.Resource);

                if (EventValidator.Validate(true, metadata, Channel, graphManager, context).Validated)
                {
                    EventMessage msg = new EventMessage(mqttUri.ContentType, mqttUri.Resource, ProtocolType.MQTT,
                                                        message.Encode(), DateTime.UtcNow, metadata.Audit);
                    if (!string.IsNullOrEmpty(mqttUri.CacheKey))
                    {
                        msg.CacheKey = mqttUri.CacheKey;
                    }

                    if (mqttUri.Indexes != null)
                    {
                        List <KeyValuePair <string, string> > list = GetIndexes(mqttUri);
                        await adapter.PublishAsync(msg, list);
                    }
                    else
                    {
                        await adapter.PublishAsync(msg);
                    }
                }
                else
                {
                    if (metadata.Audit)
                    {
                        record = new MessageAuditRecord("XXXXXXXXXXXX", session.Identity, Channel.TypeId, "MQTT",
                                                        message.Payload.Length, MessageDirectionType.In, false, DateTime.UtcNow,
                                                        "Not authorized, missing resource metadata, or channel encryption requirements");
                    }

                    throw new SecurityException(string.Format("'{0}' not authorized to publish to '{1}'",
                                                              session.Identity, metadata.ResourceUriString));
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex, $"MQTT adapter PublishAsync error on channel '{Channel.Id}'.");

                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }
            finally
            {
                if (metadata != null && metadata.Audit && record != null)
                {
                    await messageAuditor?.WriteAuditRecordAsync(record);
                }
            }
        }
        public async Task <CoapMessage> PostAsync(CoapMessage message)
        {
            try
            {
                CoapUri             uri      = new CoapUri(message.ResourceUri.ToString());
                ResponseMessageType rmt      = message.MessageType == CoapMessageType.Confirmable ? ResponseMessageType.Acknowledgement : ResponseMessageType.NonConfirmable;
                EventMetadata       metadata = await graphManager.GetPiSystemMetadataAsync(uri.Resource);

                ValidatorResult result = EventValidator.Validate(true, metadata, null, graphManager);

                if (!result.Validated)
                {
                    if (metadata.Audit)
                    {
                        await auditor?.WriteAuditRecordAsync(new MessageAuditRecord("XXXXXXXXXXXX", session.Identity, this.channel.TypeId, "COAP", message.Payload.Length, MessageDirectionType.In, false, DateTime.UtcNow, "Not authorized, missing resource metadata, or channel encryption requirements")).LogExceptions(logger);
                    }

                    logger?.LogErrorAsync(result.ErrorMessage);
                    return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Unauthorized, message.Token));
                }

                string contentType = message.ContentType.HasValue ? message.ContentType.Value.ConvertToContentType() : "application/octet-stream";

                EventMessage msg = new EventMessage(contentType, uri.Resource, ProtocolType.COAP, message.Encode(), DateTime.UtcNow, metadata.Audit);

                if (!string.IsNullOrEmpty(uri.CacheKey))
                {
                    msg.CacheKey = uri.CacheKey;
                }

                if (uri.Indexes == null)
                {
                    await adapter.PublishAsync(msg);
                }
                else
                {
                    List <KeyValuePair <string, string> > indexes = GetIndexes(uri);
                    await adapter.PublishAsync(msg, indexes);
                }

                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Created, message.Token));
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"CoAP POST fault for {session.Identity}.");
                throw ex;
            }
        }
Esempio n. 6
0
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
        {
            var newEvent = JsonConvert.DeserializeObject <Event>(await req.ReadAsStringAsync());

            var validator        = new EventValidator();
            var validatorResults = validator.Validate(newEvent);

            if (!validatorResults.IsValid)
            {
                return(new BadRequestObjectResult(validatorResults.Errors));
            }

            await newEvent.SaveAsync(Repository);

            return(new JsonResult(newEvent));
        }
        public Notification <bool> CreateEvent(Event ev)
        {
            ev.SetId(GetMaxId() + 1);
            EventValidator      validator = new EventValidator(ev);
            bool                valid     = validator.Validate();
            Notification <bool> notifier  = new Notification <bool>();

            if (!valid)
            {
                foreach (var error in validator.GetErrors())
                {
                    notifier.AddError(error);
                }
                notifier.SetResult(false);
            }
            else
            {
                notifier.SetResult(eventRepo.Create(ev));
            }
            return(notifier);
        }
Esempio n. 8
0
        private void Session_OnUnsubscribe(object sender, MqttMessageEventArgs args)
        {
            try
            {
                UnsubscribeMessage msg = (UnsubscribeMessage)args.Message;
                foreach (var item in msg.Topics)
                {
                    MqttUri uri = new MqttUri(item.ToLowerInvariant());

                    if (EventValidator.Validate(false, uri.Resource, Channel, graphManager, context).Validated)
                    {
                        adapter.UnsubscribeAsync(uri.Resource).GetAwaiter();
                        logger?.LogInformationAsync($"MQTT adapter unsubscribed {uri.ToString()}");
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"MQTT adapter Session_OnUnsubscribe error on channel '{Channel.Id}'.").GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }
        }
Esempio n. 9
0
        private List <string> Session_OnSubscribe(object sender, MqttMessageEventArgs args)
        {
            List <string> list = new List <string>();

            try
            {
                SubscribeMessage message = args.Message as SubscribeMessage;

                SubscriptionMetadata metadata = new SubscriptionMetadata
                {
                    Identity    = session.Identity,
                    Indexes     = session.Indexes,
                    IsEphemeral = true
                };

                foreach (var item in message.Topics)
                {
                    MqttUri uri = new MqttUri(item.Key);
                    string  resourceUriString = uri.Resource;

                    if (EventValidator.Validate(false, resourceUriString, Channel, graphManager, context).Validated)
                    {
                        Task <string> subTask = Subscribe(resourceUriString, metadata);
                        string        subscriptionUriString = subTask.Result;
                        list.Add(resourceUriString);
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"MQTT adapter Session_OnSubscribe error on channel '{Channel.Id}'.")
                .GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }

            return(list);
        }
Esempio n. 10
0
 public void ForValidEvent_DoesNotThrowException()
 {
     FluentActions.Invoking(() => validator.Validate(command))
     .Should().NotThrow();
 }