async Task <bool> ExistsDatabase()
        {
            string baseUri = $"{_EndpointUrl}dbs/{_DatabaseId}";

            using (var _httpClient = new HttpClient())
            {
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                _httpClient.DefaultRequestHeaders.Add("x-ms-date", utc_date);
                _httpClient.DefaultRequestHeaders.Add("x-ms-version", "2015-08-06");

                string verb         = "GET";
                string resourceType = "dbs";
                string resourceLink = "dbs/" + _DatabaseId;

                string authHeader = DocumentAuthorization.GenerateMasterKeyAuthorizationSignature(verb, resourceLink, resourceType, _Key, "master", "1.0", utc_date);
                _httpClient.DefaultRequestHeaders.Remove("authorization");
                _httpClient.DefaultRequestHeaders.Add("authorization", authHeader);

                var response = await _httpClient.GetAsync(new Uri(baseUri));

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return(true);
                }
            }

            return(false);
        }
        async Task CreateDocument(string collectionName, string content)
        {
            Thread.Sleep(500); // Try to avoid error 429 (Too Many Requests) without increasing the pricing tier. Don´t do this in a real app.

            string uri = $"{_EndpointUrl}dbs/{_DatabaseId}/colls/{collectionName}/docs";

            using (var _httpClient = new HttpClient())
            {
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                _httpClient.DefaultRequestHeaders.Add("x-ms-date", utc_date);
                _httpClient.DefaultRequestHeaders.Add("x-ms-version", "2015-08-06");

                string verb         = "POST";
                string resourceType = "docs";
                string resourceLink = $"dbs/{_DatabaseId}/colls/{collectionName}";

                string authHeader = DocumentAuthorization.GenerateMasterKeyAuthorizationSignature(verb, resourceLink, resourceType, _Key, "master", "1.0", utc_date);
                _httpClient.DefaultRequestHeaders.Remove("authorization");
                _httpClient.DefaultRequestHeaders.Add("authorization", authHeader);

                var response = await _httpClient.PostAsync(new Uri(uri), new StringContent(content, Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();
            }
        }
        async Task CreateCollection(string collectionName)
        {
            string uri = $"{_EndpointUrl}dbs/{_DatabaseId}/colls";

            using (var _httpClient = new HttpClient())
            {
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                _httpClient.DefaultRequestHeaders.Add("x-ms-date", utc_date);
                _httpClient.DefaultRequestHeaders.Add("x-ms-version", "2015-08-06");

                string verb         = "POST";
                string resourceType = "colls";
                string resourceLink = $"dbs/{_DatabaseId}/colls";
                string resourceId   = $"dbs/{_DatabaseId}";

                string authHeader = DocumentAuthorization.GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, _Key, "master", "1.0", utc_date);
                _httpClient.DefaultRequestHeaders.Remove("authorization");
                _httpClient.DefaultRequestHeaders.Add("authorization", authHeader);

                var content  = JsonConvert.SerializeObject(new { id = collectionName });
                var response = await _httpClient.PostAsync(uri, new StringContent(content, Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();
            }
        }
Exemplo n.º 4
0
        public void DocumentWithoutPermissionWillBeFilteredOutSilentlyWithStreaming()
        {
            var rhinosCompany = new Company
            {
                Name = "Hibernating Rhinos"
            };

            var secretCompany = new Company
            {
                Name = "Secret Co."
            };

            var authorizationUser = new AuthorizationUser
            {
                Id   = UserId,
                Name = "Ayende Rahien",
            };

            var operation = "Company/Bid";

            using (var s = store.OpenSession())
            {
                s.Store(authorizationUser);
                s.Store(rhinosCompany);
                s.Store(secretCompany);

                var documentAuthorization = new DocumentAuthorization();
                documentAuthorization.Permissions.Add(new DocumentPermission()
                {
                    Allow     = true,
                    Operation = operation,
                    User      = UserId
                });

                s.SetAuthorizationFor(rhinosCompany, documentAuthorization);       // allow Ayende Rahien
                s.SetAuthorizationFor(secretCompany, new DocumentAuthorization()); // deny everyone

                s.SaveChanges();
            }


            using (var s = store.OpenSession())
            {
                s.SecureFor(UserId, operation);

                var results = 0;

                using (var it = s.Advanced.Stream <Company>("companies/"))
                {
                    while (it.MoveNext())
                    {
                        results++;
                    }
                }

                Assert.Equal(2, results);
            }
        }
Exemplo n.º 5
0
        public void DocumentWithoutPermissionWillBeFilteredOutSilentlyWithQueryStreaming()
        {
            new CompanyIndex().Execute(store);
            var rhinosCompany = new Company
            {
                Name = "Hibernating Rhinos"
            };

            var secretCompany = new Company
            {
                Name = "Secret Co."
            };

            var authorizationUser = new AuthorizationUser
            {
                Id   = UserId,
                Name = "Ayende Rahien",
            };

            var operation = "Company/Bid";

            using (var s = store.OpenSession())
            {
                s.Store(authorizationUser);
                s.Store(rhinosCompany);
                s.Store(secretCompany);

                var documentAuthorization = new DocumentAuthorization();
                documentAuthorization.Permissions.Add(new DocumentPermission()
                {
                    Allow     = true,
                    Operation = operation,
                    User      = UserId
                });

                s.SetAuthorizationFor(rhinosCompany, documentAuthorization);                 // allow Ayende Rahien
                s.SetAuthorizationFor(secretCompany, new DocumentAuthorization());           // deny everyone

                s.SaveChanges();
            }

            WaitForIndexing(store);

            using (var s = store.OpenSession())
            {
                s.SecureFor(UserId, operation);
                var expected = s.Advanced.LuceneQuery <Company, CompanyIndex>().ToList().Count();

                var results = QueryExtensions.StreamAllFrom(s.Advanced.LuceneQuery <Company, CompanyIndex>(), s);

                Assert.Equal(expected, results.Count());
            }
        }
Exemplo n.º 6
0
        public void SecureForCausesHighCpu()
        {
            User user = new User {
                Name = "Mr. Test"
            };
            Content contentWithoutPermission = new Content {
                Title = "Content Without Permission"
            };
            Content contentWithPermission = new Content {
                Title = "Content With Permission"
            };

            using (IDocumentSession session = store.OpenSession())
            {
                session.Store(user);
                session.Store(contentWithoutPermission);
                session.Store(contentWithPermission);

                DocumentAuthorization authorization = session.GetAuthorizationFor(contentWithoutPermission) ??
                                                      new DocumentAuthorization();
                authorization.Permissions.Add(new DocumentPermission {
                    Allow = false, Operation = Operation, User = user.Id
                });
                session.SetAuthorizationFor(contentWithoutPermission, authorization);

                authorization = session.GetAuthorizationFor(contentWithPermission) ?? new DocumentAuthorization();
                authorization.Permissions.Add(new DocumentPermission {
                    Allow = true, Operation = Operation, User = user.Id
                });
                session.SetAuthorizationFor(contentWithPermission, authorization);

                session.SaveChanges();
            }

            while (store.DatabaseCommands.GetStatistics().StaleIndexes.Length > 0)
            {
                Thread.Sleep(10);
            }

            for (int i = 0; i < 5; i++)
            {
                using (IDocumentSession session = store.OpenSession())
                {
                    session.SecureFor(user.Id, Operation);
                    Content contentY = session.Query <Content>().FirstOrDefault();
                    Assert.NotNull(contentY);
                    Assert.Equal(contentWithPermission.Id, contentY.Id);
                }
            }
        }
Exemplo n.º 7
0
        private static void ExplainWhyUserCantAccessTheDocument(Action <string> logger, string documentId, string userId, AuthorizationUser user, DocumentAuthorization documentAuthorization, string operation)
        {
            var sb = new StringBuilder("Could not find any permissions for operation: ")
                     .Append(operation)
                     .Append(" on ")
                     .Append(documentId)
                     .Append(" for user ")
                     .Append(userId)
                     .Append(".");

            if (user.Roles.Count > 0)
            {
                sb.Append(" or the user's roles: [")
                .Append(string.Join(", ", user.Roles))
                .Append("]");
            }
            sb.AppendLine();

            if (documentAuthorization.Permissions.Count(x => x.Operation.Equals(operation, StringComparison.InvariantCultureIgnoreCase)) == 0)
            {
                sb.Append("No one may perform operation ")
                .Append(operation)
                .Append(" on ")
                .Append(documentId);
            }
            else
            {
                sb.Append("Only the following may perform operation ")
                .Append(operation)
                .Append(" on ")
                .Append(documentId)
                .AppendLine(":");

                foreach (var documentPermission in documentAuthorization.Permissions)
                {
                    sb.Append("\t")
                    .Append(documentPermission.Explain)
                    .AppendLine();
                }
            }

            logger(sb.ToString());
        }
Exemplo n.º 8
0
        public static void SetAuthorizationFor(this IDocumentSession session, object entity, DocumentAuthorization documentAuthorization)
        {
            var metadata       = session.Advanced.GetMetadataFor(entity);
            var jsonSerializer = JsonExtensions.CreateDefaultJsonSerializer();

            jsonSerializer.ContractResolver      = session.Advanced.DocumentStore.Conventions.JsonContractResolver;
            metadata[RavenDocumentAuthorization] = RavenJObject.FromObject(documentAuthorization, jsonSerializer);
        }
Exemplo n.º 9
0
        public static void SetAuthorizationFor(this IDocumentSession session, object entity, DocumentAuthorization documentAuthorization)
        {
            var metadata = session.Advanced.GetMetadataFor(entity);

            metadata[RavenDocumentAuthorization] = RavenJObject.FromObject(documentAuthorization, new JsonSerializer
            {
                ContractResolver = session.Advanced.Conventions.JsonContractResolver,
            });
        }