예제 #1
0
        /// <summary>
        /// Grants access to a table.
        /// </summary>
        private async Task <IResponse> Grant(IRequestContext request, Route route)
        {
            string tableName = GetAndValidateTableName(route);

            if (!this.Database.TableExists(tableName))
            {
                return(ArribaResponse.NotFound("Table not found to grant permission on."));
            }

            var identity = await request.Request.ReadBodyAsync <SecurityIdentity>();

            if (String.IsNullOrEmpty(identity.Name))
            {
                return(ArribaResponse.BadRequest("Identity name must not be empty"));
            }

            PermissionScope scope;

            if (!Enum.TryParse <PermissionScope>(route["scope"], true, out scope))
            {
                return(ArribaResponse.BadRequest("Unknown permission scope {0}", route["scope"]));
            }

            using (request.Monitor(MonitorEventLevel.Information, "GrantPermission", type: "Table", identity: tableName, detail: new { Scope = scope, Identity = identity }))
            {
                SecurityPermissions security = this.Database.Security(tableName);
                security.Grant(identity.Scope, identity.Name, scope);

                // Save permissions
                this.Database.SaveSecurity(tableName);
            }

            return(ArribaResponse.Ok("Granted"));
        }
예제 #2
0
        protected bool HasPermission(SecurityPermissions security, IPrincipal currentUser, PermissionScope scope)
        {
            // No user identity? Forbidden!
            if (currentUser == null || !currentUser.Identity.IsAuthenticated)
            {
                return(false);
            }

            // Try user first, cheap check.
            if (security.IsIdentityInPermissionScope(IdentityScope.User, currentUser.Identity.Name, scope))
            {
                return(true);
            }

            // See if the user is in any allowed groups.
            foreach (var group in security.GetScopeIdentities(scope, IdentityScope.Group))
            {
                if (_claimsAuth.IsUserInGroup(currentUser, group.Name))
                {
                    return(true);
                }
            }

            return(false);
        }
예제 #3
0
        public SecurityPermissions Security(string tableName)
        {
            SecurityPermissions security;

            if (_securityByTable.TryGetValue(tableName, out security))
            {
                // Return cached Security, if found
                return(security);
            }
            else
            {
                // Construct a new [empty] SecurityPermissions
                security = new SecurityPermissions();

                // Load previously serialized permissions if found
                string securityPath = SecurityCachePath(tableName);
                if (File.Exists(securityPath))
                {
                    security.Read(securityPath);
                }

                // Cache the created|loaded security
                lock (_tableLock)
                {
                    _securityByTable[tableName] = security;
                }

                return(security);
            }
        }
예제 #4
0
 public void SetSecurity(string tableName, SecurityPermissions security)
 {
     lock (_tableLock)
     {
         _securityByTable[tableName] = security;
     }
 }
예제 #5
0
        public void CreateTable(IList <ColumnDetails> columns, SecurityPermissions permissions)
        {
            this.Table = new Table(this.Configuration.ArribaTable, this.Configuration.ItemCountLimit);

            // Try to load the table if it already exists
            if (BinarySerializable.EnumerateUnder(Path.Combine("Tables", this.Configuration.ArribaTable)).Count() > 0)
            {
                Trace.WriteLine(string.Format("Loading Arriba Table '{0}'...", this.Configuration.ArribaTable));
                this.Table.Load(this.Configuration.ArribaTable);
            }

            // Columns are added dynamically by Append

            // Set the table security
            SecureDatabase sdb = new SecureDatabase();

            sdb.SetSecurity(this.Configuration.ArribaTable, permissions);
            sdb.SaveSecurity(this.Configuration.ArribaTable);

            // Debug Only: Verify consistency just after load
            if (this.DiagnosticsEnabled)
            {
                Trace.WriteLine("Verifying Arriba Table consistency [on load]...");

                ExecutionDetails d = new ExecutionDetails();
                this.Table.VerifyConsistency(this.DiagnosticsLevel, d);

                if (!d.Succeeded)
                {
                    Debugger.Break();
                    Trace.TraceError(String.Format("Consistency Errors Detected: {0}", String.Join("\r\n", d.Errors)));
                }
            }
        }
예제 #6
0
        public void CreateTable(IList <ColumnDetails> columns, SecurityPermissions permissions)
        {
            this.Table = new Table(this.Configuration.ArribaTable, this.Configuration.ItemCountLimit);

            // Try to load the table if it already exists
            if (BinarySerializable.EnumerateUnder(Path.Combine("Tables", this.Configuration.ArribaTable)).Count() > 0)
            {
                Trace.WriteLine(string.Format("Loading Arriba Table '{0}'...", this.Configuration.ArribaTable));
                this.Table.Load(this.Configuration.ArribaTable);
            }

            // Verify all columns match requested types [will throw if column exists but as different type]
            foreach (ColumnDetails cd in columns)
            {
                this.Table.AddColumn(cd);
            }

            // Set the table security
            new SecureDatabase().SetSecurity(this.Configuration.ArribaTable, permissions);

            // Debug Only: Verify consistency just after load
            if (this.DiagnosticsEnabled)
            {
                Trace.WriteLine("Verifying Arriba Table consistency [on load]...");

                ExecutionDetails d = new ExecutionDetails();
                this.Table.VerifyConsistency(this.DiagnosticsLevel, d);

                if (!d.Succeeded)
                {
                    Debugger.Break();
                    Trace.TraceError(String.Format("Consistency Errors Detected: {0}", String.Join("\r\n", d.Errors)));
                }
            }
        }
 public void CreateTable(IList <ColumnDetails> columns, SecurityPermissions permissions)
 {
     foreach (IItemConsumer consumer in this.InnerConsumers)
     {
         consumer.CreateTable(columns, permissions);
     }
 }
        private void SecureSampleDB(SecureDatabase db)
        {
            SecurityPermissions security = db.Security(sampleTableName);

            security.RestrictedColumns.Add(SecurityIdentity.Create(IdentityScope.Group, "G1"), new List <string>(new string[] { "SecretOwner" }));
            security.RestrictedColumns.Add(SecurityIdentity.Create(IdentityScope.Group, "G2"), new List <string>(new string[] { "SecretPriority" }));
            security.RowRestrictedUsers.Add(SecurityIdentity.Create(IdentityScope.Group, "G3"), "SecretPriority > 1");
            security.RowRestrictedUsers.Add(SecurityIdentity.Create(IdentityScope.Group, "G4"), "SecretPriority > 2");
        }
예제 #9
0
        public async Task SetPermissionsAsync(SecurityPermissions permissions)
        {
            var resp = await _client.SendObjectAsync(
                HttpMethod.Post,
                String.Format("table/{0}/permissions", _tableName),
                value : permissions);

            await resp.EnsureArribaSuccess();

            return;
        }
 /// <summary>
 /// When New symbol is Subscribed
 /// Saving its Permissions in a dictionary
 /// </summary>
 /// <param name="securityPermissions"></param>
 public void OnSymbolSubscribed(SecurityPermissions securityPermissions)
 {
     if (Logger.IsDebugEnabled)
     {
         Logger.Info(securityPermissions.ToString(), _oType.FullName, "OnSymbolSubscribed");
     }
     try
     {
         SecurityPermissionDictionary.Add(securityPermissions.Security.Symbol, securityPermissions);
     }
     catch (Exception exception)
     {
         Logger.Error(exception, _oType.FullName, "OnSymbolSubscribed");
     }
 }
예제 #11
0
 /// <summary>
 /// When User Subscribe to New Symbol.
 /// </summary>
 /// <param name="security"></param>
 private void SubscribeToNewSymbol(SecurityPermissions security)
 {
     if (Logger.IsInfoEnabled)
     {
         Logger.Info(security.ToString(), _oType.FullName, "SubscribeToNewSymbol");
     }
     if (!SecurityStatDictionary[SelectedProvider.ProviderName].Any(x => x.Symbol == security.Security.Symbol))
     {
         SecutiryList.Add(security);
         SecurityStatDictionary[SelectedProvider.ProviderName].Add(new SecurityStatisticsViewModel
         {
             Symbol = security.Security.Symbol, Id = security.Id, ProviderName = SelectedProvider.ProviderName
         });
         ReloadList(SelectedProvider);
     }
 }
예제 #12
0
        private async Task <IResponse> SetTablePermissions(IRequestContext request, Route route)
        {
            SecurityPermissions security = await request.Request.ReadBodyAsync <SecurityPermissions>();

            string tableName = GetAndValidateTableName(route);

            if (!this.Database.TableExists(tableName))
            {
                return(ArribaResponse.NotFound("Table doesn't exist to update security for."));
            }

            // Reset table permissions and save them
            this.Database.SetSecurity(tableName, security);
            this.Database.SaveSecurity(tableName);

            return(ArribaResponse.Ok("Security Updated"));
        }
예제 #13
0
        public IList <string> GetRestrictedColumns(string tableName, Func <SecurityIdentity, bool> isCurrentUserIn)
        {
            List <string>       restrictedColumns = null;
            SecurityPermissions security          = this.Security(tableName);

            foreach (var columnRestriction in security.RestrictedColumns)
            {
                if (!isCurrentUserIn(columnRestriction.Key))
                {
                    if (restrictedColumns == null)
                    {
                        restrictedColumns = new List <string>();
                    }
                    restrictedColumns.AddRange(columnRestriction.Value);
                }
            }
            return(restrictedColumns);
        }
 /// <summary>
 /// Chnage Permission of Symbol
 /// </summary>
 /// <param name="securityPermissions"></param>
 public void ChangeSecurityPermission(SecurityPermissions securityPermissions)
 {
     try
     {
         if (Logger.IsInfoEnabled)
         {
             Logger.Info(securityPermissions.ToString(), _oType.FullName, "ChangeSecurityPermission");
         }
         if (SecurityPermissionDictionary[securityPermissions.Security.Symbol] != null)
         {
             SecurityPermissionDictionary[securityPermissions.Security.Symbol] = securityPermissions;
         }
     }
     catch (Exception exception)
     {
         Logger.Error(exception, _oType.FullName, "ChangeSecurityPermission");
     }
 }
예제 #15
0
        /// <summary>
        /// Get Requset From User And forwards it to MarketDataEngine
        /// </summary>
        /// <param name="subscribe"></param>
        public void RequestDataFromMarketDataEngine(SecurityPermissions subscribe)
        {
            try
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug(subscribe.ToString(), _oType.FullName, "RequestDataFromMarketDataEngine");
                }
                _responseHandler.OnSymbolSubscribed(subscribe);

                // Send Tick Subscription Request
                _marketDataService.Subscribe(subscribe);
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _oType.FullName, "RequestDataFromMarketDataEngine");
            }
        }
        /// <summary>
        /// Methord Fired When ever Permission Changes.
        /// </summary>
        private void PublishSecurityPermissionsChangeMessage()
        {
            SecurityPermissions permissions = new SecurityPermissions
            {
                Id = Id,
                MarketDataProvider = ProviderName,
                Security           = new Security {
                    Symbol = Symbol
                },
                WriteBars  = true,
                WriteQuote = QuoteChecked,
                WriteTrade = TradeChecked
            };
            ChangeSecurityPermissionsMessage changeSecurityPermissionsMessage = new ChangeSecurityPermissionsMessage();

            changeSecurityPermissionsMessage.Permissions = permissions;
            EventSystem.Publish <ChangeSecurityPermissionsMessage>(changeSecurityPermissionsMessage);
        }
예제 #17
0
        private static void SetTableCreators(string creators)
        {
            Console.WriteLine("Setting table creators...");

            SecurityPermissions createPermissions = new SecurityPermissions();

            foreach (string creator in creators.Split(';'))
            {
                string[]      parts = creator.Split(':');
                IdentityScope scope = parts[0].Equals("u", StringComparison.OrdinalIgnoreCase) ? IdentityScope.User : IdentityScope.Group;
                createPermissions.Grant(new SecurityIdentity(scope, parts[1]), PermissionScope.Owner);

                Console.WriteLine($" - {scope} {parts[1]}");
            }

            // Create table, if required
            SecureDatabase db = new SecureDatabase();

            db.SetSecurity("", createPermissions);
            db.SaveSecurity("");
        }
        public SecurityPermissions LoadPermissions()
        {
            SecurityPermissions result = new SecurityPermissions();

            foreach (SecurityIdentity identity in ParseIdentities(this.Owners))
            {
                result.Grant(identity, PermissionScope.Owner);
            }

            foreach (SecurityIdentity identity in ParseIdentities(this.Writers))
            {
                result.Grant(identity, PermissionScope.Writer);
            }

            foreach (SecurityIdentity identity in ParseIdentities(this.Readers))
            {
                result.Grant(identity, PermissionScope.Reader);
            }

            return(result);
        }
예제 #19
0
        public void SubscribeToNewSymbol()
        {
            DataViewModel viewModel = new DataViewModel();

            EventSystem.Publish <LoginArrivedMessage>(new LoginArrivedMessage {
                Provider = new Provider {
                    IsConnected = true, ProviderName = MarketDataProvider.Blackwood
                }
            });
            SecurityPermissions securityPermissions = new SecurityPermissions {
                Id = Guid.NewGuid().ToString(), MarketDataProvider = MarketDataProvider.Blackwood, Security = new Security {
                    Symbol = "AAPL"
                }
            };

            viewModel.SelectedProvider = new Provider {
                IsConnected = true, ProviderName = MarketDataProvider.Blackwood
            };
            EventSystem.Publish <SecurityPermissions>(securityPermissions);

            Assert.AreEqual(1, viewModel.SecurityStatDictionary[MarketDataProvider.Blackwood].Count);
        }
        public void CreateTable(IList <ColumnDetails> columns, SecurityPermissions permissions)
        {
            HashSet <string> tables = new HashSet <string>(this.Client.Tables);

            if (!tables.Contains(this.Configuration.ArribaTable))
            {
                // Create the table if it doesn't yet exist
                CreateTableRequest ctr = new CreateTableRequest();
                ctr.TableName      = this.Configuration.ArribaTable;
                ctr.ItemCountLimit = this.Configuration.ItemCountLimit;
                ctr.Permissions    = permissions;

                this.Client.CreateTableAsync(ctr).Wait();
            }
            else
            {
                // Always ensure permissions up-to-date on Table
                this.Table.SetPermissionsAsync(permissions).Wait();
            }

            // Columns will be added dynamically
        }
        public void CreateTable(IList <ColumnDetails> columns, SecurityPermissions permissions)
        {
            HashSet <string> tables = new HashSet <string>(this.Client.Tables);

            if (!tables.Contains(this.Configuration.ArribaTable))
            {
                // Create the table if it doesn't yet exist
                CreateTableRequest ctr = new CreateTableRequest();
                ctr.TableName      = this.Configuration.ArribaTable;
                ctr.ItemCountLimit = this.Configuration.ItemCountLimit;
                ctr.Permissions    = this.Configuration.LoadPermissions();

                this.Client.CreateTableAsync(ctr).Wait();
            }
            else
            {
                // Always ensure permissions up-to-date on Table
                this.Table.SetPermissionsAsync(permissions).Wait();
            }

            // Verify all columns match requested types [will throw if column exists but as different type]
            this.Table.AddColumnsAsync(columns).Wait();
        }
예제 #22
0
        private static async Task Example()
        {
            using (var client = new ArribaClient(ArribaServerUrl))
            {
                // Create Table [2 Partition Bits = 4 Partitions = 256k items]
                CreateTableRequest tableRequest = new CreateTableRequest("Test_" + DateTime.Now.Ticks.ToString(), 2);
                tableRequest.Columns.Add(new ColumnDetails("ID", "int", -1, String.Empty, true));
                tableRequest.Columns.Add(new ColumnDetails("Name", "string", null));
                tableRequest.Columns.Add(new ColumnDetails("Age", "int", -1));
                var table = await client.CreateTableAsync(tableRequest);

                // Add columns (after creation)
                await table.AddColumnsAsync(new ColumnDetails[] { new ColumnDetails("Team", "string", null) });

                // Add items (CSV) [ID,Name,Age]
                using (MemoryStream ms = BuildSampleUserCsv())
                {
                    await table.ImportFileAsync(ms, "csv");
                }

                // Add items (DataBlock)
                DataBlock block = new DataBlock(
                    new string[] { "ID", "Name", "Age", "Team" },
                    1,
                    new Array[] {
                    new int[] { 4 },
                    new string[] { "Karl" },
                    new int[] { 30 },
                    new string[] { "VSPlat" }
                });
                await table.ImportDataBlock(block);

                // Get Table Information
                var d = await table.GetTableInformationAsync();

                // Select ID, Name WHERE Age = 32
                SelectResult selectResult = await table.Select(new SelectQuery(new string[] { "ID" }, "Age = 32"));

                Trace.WriteLine(String.Format("Found {0:n0} 32 year olds (expected 2)", selectResult.Total));

                // Aggregate COUNT(*) WHERE {ALL} BY Age < 30, Age >= 30
                AggregationQuery aggregateQuery = new AggregationQuery("Count", new string[] { "ID" }, "");
                aggregateQuery.Dimensions.Add(new AggregationDimension("Age", "Age < 30", "Age >= 30"));
                AggregationResult aggregateResult = await table.Aggregate(aggregateQuery);

                Trace.WriteLine(String.Format("Found {0:n0} under 30 year olds (expected 1)", aggregateResult.Values[0, 1]));
                Trace.WriteLine(String.Format("Found {0:n0} over 30 year olds (expected 3)", aggregateResult.Values[1, 1]));
                Trace.WriteLine(String.Format("Found {0:n0} altogether (expected 4)", aggregateResult.Values[2, 1]));

                // Delete WHERE ID = 2
                int countDeleted = await table.Delete(SelectQuery.ParseWhere("ID = 2"));

                Trace.WriteLine(String.Format("Deleted {0:n0} users (expected 1)", countDeleted));

                // Select ID, Name WHERE Age = 32 (again)
                selectResult = await table.Select(new SelectQuery(new string[] { "ID" }, "Age = 32"));

                Trace.WriteLine(String.Format("Found {0:n0} 32 year olds (expected 1)", selectResult.Total));

                // Add write permission to another user
                await table.GrantPermissionsAsync(Model.Security.PermissionScope.Reader, Model.Security.IdentityScope.User, "phil");

                SecurityPermissions permissions = await table.GetPermissionsAsync();

                Trace.WriteLine(String.Format("Expecting 'Phil' as reader. Readers: {0}", permissions.Readers.First().Name));

                // Deny myself write permission
                await table.RevokePermissionsAsync(Model.Security.PermissionScope.Reader, Model.Security.IdentityScope.User, "phil");

                permissions = await table.GetPermissionsAsync();

                Trace.WriteLine(String.Format("Found {0:n0} readers (expected 0)", permissions.Readers.Count()));

                // Delete table
                await table.DeleteAsync();
            }
        }
예제 #23
0
        protected void ApplyTableSecurity <T>(IQuery <T> query, Func <SecurityIdentity, bool> isCurrentUserIn, ExecutionDetails details)
        {
            SecurityPermissions security = this.Security(query.TableName);

            // If table has row restrictions and one matches, restrict rows and allow
            // NOTE: If restricted rows are returned, columns are NOT restricted.
            foreach (var rowRestriction in security.RowRestrictedUsers)
            {
                if (isCurrentUserIn(rowRestriction.Key))
                {
                    query.Where = new AndExpression(QueryParser.Parse(rowRestriction.Value), query.Where);
                    return;
                }
            }

            // If table has column restrictions, build a list of excluded columns
            IList <string> restrictedColumns = GetRestrictedColumns(query.TableName, isCurrentUserIn);

            // If no columns were restricted, return query as-is
            if (restrictedColumns == null)
            {
                return;
            }

            // Exclude disallowed columns from where clauses
            // If a disallowed column is requested specifically, block the query and return an error
            ColumnSecurityCorrector c = new ColumnSecurityCorrector(restrictedColumns);

            try
            {
                query.Correct(c);
            }
            catch (ArribaColumnAccessDeniedException e)
            {
                query.Where = new EmptyExpression();
                details.AddDeniedColumn(e.Message);
                details.AddError(ExecutionDetails.DisallowedColumnQuery, e.Message);
            }

            // If columns are excluded, remove those from the select list
            IQuery <T> primaryQuery = query;

            if (query is JoinQuery <T> )
            {
                primaryQuery = ((JoinQuery <T>)query).PrimaryQuery;
            }

            if (primaryQuery.GetType().Equals(typeof(SelectQuery)))
            {
                SelectQuery   sq = (SelectQuery)primaryQuery;
                List <string> filteredColumns = null;

                if (sq.Columns.Count == 1 && sq.Columns[0] == "*")
                {
                    filteredColumns = new List <string>();
                    foreach (ColumnDetails column in this[sq.TableName].ColumnDetails)
                    {
                        if (restrictedColumns.Contains(column.Name))
                        {
                            details.AddDeniedColumn(column.Name);
                        }
                        else
                        {
                            filteredColumns.Add(column.Name);
                        }
                    }
                }
                else
                {
                    foreach (string columnName in sq.Columns)
                    {
                        if (restrictedColumns.Contains(columnName))
                        {
                            if (filteredColumns == null)
                            {
                                filteredColumns = new List <string>(sq.Columns);
                            }
                            filteredColumns.Remove(columnName);

                            details.AddDeniedColumn(columnName);
                        }
                    }
                }

                if (filteredColumns != null)
                {
                    sq.Columns = filteredColumns;
                }
            }
            else if (primaryQuery.GetType().Equals(typeof(AggregationQuery)))
            {
                AggregationQuery aq = (AggregationQuery)primaryQuery;
                if (aq.AggregationColumns != null)
                {
                    foreach (string columnName in aq.AggregationColumns)
                    {
                        if (restrictedColumns.Contains(columnName))
                        {
                            details.AddDeniedColumn(columnName);
                            details.AddError(ExecutionDetails.DisallowedColumnQuery, columnName);
                            aq.Where = new EmptyExpression();
                        }
                    }
                }
            }
            else if (primaryQuery.GetType().Equals(typeof(DistinctQuery)))
            {
                DistinctQuery dq = (DistinctQuery)primaryQuery;
                if (restrictedColumns.Contains(dq.Column))
                {
                    details.AddDeniedColumn(dq.Column);
                    details.AddError(ExecutionDetails.DisallowedColumnQuery, dq.Column);
                    dq.Where = new EmptyExpression();
                }
            }
            else
            {
                // IQuery is extensible; there's no way to ensure that user-implemented
                // queries respect security rules.
                details.AddError(ExecutionDetails.DisallowedQuery, primaryQuery.GetType().Name);
                primaryQuery.Where = new EmptyExpression();
            }
        }
예제 #24
0
 public void CreateTable(IList <ColumnDetails> columns, SecurityPermissions permissions)
 {
 }
예제 #25
0
        public void ChangingSecurity()
        {
            var cachier = GetCachier();

            var modelReader   = Guid.NewGuid();
            var modelWriter   = Guid.NewGuid();
            var elementReader = Guid.NewGuid();
            var elementWriter = Guid.NewGuid();

            var elemPermissions = new SecurityPermissions
            {
                AllowedForRead  = new[] { elementReader },
                AllowedForWrite = new[] { elementWriter }
            };

            var modelPermissions = new SecurityPermissions
            {
                AllowedForRead  = new[] { modelReader },
                AllowedForWrite = new[] { modelWriter }
            };

            cachier.Post(_singleModel.Key, modelPermissions);
            cachier.Post(_dependentModel.Key, modelPermissions);
            cachier.Post(_singleElement.Key, elemPermissions);
            cachier.Post(_dependentElement.Key, elemPermissions);

            var user1 = Guid.NewGuid();
            var user2 = Guid.NewGuid();

            var group1 = new SecurityGroup {
                Groups = new[] { modelReader, elementReader, elementWriter }
            };

            var group2 = new SecurityGroup {
                Groups = new[] { modelReader, elementReader, modelWriter }
            };

            cachier.Post(user1, group1);
            cachier.Post(user2, group2);

            Session.UserId = user1;
            var elem = cachier.Get <Element>(_singleElement.Key);

            Assert.IsNotNull(elem);
            var model = cachier.Get <Model>(_singleModel.Key);

            Assert.IsNotNull(model);

            //запрещаем чтение из модели
            group1.Groups = new[] { elementReader, elementWriter };

            elem = cachier.Get <Element>(_singleElement.Key);
            Assert.IsNotNull(elem);
            model = cachier.Get <Model>(_singleModel.Key);
            Assert.IsNotNull(model);

            cachier.Post(user1, group1);
            elem = cachier.Get <Element>(_singleElement.Key);
            Assert.IsNotNull(elem);
            model = cachier.Get <Model>(_singleModel.Key);
            Assert.IsNull(model);
            MockHelper.AwaitException <SecurityException>(() => cachier.Post(_singleModel.Key, _singleModel));
            cachier.Post(_singleElement.Key, _singleElement);

            //разрешаем только запись во все
            group1.Groups = new[] { modelWriter, elementWriter };
            cachier.Post(user1, group1);
            cachier.Post(_singleModel.Key, _singleModel);
            cachier.Post(_singleElement.Key, _singleElement);

            Session.UserId = user2;
            elem           = cachier.Get <Element>(_singleElement.Key);
            Assert.IsNotNull(elem);
            model = cachier.Get <Model>(_singleModel.Key);
            Assert.IsNotNull(model);
            MockHelper.AwaitException <SecurityException>(() => cachier.Post(_singleElement.Key, _singleElement));
            cachier.Post(_singleModel.Key, _singleModel);
        }
예제 #26
0
        public void DeferredSecurity()
        {
            var cachier = GetCachier();

            ModelSecurityProvider.TimesWasUsed = 0;
            var modelReader   = Guid.NewGuid();
            var modelWriter   = Guid.NewGuid();
            var elementReader = Guid.NewGuid();
            var elementWriter = Guid.NewGuid();

            var elemPermissions = new SecurityPermissions
            {
                AllowedForRead  = new[] { elementReader },
                AllowedForWrite = new[] { elementWriter }
            };

            var modelPermissions = new SecurityPermissions
            {
                AllowedForRead  = new[] { modelReader },
                AllowedForWrite = new[] { modelWriter }
            };

            cachier.Post(_singleModel.Key, modelPermissions);
            cachier.Post(_dependentModel.Key, modelPermissions);
            cachier.Post(_singleElement.Key, elemPermissions);
            cachier.Post(_dependentElement.Key, elemPermissions);

            var user1 = Guid.NewGuid();
            var user2 = Guid.NewGuid();

            var group1 = new SecurityGroup {
                Groups = new[] { modelReader, elementReader, elementWriter }
            };

            var group2 = new SecurityGroup {
                Groups = new[] { modelReader, elementReader, modelWriter }
            };

            cachier.Post(user1, group1);
            cachier.Post(user2, group2);

            Session.UserId = user1;


            var elem  = cachier.GetLater <Element>(_singleElement.Key);
            var elem2 = cachier.GetLater <Element>(_dependentElement.Key);

            Assert.IsNotNull(elem.Value);
            Assert.IsNotNull(elem2.Value);
            Assert.AreEqual(1, ModelSecurityProvider.TimesWasUsed);//серия должна взяться один раз
            //после этого должы браться результаты серии закэшированные результаты
            ModelSecurityProvider.TimesWasUsed = 0;
            cachier.Post(_singleElement.Key, _singleElement);
            cachier.Post(_dependentElement.Key, _dependentElement);
            Assert.AreEqual(0, ModelSecurityProvider.TimesWasUsed);

            Session.UserId = user2;
            elem           = cachier.GetLater <Element>(_singleElement.Key);
            elem2          = cachier.GetLater <Element>(_dependentElement.Key);

            Assert.IsNotNull(elem.Value);
            Assert.IsNotNull(elem2.Value);
            Assert.AreEqual(1, ModelSecurityProvider.TimesWasUsed);//серия должна взяться один раз
            //после этого должы браться результаты серии закэшированные результаты
            ModelSecurityProvider.TimesWasUsed = 0;
            MockHelper.AwaitException <SecurityException>(() => cachier.Post(_singleElement.Key, _singleElement));
            MockHelper.AwaitException <SecurityException>(() => cachier.Post(_dependentElement.Key, _dependentElement));

            Assert.AreEqual(0, ModelSecurityProvider.TimesWasUsed);
        }
예제 #27
0
        public void BasicSecurity()
        {
            var cachier = GetCachier();

            var modelReader   = Guid.NewGuid();
            var modelWriter   = Guid.NewGuid();
            var elementReader = Guid.NewGuid();
            var elementWriter = Guid.NewGuid();

            var elemPermissions = new SecurityPermissions
            {
                AllowedForRead  = new[] { elementReader },
                AllowedForWrite = new[] { elementWriter }
            };

            var modelPermissions = new SecurityPermissions
            {
                AllowedForRead  = new[] { modelReader },
                AllowedForWrite = new[] { modelWriter }
            };

            cachier.Post(_singleModel.Key, modelPermissions);
            cachier.Post(_dependentModel.Key, modelPermissions);
            cachier.Post(_singleElement.Key, elemPermissions);
            cachier.Post(_dependentElement.Key, elemPermissions);

            var user1 = Guid.NewGuid();
            var user2 = Guid.NewGuid();

            var group1 = new SecurityGroup {
                Groups = new[] { modelReader, elementReader, elementWriter }
            };

            var group2 = new SecurityGroup {
                Groups = new[] { modelReader, elementReader, modelWriter }
            };

            cachier.Post(user1, group1);
            cachier.Post(user2, group2);

            Session.UserId = user1;
            var elem = cachier.Get <Element>(_singleElement.Key);

            Assert.IsNotNull(elem);
            var model = cachier.Get <Model>(_singleModel.Key);

            Assert.IsNotNull(model);
            ModelSecurityProvider.TimesWasUsed = 0;//после этого должы браться закэшированные результаты
            try
            {
                cachier.Post(_singleModel.Key, _singleModel);
                Assert.Fail();
            }
            catch (SecurityException)
            {
            }

            cachier.Post(_singleElement.Key, _singleElement);
            Assert.AreEqual(0, ModelSecurityProvider.TimesWasUsed);

            Session.UserId = user2;
            elem           = cachier.Get <Element>(_singleElement.Key);
            Assert.IsNotNull(elem);
            model = cachier.Get <Model>(_singleModel.Key);
            Assert.IsNotNull(model);
            Assert.AreEqual(2, ModelSecurityProvider.TimesWasUsed); //поскольку берем в другом контексте безопасности, кэшироваться еще ничего было не должно
            ModelSecurityProvider.TimesWasUsed = 0;                 //после этого снова должны браться закэшированные результаты
            try
            {
                cachier.Post(_singleElement.Key, _singleElement);
                Assert.Fail();
            }
            catch (SecurityException)
            {
            }
            cachier.Post(_singleModel.Key, _singleModel);
            Assert.AreEqual(0, ModelSecurityProvider.TimesWasUsed);
        }