public async void TestAGPL() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg")) { var clock = new RealClock(); var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem()); var licensing = new Licensing(mgr); using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions () { Licensing = licensing, MyOpenSourceProjectUrl = "https://github.com/username/project", EnforcementMethod = EnforceLicenseWith.RedDotWatermark }.MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images"))); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); using var licensedResponse = await client.GetAsync("/fire.jpg?w=1"); licensedResponse.EnsureSuccessStatusCode(); var page = licensing.Result.ProvidePublicLicensesPage(); Assert.Contains("License Validation OFF", page); Assert.Contains("No license keys found.", page); Assert.DoesNotContain("You must purchase a license key or comply with the AGPLv3.", page); Assert.DoesNotContain("To get a license key", page); Assert.Contains("You are using EnforceLicenseWith.RedDotWatermark", page); await host.StopAsync(CancellationToken.None); } }
public async void TestDiskCache() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg") .AddResource("images/logo.png", "TestFiles.imazen_400.png")) { var diskCacheDir = Path.Combine(contentRoot.PhysicalPath, "diskcache"); var hostBuilder = new HostBuilder() .ConfigureServices(services => { services.AddImageflowDiskCache( new DiskCacheOptions(diskCacheDir) { AsyncWrites = false }); }) .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) .SetAllowDiskCaching(true) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images"))); }); }); // Build and start the IHost using var host = await hostBuilder.StartAsync(); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); using var response = await client.GetAsync("/not_there.jpg"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); using var response2 = await client.GetAsync("/fire.jpg?width=1"); response2.EnsureSuccessStatusCode(); var responseBytes = await response2.Content.ReadAsByteArrayAsync(); Assert.True(responseBytes.Length < 1000); using var response3 = await client.GetAsync("/fire.jpg"); response3.EnsureSuccessStatusCode(); responseBytes = await response3.Content.ReadAsByteArrayAsync(); Assert.Equal(contentRoot.GetResourceBytes("TestFiles.fire-umbrella-small.jpg"), responseBytes); await host.StopAsync(CancellationToken.None); var cacheFiles = Directory.GetFiles(diskCacheDir, "*.jpg", SearchOption.AllDirectories); Assert.Single(cacheFiles); } }
public async void TestSiteLicense() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg")) { var clock = new FakeClock("2017-04-25", "2017-04-25"); var set = LicenseStrings.GetSets("SiteWideImageflow").First(); var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem()); MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, set.Remote, null); var url = new RequestUrlProvider(); var licensing = new Licensing(mgr, url.Get); using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions () { Licensing = licensing, MyOpenSourceProjectUrl = null } .SetLicenseKey (EnforceLicenseWith.Http402Error, set.Placeholder) .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images"))); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); mgr.WaitForTasks(); Assert.Empty(mgr.GetIssues()); url.Url = new Uri("https://acme.com"); using var licensedResponse1 = await client.GetAsync("/fire.jpg?w=1"); licensedResponse1.EnsureSuccessStatusCode(); url.Url = new Uri("https://acmestaging.com"); using var licensedResponse2 = await client.GetAsync("/fire.jpg?w=1"); licensedResponse2.EnsureSuccessStatusCode(); url.Url = new Uri("https://subdomain.acme.com"); using var licensedResponse3 = await client.GetAsync("/fire.jpg?w=1"); licensedResponse3.EnsureSuccessStatusCode(); Assert.Empty(mgr.GetIssues()); var page = licensing.Result.ProvidePublicLicensesPage(); Assert.Contains("License Validation ON", page); Assert.Contains("License key valid for all domains.", page); Assert.Contains("No resale of usage. Only for organizations with less than 500 employees.", page); Assert.Contains("You are using EnforceLicenseWith.Http402Error", page); Assert.Contains("Manage your subscription at https://account.imazen.io", page); await host.StopAsync(CancellationToken.None); } }
public async void TestPresets() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg")) { var hostBuilder = new HostBuilder() .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")) .AddPreset(new PresetOptions("tiny", PresetPriority.OverrideQuery) .SetCommand("width", "2") .SetCommand("height", "1")) .AddPreset(new PresetOptions("small", PresetPriority.DefaultValues) .SetCommand("width", "30") .SetCommand("height", "20")) ); }); }); // Build and start the IHost using var host = await hostBuilder.StartAsync(); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); using var presetValidResponse = await client.GetAsync("/fire.jpg?preset=small&height=35&mode=pad"); presetValidResponse.EnsureSuccessStatusCode(); var responseBytes = await presetValidResponse.Content.ReadAsByteArrayAsync(); var imageResults = await ImageJob.GetImageInfo(new BytesSource(responseBytes)); Assert.Equal(30, imageResults.ImageWidth); Assert.Equal(35, imageResults.ImageHeight); using var presetTinyResponse = await client.GetAsync("/fire.jpg?preset=tiny&height=35"); presetTinyResponse.EnsureSuccessStatusCode(); responseBytes = await presetTinyResponse.Content.ReadAsByteArrayAsync(); imageResults = await ImageJob.GetImageInfo(new BytesSource(responseBytes)); Assert.Equal(2, imageResults.ImageWidth); Assert.Equal(1, imageResults.ImageHeight); await host.StopAsync(CancellationToken.None); } }
public async void TestPresetsExclusive() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg")) { var hostBuilder = new HostBuilder() .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")) .SetUsePresetsExclusively(true) .AddPreset(new PresetOptions("small", PresetPriority.OverrideQuery) .SetCommand("maxwidth", "1") .SetCommand("maxheight", "1")) ); }); }); // Build and start the IHost using var host = await hostBuilder.StartAsync(); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); using var notFoundResponse = await client.GetAsync("/not_there.jpg"); Assert.Equal(HttpStatusCode.NotFound, notFoundResponse.StatusCode); using var foundResponse = await client.GetAsync("/fire.jpg"); foundResponse.EnsureSuccessStatusCode(); using var presetValidResponse = await client.GetAsync("/fire.jpg?preset=small"); presetValidResponse.EnsureSuccessStatusCode(); await Assert.ThrowsAsync <InvalidOperationException>(async() => { using var watermarkInvalidResponse = await client.GetAsync("/fire.jpg?preset=not-a-preset"); }); using var nonPresetResponse = await client.GetAsync("/fire.jpg?width=1"); Assert.Equal(HttpStatusCode.Forbidden, nonPresetResponse.StatusCode); await host.StopAsync(CancellationToken.None); } }
public async void TestRequestSigning() { const string key = "test key"; using (var contentRoot = new TempContentRoot() .AddResource("images/fire umbrella.jpg", "TestFiles.fire-umbrella-small.jpg")) { var hostBuilder = new HostBuilder() .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")) .SetRequireRequestSignature(true) .AddRequestSigningKey(key) ); }); }); using var host = await hostBuilder.StartAsync(); using var client = host.GetTestClient(); using var unsignedResponse = await client.GetAsync("/fire umbrella.jpg?width=1"); Assert.Equal(HttpStatusCode.Forbidden, unsignedResponse.StatusCode); var signedUrl = Imazen.Common.Helpers.Signatures.SignRequest("/fire umbrella.jpg?width=1", key); using var signedResponse = await client.GetAsync(signedUrl); signedResponse.EnsureSuccessStatusCode(); var signedEncodedUnmodifiedUrl = Imazen.Common.Helpers.Signatures.SignRequest("/fire%20umbrella.jpg", key); using var signedEncodedUnmodifiedResponse = await client.GetAsync(signedEncodedUnmodifiedUrl); signedEncodedUnmodifiedResponse.EnsureSuccessStatusCode(); var signedEncodedUrl = Imazen.Common.Helpers.Signatures.SignRequest("/fire%20umbrella.jpg?width=1", key); using var signedEncodedResponse = await client.GetAsync(signedEncodedUrl); signedEncodedResponse.EnsureSuccessStatusCode(); var url5 = Imazen.Common.Helpers.Signatures.SignRequest("/fire umbrella.jpg?width=1&ke%20y=val%2fue&another key=another val/ue", key); using var response5 = await client.GetAsync(url5); response5.EnsureSuccessStatusCode(); await host.StopAsync(CancellationToken.None); } }
public async void TestAmazonS3WithCustomClient() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg") .AddResource("images/logo.png", "TestFiles.imazen_400.png")) { var diskCacheDir = Path.Combine(contentRoot.PhysicalPath, "diskcache"); var hostBuilder = new HostBuilder() .ConfigureServices(services => { services.AddSingleton <IAmazonS3>(new AmazonS3Client(new AnonymousAWSCredentials(), RegionEndpoint.USEast1)); services.AddImageflowDiskCache(new DiskCacheOptions(diskCacheDir) { AsyncWrites = false }); services.AddImageflowS3Service( new S3ServiceOptions() .MapPrefix("/ri/", new AmazonS3Client(new AnonymousAWSCredentials(), RegionEndpoint.USEast1), "resizer-images", "", false, false)); }) .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) .SetAllowDiskCaching(true) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images"))); }); }); // Build and start the IHost using var host = await hostBuilder.StartAsync(); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); using var response = await client.GetAsync("/ri/not_there.jpg"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); using var response2 = await client.GetAsync("/ri/imageflow-icon.png?width=1"); response2.EnsureSuccessStatusCode(); await host.StopAsync(CancellationToken.None); var cacheFiles = Directory.GetFiles(diskCacheDir, "*.png", SearchOption.AllDirectories); Assert.Single(cacheFiles); } }
public async void TestNoLicense() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg")) { var clock = new RealClock(); var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem()); var licensing = new Licensing(mgr); using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions () { Licensing = licensing, MyOpenSourceProjectUrl = null, EnforcementMethod = EnforceLicenseWith.Http402Error } .SetDiagnosticsPageAccess (AccessDiagnosticsFrom.None) .SetDiagnosticsPagePassword ("pass") .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images"))); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); using var notLicensedResponse = await client.GetAsync("/fire.jpg?w=1"); Assert.Equal(HttpStatusCode.PaymentRequired, notLicensedResponse.StatusCode); using var licensePageResponse = await client.GetAsync("/imageflow.license"); licensePageResponse.EnsureSuccessStatusCode(); using var notAuthorizedResponse = await client.GetAsync("/imageflow.debug"); Assert.Equal(HttpStatusCode.Unauthorized, notAuthorizedResponse.StatusCode); using var debugPageResponse = await client.GetAsync("/imageflow.debug?password=pass"); debugPageResponse.EnsureSuccessStatusCode(); var page = licensing.Result.ProvidePublicLicensesPage(); Assert.Contains("License Validation ON", page); Assert.Contains("No license keys found.", page); Assert.Contains("You must purchase a license key or comply with the AGPLv3.", page); Assert.Contains("To get a license key, visit", page); Assert.Contains("You are using EnforceLicenseWith.Http402Error", page); await host.StopAsync(CancellationToken.None); } }
public async void TestSqliteCache() { using var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg") .AddResource("images/logo.png", "TestFiles.imazen_400.png"); var hostBuilder = new HostBuilder() .ConfigureServices(services => { services.AddImageflowSqliteCache( new SqliteCacheOptions(":memory:")); }) .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) .SetAllowSqliteCaching(true) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images"))); }); }); // Build and start the IHost using var host = await hostBuilder.StartAsync(); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); for (var i = 0; i < 5; i++) { for (var j = 0; j < 5; j++) { using var response2 = await client.GetAsync($"/fire.jpg?width={i}"); response2.EnsureSuccessStatusCode(); } } await host.StopAsync(CancellationToken.None); }
public async void TestRevocations() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg")) { // set clock to present, and build date to far future var clock = new FakeClock("2017-04-25", "2022-01-01"); foreach (var set in LicenseStrings.GetSets("CancelledImageflow", "SoftRevocationImageflow", "HardRevocationImageflow")) { output.WriteLine($"Testing revocation for {set.Name}"); var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem()); MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, set.Remote, null); var url = new RequestUrlProvider(); var licensing = new Licensing(mgr, url.Get); using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions () { Licensing = licensing, MyOpenSourceProjectUrl = null } .SetLicenseKey (EnforceLicenseWith.Http402Error, set.Placeholder) .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images"))); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); mgr.WaitForTasks(); url.Url = new Uri("https://domain.com"); using var notLicensedResponse = await client.GetAsync("/fire.jpg?w=1"); Assert.Equal(HttpStatusCode.PaymentRequired, notLicensedResponse.StatusCode); url.Url = null; using var notLicensedResponse2 = await client.GetAsync("/fire.jpg?w=1"); Assert.Equal(HttpStatusCode.PaymentRequired, notLicensedResponse2.StatusCode); Assert.NotEmpty(mgr.GetIssues()); var page = licensing.Result.ProvidePublicLicensesPage(); Assert.Contains("License Validation ON", page); Assert.Contains("You are using EnforceLicenseWith.Http402Error", page); Assert.Contains("No valid license keys found.", page); Assert.Contains( "Your license is invalid. Please renew your license via the management portal or purchase a new one at", page); Assert.DoesNotContain("Your license needs to be upgraded.", page); if (set.Name == "CancelledImageflow") { Assert.Contains("Your subscription has lapsed; please renew to continue using product.", page); } if (set.Name == "SoftRevocationImageflow") { Assert.Contains( "This license has been compromised; please contact Vendor Gamma for an updated license", page); } if (set.Name == "HardRevocationImageflow") { Assert.Contains( "Please contact support; the license was shared with an unauthorized party and has been revoked.", page); } await host.StopAsync(CancellationToken.None); } } }
public async void TestDomainsLicense() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg")) { var clock = new FakeClock("2017-04-25", "2017-04-25"); var set = LicenseStrings.GetSets("PerCore2DomainsImageflow").First(); var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, new StringCacheMem()); MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, set.Remote, null); var url = new RequestUrlProvider(); var licensing = new Licensing(mgr, url.Get); using var host = await StartAsyncWithOptions(new ImageflowMiddlewareOptions () { Licensing = licensing, MyOpenSourceProjectUrl = null } .SetLicenseKey (EnforceLicenseWith.Http402Error, set.Placeholder) .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images"))); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); mgr.WaitForTasks(); Assert.Empty(mgr.GetIssues()); url.Url = new Uri("https://unlicenseddomain.com"); using var notLicensedResponse = await client.GetAsync("/fire.jpg?w=1"); Assert.Equal(HttpStatusCode.PaymentRequired, notLicensedResponse.StatusCode); url.Url = new Uri("https://acme.com"); using var licensedResponse1 = await client.GetAsync("/fire.jpg?w=1"); licensedResponse1.EnsureSuccessStatusCode(); url.Url = new Uri("https://acmestaging.com"); using var licensedResponse2 = await client.GetAsync("/fire.jpg?w=1"); licensedResponse2.EnsureSuccessStatusCode(); url.Url = new Uri("https://subdomain.acme.com"); using var licensedResponse3 = await client.GetAsync("/fire.jpg?w=1"); licensedResponse3.EnsureSuccessStatusCode(); Assert.Empty(mgr.GetIssues()); var page = licensing.Result.ProvidePublicLicensesPage(); Assert.Contains("License Validation ON", page); Assert.DoesNotContain("No license keys found.", page); Assert.Contains("License valid for 2 domains, missing for 1 domains", page); Assert.Contains("Your license needs to be upgraded", page); Assert.Contains("You are using EnforceLicenseWith.Http402Error", page); await host.StopAsync(CancellationToken.None); } }
public async void TestLocalFiles() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg") .AddResource("images/logo.png", "TestFiles.imazen_400.png")) { var hostBuilder = new HostBuilder() .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")) .AddWatermark(new NamedWatermark("imazen", "/logo.png", new WatermarkOptions())) .AddWatermark(new NamedWatermark("broken", "/not_there.png", new WatermarkOptions()))); }); }); // Build and start the IHost using var host = await hostBuilder.StartAsync(); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); using var notFoundResponse = await client.GetAsync("/not_there.jpg"); Assert.Equal(HttpStatusCode.NotFound, notFoundResponse.StatusCode); using var watermarkBrokenResponse = await client.GetAsync("/fire.jpg?watermark=broken"); Assert.Equal(HttpStatusCode.NotFound, watermarkBrokenResponse.StatusCode); await Assert.ThrowsAsync <InvalidOperationException>(async() => { using var watermarkInvalidResponse = await client.GetAsync("/fire.jpg?watermark=not-a-watermark"); }); using var watermarkResponse = await client.GetAsync("/fire.jpg?watermark=imazen"); watermarkResponse.EnsureSuccessStatusCode(); using var response2 = await client.GetAsync("/fire.jpg?width=1"); response2.EnsureSuccessStatusCode(); var responseBytes = await response2.Content.ReadAsByteArrayAsync(); Assert.True(responseBytes.Length < 1000); using var response3 = await client.GetAsync("/fire.jpg"); response3.EnsureSuccessStatusCode(); responseBytes = await response3.Content.ReadAsByteArrayAsync(); Assert.Equal(contentRoot.GetResourceBytes("TestFiles.fire-umbrella-small.jpg"), responseBytes); await host.StopAsync(CancellationToken.None); } }
public async void TestRemoteReaderPlusRequestSigning() { // This is the key we use to encode the remote URL and ensure that we are authorized to fetch the given url const string remoteReaderKey = "remoteReaderSigningKey_changeMe"; // This is the key we use to ensure that the set of modifications to the remote file is permitted. const string requestSigningKey = "test key"; using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg")) { var hostBuilder = new HostBuilder() .ConfigureServices(services => { services.AddHttpClient(); services.AddImageflowRemoteReaderService(new RemoteReaderServiceOptions() { SigningKey = remoteReaderKey }.AddPrefix("/remote") ); }) .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")) .SetRequestSignatureOptions( new RequestSignatureOptions(SignatureRequired.ForAllRequests, new [] { requestSigningKey }) )); }); }); using var host = await hostBuilder.StartAsync(); using var client = host.GetTestClient(); // The origin file var remoteUrl = "https://imageflow-resources.s3-us-west-2.amazonaws.com/test_inputs/imazen_400.png"; // We encode it, but this doesn't add the /remote/ prefix since that is configurable var encodedRemoteUrl = RemoteReaderService.EncodeAndSignUrl(remoteUrl, remoteReaderKey); // Now we add the /remote/ prefix and add some commands var modifiedUrl = $"/remote/{encodedRemoteUrl}?width=1"; // Now we could stop here, but we also enabled request signing which is different from remote reader signing var signedModifiedUrl = Imazen.Common.Helpers.Signatures.SignRequest(modifiedUrl, requestSigningKey); using var signedResponse = await client.GetAsync(signedModifiedUrl); signedResponse.EnsureSuccessStatusCode(); // Now, verify that the remote url can't be fetched without signing it the second time, // since we called .SetRequestSignatureOptions using var halfSignedResponse = await client.GetAsync(modifiedUrl); Assert.Equal(HttpStatusCode.Forbidden, halfSignedResponse.StatusCode); await host.StopAsync(CancellationToken.None); } }
public async void TestLocalFiles() { using (var contentRoot = new TempContentRoot() .AddResource("images/fire.jpg", "TestFiles.fire-umbrella-small.jpg") .AddResource("images/fire.jfif", "TestFiles.fire-umbrella-small.jpg") .AddResource("images/fire umbrella.jpg", "TestFiles.fire-umbrella-small.jpg") .AddResource("images/logo.png", "TestFiles.imazen_400.png") .AddResource("images/wrong.webp", "TestFiles.imazen_400.png") .AddResource("images/wrong.jpg", "TestFiles.imazen_400.png") .AddResource("images/extensionless/file", "TestFiles.imazen_400.png")) { var hostBuilder = new HostBuilder() .ConfigureWebHost(webHost => { // Add TestServer webHost.UseTestServer(); webHost.Configure(app => { app.UseImageflow(new ImageflowMiddlewareOptions() .SetMapWebRoot(false) // Maps / to ContentRootPath/images .MapPath("/", Path.Combine(contentRoot.PhysicalPath, "images")) .MapPath("/insensitive", Path.Combine(contentRoot.PhysicalPath, "images"), true) .MapPath("/sensitive", Path.Combine(contentRoot.PhysicalPath, "images"), false) .HandleExtensionlessRequestsUnder("/extensionless/") .AddWatermark(new NamedWatermark("imazen", "/logo.png", new WatermarkOptions())) .AddWatermark(new NamedWatermark("broken", "/not_there.png", new WatermarkOptions())) .AddWatermarkingHandler("/", args => { if (args.Query.TryGetValue("water", out var value) && value == "mark") { args.AppliedWatermarks.Add(new NamedWatermark(null, "/logo.png", new WatermarkOptions())); } })); }); }); // Build and start the IHost using var host = await hostBuilder.StartAsync(); // Create an HttpClient to send requests to the TestServer using var client = host.GetTestClient(); using var notFoundResponse = await client.GetAsync("/not_there.jpg"); Assert.Equal(HttpStatusCode.NotFound, notFoundResponse.StatusCode); using var watermarkBrokenResponse = await client.GetAsync("/fire.jpg?watermark=broken"); Assert.Equal(HttpStatusCode.NotFound, watermarkBrokenResponse.StatusCode); await Assert.ThrowsAsync <InvalidOperationException>(async() => { using var watermarkInvalidResponse = await client.GetAsync("/fire.jpg?watermark=not-a-watermark"); }); using var watermarkResponse = await client.GetAsync("/fire.jpg?watermark=imazen"); watermarkResponse.EnsureSuccessStatusCode(); using var watermarkResponse2 = await client.GetAsync("/fire.jpg?water=mark"); watermarkResponse2.EnsureSuccessStatusCode(); using var wrongImageExtension1 = await client.GetAsync("/wrong.webp"); wrongImageExtension1.EnsureSuccessStatusCode(); Assert.Equal("image/png", wrongImageExtension1.Content.Headers.ContentType.MediaType); using var wrongImageExtension2 = await client.GetAsync("/wrong.jpg"); wrongImageExtension2.EnsureSuccessStatusCode(); Assert.Equal("image/png", wrongImageExtension2.Content.Headers.ContentType.MediaType); using var extensionlessRequest = await client.GetAsync("/extensionless/file"); extensionlessRequest.EnsureSuccessStatusCode(); Assert.Equal("image/png", extensionlessRequest.Content.Headers.ContentType.MediaType); using var response2 = await client.GetAsync("/fire.jpg?width=1"); response2.EnsureSuccessStatusCode(); var responseBytes = await response2.Content.ReadAsByteArrayAsync(); Assert.True(responseBytes.Length < 1000); using var response3 = await client.GetAsync("/fire%20umbrella.jpg"); response3.EnsureSuccessStatusCode(); responseBytes = await response3.Content.ReadAsByteArrayAsync(); Assert.Equal(contentRoot.GetResourceBytes("TestFiles.fire-umbrella-small.jpg"), responseBytes); using var response4 = await client.GetAsync("/inSenSitive/fire.jpg?width=1"); response4.EnsureSuccessStatusCode(); using var response5 = await client.GetAsync("/senSitive/fire.jpg?width=1"); Assert.Equal(HttpStatusCode.NotFound, response5.StatusCode); using var response6 = await client.GetAsync("/sensitive/fire.jpg?width=1"); response6.EnsureSuccessStatusCode(); using var response7 = await client.GetAsync("/fire.jfif?width=1"); response7.EnsureSuccessStatusCode(); var responseBytes7 = await response7.Content.ReadAsByteArrayAsync(); Assert.True(responseBytes7.Length < 1000); using var response8 = await client.GetAsync("/imageflow.health"); response8.EnsureSuccessStatusCode(); using var response9 = await client.GetAsync("/imageflow.ready"); response9.EnsureSuccessStatusCode(); await host.StopAsync(CancellationToken.None); } }