Exemple #1
0
        public void Test_CustomAction_OnSaved()
        {
            object id = null;

            Core.Configuration.ResetCustomActions();
            Core.Configuration.Setup()
            .UseDynamicProvider(_ => _.OnInsert(ev => ev.EventType))
            .WithCreationPolicy(EventCreationPolicy.InsertOnStartReplaceOnEnd);
            Core.Configuration.AddCustomAction(ActionType.OnEventSaved, scope =>
            {
                id = scope.EventId;
            });
            using (var scope = AuditScope.Create("eventType as id", null))
            {
                scope.Discard();
            }
            Core.Configuration.ResetCustomActions();

            Assert.AreEqual("eventType as id", id);
        }
        /// <summary>
        /// Creates the Audit scope.
        /// </summary>
        public AuditScope CreateAuditScope(IAuditDbContext context, EntityFrameworkEvent efEvent)
        {
            var typeName     = context.GetType().Name;
            var eventType    = context.AuditEventType?.Replace("{context}", typeName).Replace("{database}", efEvent.Database) ?? typeName;
            var auditEfEvent = new AuditEventEntityFramework
            {
                EntityFrameworkEvent = efEvent
            };
            var scope = AuditScope.Create(eventType, null, null, EventCreationPolicy.Manual, context.AuditDataProvider, auditEfEvent, 3);

            if (context.ExtraFields != null)
            {
                foreach (var field in context.ExtraFields)
                {
                    scope.SetCustomField(field.Key, field.Value);
                }
            }
            context.OnScopeCreated(scope);
            return(scope);
        }
Exemple #3
0
        public void Test_AsyncCustomAction_Fluent()
        {
            var  evs   = new List <AuditEvent>();
            bool saved = false;

            Audit.Core.Configuration.Setup()
            .UseDynamicProvider(_ => _.OnInsert(ev =>
            {
                evs.Add(AuditEvent.FromJson(ev.ToJson()));
            }))
            .WithCreationPolicy(EventCreationPolicy.Manual)
            .ResetActions()
            .WithAction(action => action
                        .OnEventSaved(async scope =>
            {
                await Task.Delay(500);
                saved = true;
            }))
            .WithAction(action => action
                        .OnEventSaving(async scope =>
            {
                await Task.Delay(500);
                scope.Comment("OnEventSaving");
            }))
            .WithAction(action => action
                        .OnScopeCreated(async scope =>
            {
                await Task.Delay(500);
                scope.Comment("OnScopeCreated");
            }));

            using (var scope = AuditScope.Create("test", null))
            {
                scope.Save();
            }

            Assert.AreEqual(1, evs.Count);
            Assert.IsTrue(evs[0].Comments.Contains("OnScopeCreated"));
            Assert.IsTrue(evs[0].Comments.Contains("OnEventSaving"));
            Assert.IsTrue(saved);
        }
Exemple #4
0
        public void Redis_Multithread(int N)
        {
            var key = Guid.NewGuid().ToString();

            Core.Configuration.Setup()
            .UseRedis(redis => redis
                      .ConnectionString(RedisCnnString + ",connectTimeout=120000")
                      .AsList(s => s
                              .Key(ev => key)))
            .WithCreationPolicy(EventCreationPolicy.InsertOnEnd);

            var tasks = new List <Task>(N);

            for (int i = 0; i < N; i++)
            {
                int a = i;
                tasks.Add(Task.Run(() =>
                {
                    using (var scope = AuditScope.Create(new AuditScopeOptions()
                    {
                        EventType = $"Redis_Multithread_{a}"
                    }))
                    {
                    }
                }));
            }

            Task.WaitAll(tasks.ToArray());

            var mx     = GetMultiplexer();
            var db     = mx.GetDatabase();
            var values = db.ListRange(key).Select(x => JsonConvert.DeserializeObject <AuditEvent>(x)).ToList();

            db.KeyDelete(key);

            Assert.AreEqual(N, values.Count);
            for (int a = 0; a < N; a++)
            {
                Assert.IsTrue(values.Any(x => x.EventType == $"Redis_Multithread_{a}"));
            }
        }
Exemple #5
0
        public void TestAzureCosmos_Enumerate()
        {
            var dp = new AzureCosmos.Providers.AzureCosmosDataProvider()
            {
                Endpoint  = AzureSettings.AzureDocDbUrl,
                Database  = "Audit",
                Container = "AuditTest",
                AuthKey   = AzureSettings.AzureDocDbAuthKey
            };
            var eventType = TestContext.CurrentContext.Test.Name + new Random().Next(1000, 9999);

            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
                DataProvider = dp,
                EventType = eventType,
                CreationPolicy = EventCreationPolicy.InsertOnEnd
            }))
            {
                scope.SetCustomField("value", 100);
            };
            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
                DataProvider = dp,
                EventType = eventType,
                CreationPolicy = EventCreationPolicy.InsertOnStartInsertOnEnd
            }))
            {
                scope.SetCustomField("value", 200);
            };

            var evs = dp.EnumerateEvents <AuditEventWithId>($"SELECT * FROM c WHERE c.EventType LIKE '{eventType}%' ORDER BY c.StartDate DESC", new Microsoft.Azure.Documents.Client.FeedOptions()
            {
                EnableCrossPartitionQuery = true
            })
                      .ToList();

            Assert.AreEqual(3, evs.Count);
            Assert.AreEqual(200, evs[0].CustomFields["value"]);
            Assert.IsFalse(evs[1].CustomFields.ContainsKey("value"));
            Assert.AreEqual(100, evs[2].CustomFields["value"]);
        }
Exemple #6
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request     = filterContext.HttpContext.Request;
            var auditAction = new AuditAction()
            {
                UserName  = (request.IsAuthenticated) ? filterContext.HttpContext.User?.Identity.Name : "Anonymous",
                IpAddress = request.ServerVariables?["HTTP_X_FORWARDED_FOR"] ?? request.UserHostAddress,
#if NET45
                RequestUrl    = request.Unvalidated.RawUrl,
                FormVariables = ToDictionary(request.Unvalidated.Form),
                Headers       = IncludeHeaders ? ToDictionary(request.Unvalidated.Headers) : null,
#else
                RequestUrl    = request.RawUrl,
                FormVariables = ToDictionary(request.Form),
                Headers       = IncludeHeaders ? ToDictionary(request.Headers) : null,
#endif
                HttpMethod       = request.HttpMethod,
                ActionName       = filterContext.ActionDescriptor?.ActionName,
                ControllerName   = filterContext.ActionDescriptor?.ControllerDescriptor?.ControllerName,
                ActionParameters = GetActionParameters(filterContext.ActionParameters)
            };
            var eventType = (EventTypeName ?? "{verb} {controller}/{action}").Replace("{verb}", auditAction.HttpMethod)
                            .Replace("{controller}", auditAction.ControllerName)
                            .Replace("{action}", auditAction.ActionName);
            // Create the audit scope
            var auditEventAction = new AuditEventMvcAction()
            {
                Action = auditAction
            };
            var options = new AuditScopeOptions()
            {
                EventType     = eventType,
                AuditEvent    = auditEventAction,
                CallingMethod = (filterContext.ActionDescriptor as ReflectedActionDescriptor)?.MethodInfo
            };
            var auditScope = AuditScope.Create(options);

            filterContext.HttpContext.Items[AuditActionKey] = auditAction;
            filterContext.HttpContext.Items[AuditScopeKey]  = auditScope;
            base.OnActionExecuting(filterContext);
        }
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewBag.Roles         = PopulateRolesDropDownList();
            ViewData["ReturnUrl"] = returnUrl;

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser()
                {
                    UserName       = ApplicationUser.GenerateUsername(model.FirstName, model.LastName),
                    Email          = model.Email,
                    FirstName      = model.FirstName,
                    LastName       = model.LastName,
                    EmailConfirmed = true
                };
                using (var audit = AuditScope.Create("User:Register", () => user))
                {
                    var result = await _userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        var    selectedRoles = Request.Form["Roles"].AsEnumerable();
                        string anonRole      = "Anonymous Role";
                        if (!selectedRoles.Contains(anonRole))
                        {
                            selectedRoles = selectedRoles.Append(anonRole);
                        }
                        await _userManager.AddToRolesAsync(user, selectedRoles);

                        audit.Comment("Created user " + user.UserName);
                        var currentUser = GetCurrentUserAsync().Result;
                        audit.Event.CustomFields["CreatedById"]       = currentUser.Id;
                        audit.Event.CustomFields["CreatedByUserName"] = currentUser.UserName;
                        //await _signInManager.SignInAsync(user, isPersistent: fa`lse);
                        return(RedirectToLocal(returnUrl));
                    }
                    AddErrors(result);
                }
            }
            return(View(model));
        }
Exemple #8
0
        /// <summary>
        /// Returns an object and a set of output objects from an instance and set of input objects.
        /// </summary>
        /// <param name="instance">The object to be invoked.</param>
        /// <param name="inputs">The inputs to the method.</param>
        /// <param name="outputs">The outputs from the method.</param>
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            object result = null;
            // Create the Wcf audit event
            var auditWcfEvent = CreateWcfAuditEvent(instance, inputs);
            // Create the audit scope
            var eventType     = _eventType.Replace("{contract}", auditWcfEvent.ContractName).Replace("{operation}", auditWcfEvent.OperationName);
            var auditEventWcf = new AuditEventWcfAction()
            {
                WcfEvent = auditWcfEvent
            };
            // Create the audit scope
            var auditScope = AuditScope.Create(new AuditScopeOptions()
            {
                EventType      = eventType,
                CreationPolicy = EventCreationPolicy.Manual,
                AuditEvent     = auditEventWcf,
                DataProvider   = GetAuditDataProvider(instance),
                CallingMethod  = _operationDescription.SyncMethod
            });

            // Store a reference to this audit scope on a thread static field
            AuditBehavior.CurrentAuditScope = auditScope;
            try
            {
                result = _baseInvoker.Invoke(instance, inputs, out outputs);
            }
            catch (Exception ex)
            {
                AuditBehavior.CurrentAuditScope = null;
                auditWcfEvent.Fault             = GetWcfFaultData(ex);
                auditWcfEvent.Success           = false;
                SaveAuditScope(auditScope, auditWcfEvent);
                throw;
            }
            AuditBehavior.CurrentAuditScope = null;
            auditWcfEvent.OutputParameters  = GetEventElements(outputs);
            auditWcfEvent.Result            = new AuditWcfEventElement(result);
            SaveAuditScope(auditScope, auditWcfEvent);
            return(result);
        }
        public void Redis_String_Ttl()
        {
            var key = Guid.NewGuid().ToString();

            Core.Configuration.Setup()
            .UseRedis(redis => redis
                      .ConnectionString(RedisCnnString)
                      .AsString(s => s
                                .Key(ev => key)
                                .TimeToLive(TimeSpan.FromSeconds(5))));

            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
                EventType = "Redis_String_Ttl"
            }))
            {
                scope.SetCustomField("custom", new List <int>()
                {
                    2, 3, 4, 5
                });
            }

            var mx    = GetMultiplexer();
            var db    = mx.GetDatabase();
            var value = db.StringGet(key);
            var aev   = Newtonsoft.Json.JsonConvert.DeserializeObject <AuditEvent>(value);

            Task.Delay(5500).Wait();

            var exists = db.KeyExists(key);
            var value2 = db.StringGet(key);

            Assert.IsFalse(exists);
            Assert.IsFalse(value2.HasValue);

            Assert.AreEqual("Redis_String_Ttl", aev.EventType);
            Assert.AreEqual(new List <int>()
            {
                2, 3, 4, 5
            }, (aev.CustomFields["custom"] as JToken).ToObject <List <int> >());
        }
Exemple #10
0
        public void Test_AuditDisable_AllDisabled()
        {
            var list = new List <AuditEvent>();

            Audit.Core.Configuration.Setup()
            .AuditDisabled(true)
            .Use(x => x
                 .OnInsertAndReplace(ev =>
            {
                list.Add(ev);
            }))
            .WithCreationPolicy(EventCreationPolicy.InsertOnStartReplaceOnEnd);

            using (var scope = AuditScope.Create("", null, null))
            {
                scope.Save();
                scope.SaveAsync().Wait();
            }
            Audit.Core.Configuration.AuditDisabled = false;
            Assert.AreEqual(0, list.Count);
        }
Exemple #11
0
        public void Test_AuditScope_SetTargetGetter_IsNull()
        {
            var evs = new List <AuditEvent>();

            Audit.Core.Configuration.Setup()
            .Use(x => x
                 .OnInsertAndReplace(ev =>
            {
                evs.Add(ev);
            }))
            .WithCreationPolicy(EventCreationPolicy.InsertOnEnd);


            using (var scope = AuditScope.Create("Test", () => new { ShouldNotUseThisObject = true }))
            {
                scope.SetTargetGetter(null);
            }

            Assert.AreEqual(1, evs.Count);
            Assert.IsNull(evs[0].Target);
        }
Exemple #12
0
        public void Test_CustomAction_OnSaving_Discard()
        {
            var provider = new Mock <AuditDataProvider>();

            provider.Setup(p => p.Serialize(It.IsAny <string>())).CallBase();
            var eventType = "event type 1";
            var target    = "test";

            Audit.Core.Configuration.AddCustomAction(ActionType.OnEventSaving, scope =>
            {
                scope.Discard();
            });
            AuditEvent ev;

            using (var scope = AuditScope.Create(eventType, () => target, EventCreationPolicy.Manual, provider.Object))
            {
                ev = scope.Event;
                scope.Save();
            }
            Core.Configuration.ResetCustomActions();
            provider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Never);
        }
Exemple #13
0
        public void Test_EventCreationPolicy_Manual()
        {
            var provider = A.Fake <AuditDataProvider>();

            AuditConfiguration.SetDataProvider(provider);
            using (var scope = AuditScope.Create("SomeEvent", () => "target", EventCreationPolicy.Manual))
            {
                scope.Comment("test");
            }
            A.CallTo(() => provider.InsertEvent(A <AuditEvent> .Ignored)).MustHaveHappened(Repeated.Never);

            using (var scope = AuditScope.Create("SomeEvent", () => "target", EventCreationPolicy.Manual))
            {
                scope.Comment("test");
                scope.Save();
                scope.Comment("test2");
                scope.Save();
            }
            A.CallTo(() => provider.ReplaceEvent(A <object> .Ignored, A <AuditEvent> .Ignored))
            .MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => provider.InsertEvent(A <AuditEvent> .Ignored)).MustHaveHappened(Repeated.Exactly.Once);
        }
        /// <inheritdoc />
        public virtual void Update(TEntity item)
        {
            var     isServiceException = false;
            TKey    id       = item.Id;
            TEntity original = ReadOnlyRepository.Retrieve(item.Id);

            try
            {
                using (var auditScope = AuditScope.Create($"{EntityName}:Update", () => original))
                {
                    auditScope.Event.Environment.UserName = UserContext.CurrentUser;
                    auditScope.Event.Target.Type          = $"{EntityFullName}";

                    try
                    {
                        DecoratedService.Update(item);
                    }
                    catch
                    {
                        isServiceException = true;
                        auditScope.Discard();
                        throw;
                    }

                    // Assign the updated item back to the original. This allows Audit.NET to determine what was
                    // changed.
                    original = item;
                }
            }
            catch (Exception e)
            {
                if (isServiceException)
                {
                    throw;
                }

                Logger.Warning(e, "Auditing failed for Update of type {Entity} with ID {Id}.", EntityName, id);
            }
        }
Exemple #15
0
        public void Test_DynamicDataProvider()
        {
            int onInsertCount = 0, onReplaceCount = 0, onInsertOrReplaceCount = 0;

            Core.Configuration.Setup()
            .UseDynamicProvider(config => config
                                .OnInsert(ev => onInsertCount++)
                                .OnReplace((obj, ev) => onReplaceCount++)
                                .OnInsertAndReplace(ev => onInsertOrReplaceCount++));

            var scope = AuditScope.Create("et1", null, EventCreationPolicy.Manual);

            scope.Save();
            scope.SetCustomField("field", "value");
            Assert.AreEqual(1, onInsertCount);
            Assert.AreEqual(0, onReplaceCount);
            Assert.AreEqual(1, onInsertOrReplaceCount);
            scope.Save();
            Assert.AreEqual(1, onInsertCount);
            Assert.AreEqual(1, onReplaceCount);
            Assert.AreEqual(2, onInsertOrReplaceCount);
        }
Exemple #16
0
        public void Test_EventCreationPolicy_Manual()
        {
            var provider = new Mock <AuditDataProvider>();

            provider.Setup(p => p.InsertEvent(It.IsAny <AuditEvent>())).Returns(() => Guid.NewGuid());
            Core.Configuration.DataProvider = provider.Object;
            using (var scope = AuditScope.Create("SomeEvent", () => "target", EventCreationPolicy.Manual))
            {
                scope.Comment("test");
            }
            provider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Never);

            using (var scope = AuditScope.Create("SomeEvent", () => "target", EventCreationPolicy.Manual))
            {
                scope.Comment("test");
                scope.Save();
                scope.Comment("test2");
                scope.Save();
            }
            provider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once);
            provider.Verify(p => p.ReplaceEvent(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Once);
        }
Exemple #17
0
        public void Redis_String_CustomSerializer()
        {
            var ids = new List <object>();
            var key = Guid.NewGuid().ToString();

            Core.Configuration.Setup()
            .UseRedis(redis => redis
                      .ConnectionString(RedisCnnString)
                      .Serializer(ev => new byte[] { 1, 2, 4, 8 })
                      .Deserializer(b => new AuditEvent()
            {
                EventType = "deserializer test"
            })
                      .AsString(s => s
                                .Key(ev => key)))
            .WithCreationPolicy(EventCreationPolicy.InsertOnStartReplaceOnEnd)
            .WithAction(_ => _.OnEventSaved(scope =>
            {
                ids.Add(scope.EventId);
            }));

            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
            }))
            {
            }

            var mx        = GetMultiplexer();
            var db        = mx.GetDatabase();
            var value     = (byte[])db.StringGet(key);
            var evFromApi = Configuration.DataProvider.GetEvent(ids[0]);

            db.KeyDelete(key);
            Configuration.ResetCustomActions();

            Assert.AreEqual(2, ids.Count);
            Assert.AreEqual("deserializer test", evFromApi.EventType);
            Assert.AreEqual(new byte[] { 1, 2, 4, 8 }, value);
        }
Exemple #18
0
        public void Redis_PubSub_Basic()
        {
            var key = Guid.NewGuid().ToString();

            Core.Configuration.Setup()
            .UseRedis(redis => redis
                      .ConnectionString(RedisCnnString)
                      .AsPubSub(h => h
                                .Channel("mychannel:audit")))
            .WithCreationPolicy(EventCreationPolicy.InsertOnEnd);

            var mx   = GetMultiplexer();
            var list = new List <AuditEvent>();
            var subs = mx.GetSubscriber();

            subs.Subscribe("mychannel:audit", (ch, x) =>
            {
                list.Add(Configuration.JsonAdapter.Deserialize <AuditEvent>(x));
            });

            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
                EventType = "Redis_PubSub_Basic_1"
            })) {}

            Task.Delay(500).Wait();

            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
                EventType = "Redis_PubSub_Basic_2"
            })) {}

            Task.Delay(1000).Wait();

            Assert.AreEqual(2, list.Count);
            Assert.AreEqual("Redis_PubSub_Basic_1", list[0].EventType);
            Assert.AreEqual("Redis_PubSub_Basic_2", list[1].EventType);
        }
Exemple #19
0
        public void Test_NLog_InsertOnStartReplaceOnEnd()
        {
            Audit.Core.Configuration.Setup()
            .UseNLog(_ => _
                     .LogLevel(NLog.LogLevel.Info));

            _adapter.Logs.Clear();

            using (var s = AuditScope.Create(new AuditScopeOptions()
            {
                CreationPolicy = EventCreationPolicy.InsertOnStartReplaceOnEnd,
                EventType = nameof(Test_NLog_InsertOnStartReplaceOnEnd)
            }))
            {
            }

            var events = _adapter.Logs.Select(l => new NLogObject(l)).ToArray();

            Assert.AreEqual(2, events.Length);
            Assert.AreEqual(nameof(Test_NLog_InsertOnStartReplaceOnEnd), JsonConvert.DeserializeObject <AuditEvent>(events[0].MessageObject).EventType);
            Assert.AreEqual(nameof(Test_NLog_InsertOnStartReplaceOnEnd), JsonConvert.DeserializeObject <AuditEvent>(events[1].MessageObject).EventType);
            Assert.AreEqual(JsonConvert.DeserializeObject <AuditEvent>(events[0].MessageObject).CustomFields["EventId"], JsonConvert.DeserializeObject <AuditEvent>(events[1].MessageObject).CustomFields["EventId"]);
        }
Exemple #20
0
        public void TestDiscard()
        {
            var provider = new Mock <AuditDataProvider>();

            provider.Setup(p => p.Serialize(It.IsAny <string>())).CallBase();
            Core.Configuration.DataProvider = provider.Object;
            var        target    = "initial";
            var        eventType = "SomeEvent";
            AuditEvent ev;

            using (var scope = AuditScope.Create(eventType, () => target, EventCreationPolicy.InsertOnEnd))
            {
                ev = scope.Event;
                scope.Comment("test");
                scope.SetCustomField <string>("custom", "value");
                target = "final";
                scope.Discard();
            }
            Assert.AreEqual(eventType, ev.EventType);
            Assert.True(ev.Comments.Contains("test"));
            Assert.Null(ev.Target.SerializedNew);
            provider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Never);
        }
Exemple #21
0
        public void TestSave()
        {
            var provider = new Mock <AuditDataProvider>();

            provider.Setup(p => p.Serialize(It.IsAny <string>())).CallBase();
            Core.Configuration.DataProvider = provider.Object;
            var        target    = "initial";
            var        eventType = "SomeEvent";
            AuditEvent ev;

            using (var scope = AuditScope.Create(eventType, () => target, EventCreationPolicy.InsertOnEnd))
            {
                ev = scope.Event;
                scope.Comment("test");
                scope.SetCustomField <string>("custom", "value");
                target = "final";
                scope.Save(); // this should do nothing because of the creation policy (this no more true since v4.6.2)
                provider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once);
            }
            Assert.AreEqual(eventType, ev.EventType);
            Assert.True(ev.Comments.Contains("test"));
            provider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Exactly(2));
        }
Exemple #22
0
        public void Test_AuditScope_Create_FluentApi()
        {
            var scope = AuditScope.Create(_ => _
                                          .EventType("event type")
                                          .ExtraFields(new { f = 1 })
                                          .CreationPolicy(EventCreationPolicy.Manual)
                                          .AuditEvent(new AuditEventEntityFramework())
                                          .DataProvider(new DynamicDataProvider())
                                          .IsCreateAndSave(true)
                                          .SkipExtraFrames(1)
                                          .Target(() => 1)
                                          .CallingMethod(MethodBase.GetCurrentMethod()));

            Assert.AreEqual("event type", scope.EventType);
            Assert.AreEqual("event type", scope.Event.EventType);
            Assert.IsTrue(scope.Event.CustomFields.ContainsKey("f"));
            Assert.AreEqual(EventCreationPolicy.Manual, scope.EventCreationPolicy);
            Assert.AreEqual(typeof(AuditEventEntityFramework), scope.Event.GetType());
            Assert.AreEqual(typeof(DynamicDataProvider), scope.DataProvider.GetType());
            Assert.AreEqual(SaveMode.InsertOnStart, scope.SaveMode);
            Assert.AreEqual("1", scope.Event.Target.Old.ToString());
            Assert.IsTrue(scope.Event.Environment.CallingMethodName.Contains(MethodBase.GetCurrentMethod().Name));
        }
        /// <inheritdoc />
        public virtual void Delete(TEntity item)
        {
            TKey id = item.Id;

            DecoratedService.Delete(item);

            try
            {
                using (var auditScope = AuditScope.Create($"{EntityName}:Delete", () => item))
                {
                    auditScope.Event.Environment.UserName = UserContext.CurrentUser;
                    auditScope.Event.Target.Type          = $"{EntityFullName}";

                    // Set the deleted item to null. This prevents Audit.NET from replicating the audit details of the
                    // "Old" object into "New".
                    item = default;
                }
            }
            catch (Exception e)
            {
                Logger.Warning(e, "Auditing failed for Delete of type {Entity} with ID {Id}.", EntityName, id);
            }
        }
Exemple #24
0
        public void Test_log4net_InsertOnStartReplaceOnEnd()
        {
            Audit.Core.Configuration.Setup()
            .UseLog4net(_ => _
                        .LogLevel(LogLevel.Info));

            _adapter.Clear();

            using (var s = AuditScope.Create(new AuditScopeOptions()
            {
                CreationPolicy = EventCreationPolicy.InsertOnStartReplaceOnEnd,
                EventType = "Test_log4net_InsertOnStartReplaceOnEnd"
            }))
            {
            }

            var events = _adapter.PopAllEvents();

            Assert.AreEqual(2, events.Length);
            Assert.AreEqual("Test_log4net_InsertOnStartReplaceOnEnd", JsonConvert.DeserializeObject <AuditEvent>(events[0].MessageObject.ToString()).EventType);
            Assert.AreEqual("Test_log4net_InsertOnStartReplaceOnEnd", JsonConvert.DeserializeObject <AuditEvent>(events[1].MessageObject.ToString()).EventType);
            Assert.AreEqual(JsonConvert.DeserializeObject <AuditEvent>(events[0].MessageObject.ToString()).CustomFields["EventId"], JsonConvert.DeserializeObject <AuditEvent>(events[1].MessageObject.ToString()).CustomFields["EventId"]);
        }
        /// <summary>
        /// Occurs before the action method is invoked.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var request        = actionContext.Request;
            var contextWrapper = new ContextWrapper(request);

            var auditAction = new AuditApiAction
            {
                UserName         = actionContext.RequestContext?.Principal?.Identity?.Name,
                IpAddress        = contextWrapper.GetClientIp(),
                RequestUrl       = request.RequestUri?.AbsoluteUri,
                HttpMethod       = actionContext.Request.Method?.Method,
                FormVariables    = contextWrapper.GetFormVariables(),
                Headers          = IncludeHeaders ? ToDictionary(request.Headers) : null,
                ActionName       = actionContext.ActionDescriptor?.ActionName,
                ControllerName   = actionContext.ActionDescriptor?.ControllerDescriptor?.ControllerName,
                ActionParameters = actionContext.ActionArguments,
                RequestBody      = IncludeRequestBody ? GetRequestBody(contextWrapper) : null
            };
            var eventType = (EventTypeName ?? "{verb} {controller}/{action}").Replace("{verb}", auditAction.HttpMethod)
                            .Replace("{controller}", auditAction.ControllerName)
                            .Replace("{action}", auditAction.ActionName);
            // Create the audit scope
            var auditEventAction = new AuditEventWebApi()
            {
                Action = auditAction
            };
            var options = new AuditScopeOptions()
            {
                EventType     = eventType,
                AuditEvent    = auditEventAction,
                CallingMethod = (actionContext.ActionDescriptor as ReflectedHttpActionDescriptor)?.MethodInfo
            };
            var auditScope = AuditScope.Create(options);

            contextWrapper.Set(AuditApiActionKey, auditAction);
            contextWrapper.Set(AuditApiScopeKey, auditScope);
        }
Exemple #26
0
        public void Redis_SortedSet_CustomSerializer()
        {
            var    key = Guid.NewGuid().ToString();
            object id;
            var    random      = new byte[] { 15, 4, 9, 22, 10, 14 };
            var    deserialize = new AuditEvent()
            {
                EventType = "test 123"
            };

            Configuration.CreationPolicy = EventCreationPolicy.InsertOnEnd;

            var dp = new RedisDataProviderHelper(RedisCnnString, ev => random, b => deserialize)
                     .AsSortedSet(s => s
                                  .Key(ev => key)
                                  .Score(ev => 1));

            Configuration.Setup().UseCustomProvider(dp);

            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
                DataProvider = dp
            }))
            {
                scope.Save();
                id = scope.EventId;
            }

            var mx     = GetMultiplexer();
            var db     = mx.GetDatabase();
            var values = db.SortedSetRangeByScore(key, 1, 1);

            db.KeyDelete(key);
            Configuration.ResetCustomActions();

            Assert.AreEqual(random, (byte[])values[0]);
        }
Exemple #27
0
        public void Test_DataProviderFactory()
        {
            GetProviderCount = 0;
            var options = new AuditScopeOptions(_ => _.DataProvider(GetProvider).CreationPolicy(EventCreationPolicy.InsertOnStartReplaceOnEnd));

            Assert.AreEqual(0, GetProviderCount);
            using (var scope = AuditScope.Create(options))
            {
                Assert.AreEqual(1, GetProviderCount);
                scope.SetCustomField("custom", "value");
                scope.Save();
            }
            Assert.AreEqual(1, GetProviderCount);
            options = new AuditScopeOptions(_ => _.DataProvider(GetProvider).CreationPolicy(EventCreationPolicy.Manual));
            using (var scope = new AuditScope(options))
            {
                Assert.AreEqual(2, GetProviderCount);
                scope.Save();
                scope.Save();
            }
            Assert.AreEqual(2, GetProviderCount);
            Audit.Core.Configuration.DataProviderFactory = GetProvider;
            using (var scope = AuditScope.Create("Test", null, new { custom = "value" }))
            {
                Assert.AreEqual(3, GetProviderCount);
                scope.Discard();
            }
            Assert.AreEqual(3, GetProviderCount);

            Audit.Core.Configuration.Setup().UseFactory(GetProvider);
            using (var scope = AuditScope.Create("Test", null, new { custom = "value" }))
            {
                Assert.AreEqual(4, GetProviderCount);
                scope.Save();
            }
            Assert.AreEqual(4, GetProviderCount);
        }
        public void Redis_SortedSet_Basic()
        {
            var key = Guid.NewGuid().ToString();

            Core.Configuration.Setup()
            .UseRedis(redis => redis
                      .ConnectionString(RedisCnnString)
                      .AsSortedSet(h => h
                                   .Key(ev => key)
                                   .Score(ev => (double)ev.CustomFields["Score"])));

            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
                EventType = "Redis_SortedSet_Basic_1", ExtraFields = new { Score = 12.34 }
            }))
            {
            }
            using (var scope = AuditScope.Create(new AuditScopeOptions()
            {
                EventType = "Redis_SortedSet_Basic_2", ExtraFields = new { Score = -56.78 }
            }))
            {
            }

            var mx     = GetMultiplexer();
            var db     = mx.GetDatabase();
            var values = db.SortedSetRangeByRankWithScores(key);

            db.KeyDelete(key);

            Assert.AreEqual(2, values.Length);
            Assert.AreEqual(-56.78, values[0].Score);
            Assert.AreEqual("Redis_SortedSet_Basic_2", JsonConvert.DeserializeObject <AuditEvent>(values[0].Element).EventType);
            Assert.AreEqual(12.34, values[1].Score);
            Assert.AreEqual("Redis_SortedSet_Basic_1", JsonConvert.DeserializeObject <AuditEvent>(values[1].Element).EventType);
        }
Exemple #29
0
        public void Test_AuditScopeCreation_WithExistingAuditEvent_WithEventType()
        {
            var evs = new List <AuditEvent>();

            Audit.Core.Configuration.Setup()
            .AuditDisabled(false)
            .UseDynamicProvider(x => x
                                .OnInsertAndReplace(ev =>
            {
                evs.Add(AuditEvent.FromJson(ev.ToJson()));
            }))
            .WithCreationPolicy(EventCreationPolicy.InsertOnEnd);

            var auditEvent = new AuditEvent()
            {
                EventType = "test"
            };
            var options = new AuditScopeOptions()
            {
                EventType  = null, // NULL means do not override eventtype
                AuditEvent = auditEvent
            };

            // scope with pre-assigned event type
            using (var scope = AuditScope.Create(options))
            {
            }
            // scope with event type to override
            options.EventType = "override";
            using (var scope = AuditScope.Create(options))
            {
            }
            Assert.AreEqual(2, evs.Count);
            Assert.AreEqual("test", evs[0].EventType);
            Assert.AreEqual("override", evs[1].EventType);
        }
Exemple #30
0
        public void Test_Elastic_HappyPath()
        {
            var ins  = new List <Core.AuditEvent>();
            var repl = new List <Core.AuditEvent>();
            var ela  = GetMockElasticsearchDataProvider(ins, repl);

            var guids = new List <string>();

            ela.IndexBuilder = ev => "auditevent";
            ela.IdBuilder    = ev => { var g = Guid.NewGuid().ToString().Replace("-", "/"); guids.Add(g); return(g); };

#pragma warning disable CS0618 // Type or member is obsolete
            ela.TypeNameBuilder = ev => "spe/c/ial";
#pragma warning restore CS0618 // Type or member is obsolete

            Audit.Core.Configuration.Setup()
            .UseCustomProvider(ela)
            .WithCreationPolicy(Core.EventCreationPolicy.InsertOnStartReplaceOnEnd)
            .ResetActions();

            var sb = "init";


            using (var scope = AuditScope.Create("eventType", () => sb, new { MyCustomField = "value" }))
            {
                sb += "-end";
            }

            Assert.AreEqual(1, guids.Count);
            Assert.AreEqual(1, ins.Count);
            Assert.AreEqual(1, repl.Count);
            Assert.AreEqual("\"init\"", ins[0].Target.SerializedOld);
            Assert.AreEqual(null, ins[0].Target.SerializedNew);
            Assert.AreEqual("\"init\"", repl[0].Target.SerializedOld);
            Assert.AreEqual("\"init-end\"", repl[0].Target.SerializedNew);
        }