예제 #1
0
        public void Sign_Validations()
        {
            var signer = UrlSigner.FromBlobSigner(new FakeBlobSigner());

            // Bucket names cannot be null or contain uppercase letters (among other rules).
            // Make sure we verify the presence and format of the bucket name in all overloads.
            Assert.Throws <ArgumentNullException>(() => signer.Sign(null, "objectName", TimeSpan.FromDays(1), new HttpRequestMessage()));
            Assert.Throws <ArgumentException>(() => signer.Sign("BUCKETNAME", "objectName", TimeSpan.FromDays(1), new HttpRequestMessage()));

            Assert.Throws <ArgumentNullException>(() => signer.Sign(null, "objectName", DateTimeOffset.UtcNow, new HttpRequestMessage()));
            Assert.Throws <ArgumentException>(() => signer.Sign("BUCKETNAME", "objectName", DateTimeOffset.UtcNow, new HttpRequestMessage()));

            var emptyHeaders = new Dictionary <string, IEnumerable <string> >();

            Assert.Throws <ArgumentNullException>(() => signer.Sign(null, "objectName", TimeSpan.FromDays(1), HttpMethod.Get, emptyHeaders, emptyHeaders));
            Assert.Throws <ArgumentException>(() => signer.Sign("BUCKETNAME", "objectName", TimeSpan.FromDays(1), HttpMethod.Get, emptyHeaders, emptyHeaders));

            Assert.Throws <ArgumentNullException>(() => signer.Sign(null, "objectName", DateTimeOffset.UtcNow, HttpMethod.Get, emptyHeaders, emptyHeaders));
            Assert.Throws <ArgumentException>(() => signer.Sign("BUCKETNAME", "objectName", DateTimeOffset.UtcNow, HttpMethod.Get, emptyHeaders, emptyHeaders));

#pragma warning disable CS0618 // Type or member is obsolete
            // Make sure exceptions are not thrown for things which may be null or uppercase.
            signer.Sign("bucketname", null, TimeSpan.FromDays(1), null);
            signer.Sign("bucketname", null, null, null, null, null);
            signer.Sign("bucketname", "OBJECTNAME", null, null, null, null);
            // Our UrlSigner is entirely synchronous - it's fine to just wait
            signer.SignAsync("bucketname", null, TimeSpan.FromDays(1), request: null).Wait();
            signer.SignAsync("bucketname", null, null, null, null, null).Wait();
            signer.SignAsync("bucketname", "OBJECTNAME", null, null, null, null).Wait();
#pragma warning restore CS0618 // Type or member is obsolete
        }
예제 #2
0
        public ExternalProviderGoogle(GXService providerService)
        {
            GoogleCredential credentials;

            using (Stream stream = KeyStream(CryptoImpl.Decrypt(providerService.Properties.Get(KEY))))
            {
                credentials = GoogleCredential.FromStream(stream).CreateScoped(StorageService.Scope.CloudPlatform);
            }

            using (Stream stream = KeyStream(CryptoImpl.Decrypt(providerService.Properties.Get(KEY))))
            {
                Signer = UrlSigner.FromServiceAccountData(stream);
            }

            Client = StorageClient.Create(credentials);

            Service = new StorageService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentials,
                ApplicationName       = providerService.Properties.Get(APPLICATION_NAME)
            });

            Project = providerService.Properties.Get(PROJECT_ID);
            Bucket  = CryptoImpl.Decrypt(providerService.Properties.Get(BUCKET));
            Folder  = providerService.Properties.Get(FOLDER);

            CreateBucket();
            CreateFolder(Folder);
        }
        private static void HeadTest_Common(StorageFixture fixture, UrlSigner signer, [CallerMemberName] string caller = null)
        {
            Func <HttpRequestMessage> createRequest = null;
            string url = null;

            fixture.RegisterDelayTest(
                s_duration,
                beforeDelay: async duration =>
            {
                url = signer.Sign(
                    fixture.ReadBucket,
                    fixture.SmallObject,
                    duration,
                    HttpMethod.Head);
                createRequest = () => new HttpRequestMessage(HttpMethod.Head, url);

                // Verify that the URL works initially.
                var response = await fixture.HttpClient.SendAsync(createRequest());
                await VerifyResponseAsync(response);
            },
                afterDelay: async() =>
            {
                // Verify that the URL no longer works.
                var response = await fixture.HttpClient.SendAsync(createRequest());
                Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            },
                caller);
        }
예제 #4
0
        /// <summary>
        ///
        /// <para>CreateSignedURLForUpload:</para>
        ///
        /// <para>Creates signed url for uploading a file</para>
        ///
        /// <para>Check <seealso cref="IBFileServiceInterface.CreateSignedURLForUpload"/> for detailed documentation</para>
        ///
        /// </summary>
        public bool CreateSignedURLForUpload(
            out string _SignedUrl,
            string _BucketName,
            string _KeyInBucket,
            string _ContentType,
            int _URLValidForMinutes             = 60,
            Action <string> _ErrorMessageAction = null)
        {
            var ContentHeaders = new Dictionary <string, IEnumerable <string> >
            {
                { "Content-Type", new string[] { _ContentType } }
            };

            try
            {
                UrlSigner Signer = UrlSigner.FromServiceAccountCredential(CredentialScoped);
                _SignedUrl = Signer.Sign(_BucketName, _KeyInBucket, TimeSpan.FromMinutes(_URLValidForMinutes), HttpMethod.Put, null, ContentHeaders);
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke("BFileServiceGC->CreateSignedURLForUpload: " + e.Message + ", Trace: " + e.StackTrace);
                _SignedUrl = null;
                return(false);
            }
            return(true);
        }
        public async Task <string> GetDownloadUrl(string path, TimeSpan?expiry = null, string contentType = null, string fileName = null, CancellationToken cancellationToken = default)
        {
            path = normalizePath(path);

            cancellationToken.ThrowIfCancellationRequested();

            var urlSigner = UrlSigner.FromServiceAccountCredential(_saCredential);

            cancellationToken.ThrowIfCancellationRequested();

            expiry ??= TimeSpan.MaxValue;

            var signedUrl = await urlSigner.SignAsync(_configuration.Bucket, path, expiry.Value, HttpMethod.Get, cancellationToken : cancellationToken);

            if (contentType is string contentTypeValue)
            {
                signedUrl += "&response-content-type=" + HttpUtility.UrlEncode(contentTypeValue);
            }

            if (fileName is string fileNameValue)
            {
                signedUrl += "&response-content-disposition=" + HttpUtility.UrlEncode(string.Format("attachment; filename=\"{0}\"", fileNameValue));
            }

            cancellationToken.ThrowIfCancellationRequested();

            return(signedUrl);
        }
예제 #6
0
            public void JsonSourceTest(JsonTest test)
            {
                var timestamp = DateTime.ParseExact(
                    test.Timestamp,
                    "yyyyMMdd'T'HHmmss'Z'",
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
                var clock  = new FakeClock(timestamp);
                var signer = UrlSigner
                             .FromServiceAccountCredential(s_testCredential)
                             .WithSigningVersion(SigningVersion.V4)
                             .WithClock(clock);

                var actualUrl = signer.Sign(test.Bucket, test.Object,
                                            duration: TimeSpan.FromSeconds(test.Expiration),
                                            requestMethod: s_methods[test.Method],
                                            requestHeaders: test.Headers?.ToDictionary(kvp => kvp.Key, kvp => Enumerable.Repeat(kvp.Value, 1)),
                                            contentHeaders: null);

                // We almost always want the complete URL afterwards, which xUnit doesn't give us.
                if (test.ExpectedUrl != actualUrl)
                {
                    FileLogger.Log($"{test.Description} failure");
                    FileLogger.Log($"Expected: {test.ExpectedUrl}");
                    FileLogger.Log($"Actual: {actualUrl}");
                }
                Assert.Equal(test.ExpectedUrl, actualUrl);
            }
    public string GenerateV4UploadSignedUrl(
        string bucketName         = "your-unique-bucket-name",
        string objectName         = "your-object-name",
        string credentialFilePath = "my-local-path/my-credential-file-name")
    {
        UrlSigner urlSigner = UrlSigner.FromServiceAccountPath(credentialFilePath);

        var contentHeaders = new Dictionary <string, IEnumerable <string> >
        {
            { "Content-Type", new[] { "text/plain" } }
        };

        // V4 is the default signing version.
        UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1));

        UrlSigner.RequestTemplate template = UrlSigner.RequestTemplate
                                             .FromBucket(bucketName)
                                             .WithObjectName(objectName)
                                             .WithHttpMethod(HttpMethod.Put)
                                             .WithContentHeaders(contentHeaders);

        string url = urlSigner.Sign(template, options);

        Console.WriteLine("Generated PUT signed URL:");
        Console.WriteLine(url);
        Console.WriteLine("You can use this URL with any user agent, for example:");
        Console.WriteLine($"curl -X PUT -H 'Content-Type: text/plain' --upload-file my-file '{url}'");
        return(url);
    }
예제 #8
0
        public async void SignedURLGet()
        {
            var bucketName          = _fixture.BucketName;
            var objectName          = _fixture.HelloStorageObjectName;
            var credentialsFilePath = GetCredentialsFilePath();
            var httpClient          = new HttpClient();

            // Sample: SignedURLGet
            // Create a signed URL which can be used to get a specific object for one hour.
            UrlSigner urlSigner = UrlSigner.FromServiceAccountPath(credentialsFilePath);
            string    url       = urlSigner.Sign(
                bucketName,
                objectName,
                TimeSpan.FromHours(1),
                HttpMethod.Get);

            // Get the content at the created URL.
            HttpResponseMessage response = await httpClient.GetAsync(url);

            string content = await response.Content.ReadAsStringAsync();

            // End sample

            Assert.Equal(_fixture.HelloWorldContent, content);
        }
예제 #9
0
        public void CommonSetUp()
        {
            var privateKey = Encoding.UTF8.GetString(Convert.FromBase64String("LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlDWEFJQkFBS0JnUUNxR0t1a08xRGU3emhaajYrSDBxdGpUa1Z4d1RDcHZLZTRlQ1owRlBxcmkwY2IySlpmWEovRGdZU0Y2dlVwCndtSkc4d1ZRWktqZUdjakRPTDVVbHN1dXNGbmNDeldCUTdSS05VU2VzbVFSTVNHa1ZiMS8zaitza1o2VXRXKzV1MDlsSE5zajZ0UTUKMXMxU1ByQ0JrZWRiTmYwVHAwR2JNSkR5UjRlOVQwNFpad0lEQVFBQkFvR0FGaWprbzU2K3FHeU44TTBSVnlhUkFYeisreFRxSEJMaAozdHg0VmdNdHJRK1dFZ0NqaG9Ud28yM0tNQkF1SkdTWW5SbW9CWk0zbE1mVEtldklrQWlkUEV4dllDZG01ZFlxM1hUb0xra0x2NUwyCnBJSVZPRk1ERytLRVNuQUZWN2wyYytjbnpSTVcwK2I2ZjhtUjFDSnpadXhWTEw2UTAyZnZMaTU1L21iU1l4RUNRUURlQXc2ZmlJUVgKR3VrQkk0ZU1aWnQ0bnNjeTJvMTJLeVluZXIzVnBvZUUrTnAycStaM3B2QU1kL2FOelEvVzlXYUkrTlJmY3hVSnJtZlB3SUdtNjNpbApBa0VBeENMNUhRYjJiUXI0QnlvcmNNV20vaEVQMk1aelJPVjczeUY0MWhQc1JDOW02NktyaGVPOUhQVEp1bzMvOXM1cCtzcUd4T2xGCkwwTkR0NFNrb3NqZ0d3SkFGa2x5UjF1Wi93UEpqajYxMWNkQmN6dGxQZHFveHNzUUduaDg1QnpDai91M1dxQnBFMnZqdnl5dnlJNWsKWDZ6azdTMGxqS3R0MmpueTIrMDBWc0JlclFKQkFKR0MxTWc1T3lkbzVOd0Q2QmlST3JQeEdvMmJwVGJ1L2ZoclQ4ZWJIa1R6MmVwbApVOVZRUVNRelkxb1pNVlg4aTFtNVdVVExQejJ5TEpJQlFWZFhxaE1DUUJHb2l1U29TamFmVWhWN2kxY0VHcGI4OGg1TkJZWnpXWEdaCjM3c0o1UXNXK3NKeW9OZGUzeEg4dmRYaHpVN2VUODJENlgvc2N3OVJaeisvNnJDSjRwMD0KLS0tLS1FTkQgUlNBIFBSSVZBVEUgS0VZLS0tLS0="));
            var cf         = new AmazonCloudFrontClient(RegionEndpoint.EUNorth1);

            _urlSigner = new UrlSigner(cf, privateKey, "ABCD3FGH1JKLM");
        }
예제 #10
0
파일: Program.cs 프로젝트: manoj14-ML/MyPOC
        private static void GenerateSignedUrl(string bucketName, string objectName)
        {
            UrlSigner urlSigner = UrlSigner.FromServiceAccountPath(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"));
            string    url       = urlSigner.Sign(bucketName, objectName, TimeSpan.FromHours(1), null);

            Console.WriteLine(url);
        }
            public void EncryptionKeyAndHashAreIgnored()
            {
                var signer = UrlSigner.FromServiceAccountCredential(CreateFakeServiceAccountCredential());
                var baseRequestTemplate = RequestTemplate.FromBucket("bucket-name").WithObjectName("object-name");
                var options             = Options
                                          .FromExpiration(DateTimeOffset.UtcNow + TimeSpan.FromDays(1))
                                          .WithSigningVersion(SigningVersion.V2);

                var algorithmTemplate = baseRequestTemplate.WithRequestHeaders(
                    new Dictionary <string, IEnumerable <string> >
                {
                    { EncryptionKey.AlgorithmHeader, new [] { EncryptionKey.AlgorithmValue } }
                });

                var keyAndHashTemplate = baseRequestTemplate.WithRequestHeaders(
                    new Dictionary <string, IEnumerable <string> >
                {
                    { EncryptionKey.AlgorithmHeader, new [] { EncryptionKey.AlgorithmValue } },
                    { EncryptionKey.KeyHeader, new [] { "abc" } },
                    { EncryptionKey.KeyHashHeader, new [] { "def" } }
                });

                var url1 = signer.Sign(algorithmTemplate, options);
                var url2 = signer.Sign(keyAndHashTemplate, options);

                Assert.Equal(url1, url2);

                // However, make sure the encryption algorithm is not ignored.
                var url3 = signer.Sign(baseRequestTemplate, options);

                Assert.NotEqual(url1, url3);
            }
        public async Task SignedURLGet()
        {
            var bucketName = _fixture.BucketName;
            var objectName = _fixture.HelloStorageObjectName;
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;
            var httpClient = new HttpClient();

            // Sample: SignedURLGet
            // Additional: Sign(string,string,TimeSpan,*,*,*)
            // Create a signed URL which can be used to get a specific object for one hour.
            UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(credential);
            string    url       = urlSigner.Sign(
                bucketName,
                objectName,
                TimeSpan.FromHours(1),
                HttpMethod.Get);

            // Get the content at the created URL.
            HttpResponseMessage response = await httpClient.GetAsync(url);

            string content = await response.Content.ReadAsStringAsync();

            // End sample

            Assert.Equal(_fixture.HelloWorldContent, content);
        }
        private static void GetBucketTest_Common(StorageFixture fixture, UrlSigner signer, [CallerMemberName] string caller = null)
        {
            var    bucket = fixture.ReadBucket;
            string url    = null;

            fixture.RegisterDelayTest(
                s_duration,
                beforeDelay: async duration =>
            {
                url = signer.Sign(bucket, null, duration);

                // Verify that the URL works initially.
                var response    = await fixture.HttpClient.GetAsync(url);
                var result      = await response.Content.ReadAsStringAsync();
                var document    = XDocument.Parse(result);
                var ns          = document.Root.GetDefaultNamespace();
                var keys        = document.Root.Elements(ns + "Contents").Select(contents => contents.Element(ns + "Key").Value).ToList();
                var objectNames = await fixture.Client.ListObjectsAsync(bucket, null).Select(o => o.Name).ToList();
                Assert.Equal(objectNames, keys);
            },
                afterDelay: async() =>
            {
                // Verify that the URL no longer works.
                var response = await fixture.HttpClient.GetAsync(url);
                Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            },
                caller);
        }
예제 #14
0
        /// <summary>
        /// DOWNlOAD BUCKET OBJECT BY USING SIGNED URL CREDENTIALS OF ServiceAccountCredential 28/03/2019
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="objectName"></param>
        /// <returns></returns>
        public async static Task <string> GetSignedURL(string bucketName, string objectName)
        {
            try
            {
                var scopes = new string[] { "https://www.googleapis.com/auth/devstorage.read_write" };

                //string cred= Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");

                ServiceAccountCredential cred;

                using (var stream = new FileStream(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"), FileMode.Open, FileAccess.Read))
                {
                    cred = GoogleCredential.FromStream(stream)
                           .CreateScoped(scopes)
                           .UnderlyingCredential as ServiceAccountCredential;
                }

                var urlSigner = UrlSigner.FromServiceAccountCredential(cred);

                return(await urlSigner.SignAsync(bucketName, objectName, TimeSpan.FromMinutes(10), HttpMethod.Get));
            }
            catch (Exception)
            {
                throw new Exception(StaticResource.UnableToGenerateSignedUrl);
            }
        }
        private static void GetObjectWithSpacesTest_Common(StorageFixture fixture, UrlSigner signer, [CallerMemberName] string caller = null)
        {
            var    bucket  = fixture.SingleVersionBucket;
            var    name    = IdGenerator.FromGuid() + " with spaces";
            var    content = fixture.SmallContent;
            string url     = null;

            fixture.RegisterDelayTest(
                s_duration,
                beforeDelay: async duration =>
            {
                fixture.Client.UploadObject(bucket, name, null, new MemoryStream(content));
                url = signer.Sign(bucket, name, duration);

                // Verify that the URL works initially.
                var response = await fixture.HttpClient.GetAsync(url);
                await VerifyResponseAsync(response);
                var result = await response.Content.ReadAsByteArrayAsync();
                AssertContentEqual(content, result);
            },
                afterDelay: async() =>
            {
                // Verify that the URL no longer works.
                var response = await fixture.HttpClient.GetAsync(url);
                Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            },
                caller);
        }
예제 #16
0
        public async Task Sign_Validations()
        {
            var signer = UrlSigner.FromBlobSigner(new FakeBlobSigner());

            Assert.Throws <ArgumentNullException>(() => signer.Sign(null, null));
            await Assert.ThrowsAsync <ArgumentNullException>(() => signer.SignAsync(null, null));

            Assert.Throws <ArgumentNullException>(() => signer.Sign(null, Options.FromDuration(TimeSpan.Zero)));
            await Assert.ThrowsAsync <ArgumentNullException>(() => signer.SignAsync(null, Options.FromDuration(TimeSpan.Zero)));

            Assert.Throws <ArgumentNullException>(() => signer.Sign(RequestTemplate.FromBucket("bucket"), null));
            await Assert.ThrowsAsync <ArgumentNullException>(() => signer.SignAsync(RequestTemplate.FromBucket("bucket"), null));

            // Bucket names cannot be null or contain uppercase letters (among other rules).
            // Make sure we verify the presence and format of the bucket name in all overloads.
            Assert.Throws <ArgumentNullException>(() => signer.Sign(null, "objectName", TimeSpan.FromDays(1)));
            await Assert.ThrowsAsync <ArgumentNullException>(() => signer.SignAsync(null, "objectName", TimeSpan.FromDays(1)));

            Assert.Throws <ArgumentException>(() => signer.Sign("BUCKETNAME", "objectName", TimeSpan.FromDays(1)));
            await Assert.ThrowsAsync <ArgumentException>(() => signer.SignAsync("BUCKETNAME", "objectName", TimeSpan.FromDays(1)));

            // Make sure exceptions are not thrown for things which may be null or uppercase.
            signer.Sign("bucketname", null, TimeSpan.FromDays(1), null, null);
            await signer.SignAsync("bucketname", null, TimeSpan.FromDays(1), null, null);
        }
예제 #17
0
        public override string SavePrivate(string domain, string path, System.IO.Stream stream, DateTime expires)
        {
            var storage = GetStorage();

            var objectKey = MakePath(domain, path);
            var buffered  = stream.GetBuffered();

            UploadObjectOptions uploadObjectOptions = new UploadObjectOptions
            {
                PredefinedAcl = PredefinedObjectAcl.BucketOwnerFullControl
            };

            buffered.Position = 0;

            var uploaded = storage.UploadObject(_bucket, MakePath(domain, path), "application/octet-stream", buffered, uploadObjectOptions, null);

            uploaded.CacheControl       = String.Format("public, maxage={0}", (int)TimeSpan.FromDays(5).TotalSeconds);
            uploaded.ContentDisposition = "attachment";

            if (uploaded.Metadata == null)
            {
                uploaded.Metadata = new Dictionary <String, String>();
            }

            uploaded.Metadata["Expires"] = DateTime.UtcNow.Add(TimeSpan.FromDays(5)).ToString("R");
            uploaded.Metadata.Add("private-expire", expires.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture));

            storage.UpdateObject(uploaded);

            var preSignedURL = UrlSigner.FromServiceAccountPath(_jsonPath)
                               .Sign(_bucket, MakePath(domain, path), expires, null);

            //TODO: CNAME!
            return(preSignedURL);
        }
예제 #18
0
        public void SignUrl_adds_oauth_signature()
        {
            var url = "http://www.example.com?parameter=hello&again=there";

            var signedUrl = new UrlSigner().SignUrl(url, null, null, GetOAuthCredentials());

            Assert.That(signedUrl.Query.Contains("oauth_signature"));
        }
예제 #19
0
        public async Task SignedURLPut()
        {
            var bucketName = _fixture.BucketName;
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;
            var httpClient = new HttpClient();

            // Sample: SignedURLPut
            // Create a request template that will be used to create the signed URL.
            var destination = "places/world.txt";

            UrlSigner.RequestTemplate requestTemplate = UrlSigner.RequestTemplate
                                                        .FromBucket(bucketName)
                                                        .WithObjectName(destination)
                                                        .WithHttpMethod(HttpMethod.Put)
                                                        .WithContentHeaders(new Dictionary <string, IEnumerable <string> >
            {
                { "Content-Type", new[] { "text/plain" } }
            });
            // Create options specifying for how long the signer URL will be valid.
            UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1));
            // Create a signed URL which allows the requester to PUT data with the text/plain content-type.
            UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(credential);
            string    url       = urlSigner.Sign(requestTemplate, options);

            // Upload the content into the bucket using the signed URL.
            string source = "world.txt";

            ByteArrayContent content;

            using (FileStream stream = File.OpenRead(source))
            {
                byte[] data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);
                content = new ByteArrayContent(data)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue("text/plain") }
                };
            }

            HttpResponseMessage response = await httpClient.PutAsync(url, content);

            // End sample

            Assert.True(response.IsSuccessStatusCode);

            var client = StorageClient.Create();
            var result = new MemoryStream();
            await client.DownloadObjectAsync(bucketName, destination, result);

            using (var stream = File.OpenRead(source))
            {
                var data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);
                Assert.Equal(result.ToArray(), data);
            }

            await client.DeleteObjectAsync(bucketName, destination);
        }
예제 #20
0
        public async Task SignedUrlWithIamServiceBlobSigner()
        {
            _fixture.SkipIf(Platform.Instance().Type == PlatformType.Unknown);

            var bucketName = _fixture.BucketName;
            var objectName = _fixture.HelloStorageObjectName;
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;
            var httpClient = new HttpClient();

            // Sample: IamServiceBlobSignerUsage
            // First obtain the email address of the default service account for this instance from the metadata server.
            HttpRequestMessage serviceAccountRequest = new HttpRequestMessage
            {
                // Note: you could use 169.254.169.254 as the address to avoid a DNS lookup.
                RequestUri = new Uri("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email"),
                Headers    = { { "Metadata-Flavor", "Google" } }
            };
            HttpResponseMessage serviceAccountResponse = await httpClient.SendAsync(serviceAccountRequest).ConfigureAwait(false);

            serviceAccountResponse.EnsureSuccessStatusCode();
            string serviceAccountId = await serviceAccountResponse.Content.ReadAsStringAsync();

            // Create an IAM service client object using the default application credentials.
            GoogleCredential iamCredential = await GoogleCredential.GetApplicationDefaultAsync();

            iamCredential = iamCredential.CreateScoped(IamService.Scope.CloudPlatform);
            IamService iamService = new IamService(new BaseClientService.Initializer
            {
                HttpClientInitializer = iamCredential
            });

            // Create a request template that will be used to create the signed URL.
            UrlSigner.RequestTemplate requestTemplate = UrlSigner.RequestTemplate
                                                        .FromBucket(bucketName)
                                                        .WithObjectName(objectName)
                                                        .WithHttpMethod(HttpMethod.Get);
            // Create options specifying for how long the signer URL will be valid.
            UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1));

            // Create a URL signer that will use the IAM service for signing. This signer is thread-safe,
            // and would typically occur as a dependency, e.g. in an ASP.NET Core controller, where the
            // same instance can be reused for each request.
            IamServiceBlobSigner blobSigner = new IamServiceBlobSigner(iamService, serviceAccountId);
            UrlSigner            urlSigner  = UrlSigner.FromBlobSigner(blobSigner);

            // Use the URL signer to sign a request for the test object for the next hour.
            string url = await urlSigner.SignAsync(requestTemplate, options);

            // Prove we can fetch the content of the test object with a simple unauthenticated GET request.
            HttpResponseMessage response = await httpClient.GetAsync(url);

            string content = await response.Content.ReadAsStringAsync();

            // End sample

            Assert.Equal(_fixture.HelloWorldContent, content);
        }
예제 #21
0
            public void ExpiryValidation_Invalid(int seconds)
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(s_testCredential)
                             .WithSigningVersion(SigningVersion.V4)
                             .WithClock(new FakeClock());

                Assert.Throws <ArgumentOutOfRangeException>(() => signer.Sign("bucket", "object", TimeSpan.FromSeconds(seconds), HttpMethod.Get));
            }
        public GCPStorageStrategyProvider(IOptions <Options> optionsAccessor)
        {
            options = optionsAccessor.Value;

            options.Validate();

            urlDuration = (options.UrlDuration ?? defaultUrlDuration);
            urlSigner   = CreateUrlSigner(options);
        }
예제 #23
0
        public string GetCoverUrl(string userId, int bookId, string coverName)
        {
            var       coverPath   = $"{_baseBookPath}{userId}/{bookId}/{coverName}";
            var       initializer = new ServiceAccountCredential.Initializer(_googleCloudStorageSettings.Id);
            UrlSigner urlSgSigner = UrlSigner.FromServiceAccountCredential(
                new ServiceAccountCredential(initializer.FromPrivateKey(_googleCloudStorageSettings.PrivateKey)));
            string url = urlSgSigner.Sign(_googleCloudStorageSettings.BucketName, coverPath, TimeSpan.FromDays(5));

            return(url);
        }
예제 #24
0
            public void ExpiryValidation_Exactly1Week()
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(s_testCredential)
                             .WithSigningVersion(SigningVersion.V4)
                             .WithClock(new FakeClock());

                // Just testing that no exception is thrown.
                signer.Sign("bucket", "object", TimeSpan.FromDays(7), HttpMethod.Get);
            }
예제 #25
0
        public async Task BlobSignerAsync()
        {
            var signer     = UrlSigner.FromBlobSigner(new FakeBlobSigner());
            var bucketName = "bucket-name";
            var objectName = "object-name";
            var expiration = new DateTime(1970, 1, 1, 0, 0, 30, DateTimeKind.Utc);
            var url        = await signer.SignAsync(bucketName, objectName, expiration);

            Assert.Equal("https://storage.googleapis.com/bucket-name/object-name?GoogleAccessId=FakeId&Expires=30&Signature=BBB%3D", url);
        }
예제 #26
0
 public CmafProxyController(StreamingTokenHelper streamingTokenHelper,
                            CmafProxyService proxyService,
                            IOptions <LivestreamOptions> options,
                            UrlSigner urlSigner)
 {
     _streamingTokenHelper = streamingTokenHelper;
     _proxyService         = proxyService;
     _urlSigner            = urlSigner;
     _liveOptions          = options.Value;
 }
            public void BlobSignerSync()
            {
                var signer     = UrlSigner.FromBlobSigner(new FakeBlobSigner()).WithSigningVersion(SigningVersion.V2);
                var bucketName = "bucket-name";
                var objectName = "object-name";
                var expiration = new DateTime(1970, 1, 1, 0, 0, 30, DateTimeKind.Utc);
                var url        = signer.Sign(bucketName, objectName, expiration);

                Assert.Equal("https://storage.googleapis.com/bucket-name/object-name?GoogleAccessId=FakeId&Expires=30&Signature=AAA%3D", url);
            }
예제 #28
0
            public void ExpiryValidation_Invalid(int seconds)
            {
                var signer = UrlSigner
                             .FromServiceAccountCredential(StorageConformanceTestData.TestCredential)
                             .WithClock(new FakeClock());
                var requestTemplate = RequestTemplate.FromBucket("bucket").WithObjectName("object");
                var options         = Options.FromDuration(TimeSpan.FromSeconds(seconds)).WithSigningVersion(SigningVersion.V4);

                Assert.Throws <ArgumentOutOfRangeException>(() => signer.Sign(requestTemplate, options));
            }
예제 #29
0
파일: Client.cs 프로젝트: samirhasanov/ruya
        // ReSharper disable once SuggestBaseTypeForParameter
        public Client(ILogger <Client> logger, IOptions <Setting> options)
        {
            _logger  = logger;
            _options = options.Value;

            GoogleCredential credentials = GetGoogleCredentials();
            var serviceAccountCredential = credentials.UnderlyingCredential as ServiceAccountCredential;

            _urlSigner     = UrlSigner.FromServiceAccountCredential(serviceAccountCredential);
            _storageClient = StorageClient.Create(credentials);
        }
            public async void Unsupported_SignPostPolicy()
            {
                var signer  = UrlSigner.FromServiceAccountCredential(CreateFakeServiceAccountCredential());
                var options = Options
                              .FromExpiration(DateTimeOffset.UtcNow + TimeSpan.FromDays(1))
                              .WithSigningVersion(SigningVersion.V2);
                var postPolicy = PostPolicy.ForBucketAndKey("my-bucket", "my-test-object");

                Assert.Throws <NotSupportedException>(() => signer.Sign(postPolicy, options));
                await Assert.ThrowsAsync <NotSupportedException>(() => signer.SignAsync(postPolicy, options));
            }