Browse Source

Merge remote-tracking branch 'origin/rel-10.7' into auto-merge-forward/rel-10.7-to-dev-67

pull/26238/head
github-actions[bot] 1 month ago
parent
commit
3c9a7fc86c
  1. 5
      .github/workflows/auto-merge-forward.yml
  2. 14
      docs/en/framework/architecture/best-practices/entities.md
  3. 12
      docs/en/framework/architecture/modularity/basics.md
  4. 29
      docs/en/studio/release-notes.md
  5. 1
      docs/en/studio/version-mapping.md
  6. 34
      framework/src/Volo.Abp.BlobStoring.FileSystem/Volo/Abp/BlobStoring/FileSystem/DefaultBlobFilePathCalculator.cs
  7. 111
      framework/test/Volo.Abp.BlobStoring.FileSystem.Tests/Volo/Abp/BlobStoring/FileSystem/BlogFilePathCalculator_Tests.cs
  8. 70
      framework/test/Volo.Abp.BlobStoring.FileSystem.Tests/Volo/Abp/BlobStoring/FileSystem/FileSystemBlobContainer_Path_Tests.cs
  9. 23
      modules/blogging/src/Volo.Blogging.Application/Volo/Blogging/Files/FileAppService.cs
  10. 144
      modules/blogging/test/Volo.Blogging.Application.Tests/Volo/Blogging/FileAppService_Tests.cs

5
.github/workflows/auto-merge-forward.yml

@ -106,11 +106,14 @@ jobs:
git push origin "$FORWARD_BRANCH"
echo "branch=$FORWARD_BRANCH" >> "$GITHUB_OUTPUT"
# BOT_SECRET, not github.token: a PR opened with the default token gets its
# pull_request checks stuck in "action_required", so they never pass and the
# PR stays permanently blocked from merging.
- name: Create pull request
if: steps.target.outputs.skip != 'true'
id: pr
env:
GH_TOKEN: ${{ github.token }}
GH_TOKEN: ${{ secrets.BOT_SECRET }}
run: |
set -euo pipefail
SOURCE="${{ steps.target.outputs.source }}"

14
docs/en/framework/architecture/best-practices/entities.md

@ -13,7 +13,7 @@
## Entities
Every aggregate root is also an entity. So, these rules are valid for aggregate roots too unless aggregate root rules override them.
Every aggregate root is also an entity. So, these rules are valid for aggregate roots too, unless aggregate root rules override them.
- **Do** define entities in the **domain layer**.
@ -22,7 +22,7 @@ Every aggregate root is also an entity. So, these rules are valid for aggregate
* **Do** define a **primary constructor** that ensures the validity of the entity on creation. Primary constructors are used to create a new instance of the entity by the application code.
- **Do** define primary constructor as `public`, `internal` or `protected internal` based on the requirements. If it's not public, the entity is expected to be created by a domain service.
- **Do** always initialize sub collections in the primary constructor.
- **Do** always initialize sub-collections in the primary constructor.
- **Do not** generate `Guid` keys inside the constructor. Get it as a parameter, so the calling code will use `IGuidGenerator` to generate a new `Guid` value.
### Parameterless Constructor
@ -55,7 +55,7 @@ Every aggregate root is also an entity. So, these rules are valid for aggregate
### Aggregate Boundary
* **Do** keep aggregates **as small as possible**. Most of the aggregates will only have primitive properties and will not have sub collections. Consider these as design decisions:
* **Do** keep aggregates **as small as possible**. Most aggregates will have only primitive properties and no sub-collections. Consider these as design decisions:
* **Performance** & **memory** cost of loading & saving aggregates (keep in mind that an aggregate is normally loaded & saved as a single unit). Larger aggregates will consume more CPU & memory.
* **Consistency** & **validity** boundary.
@ -75,9 +75,9 @@ public class Issue : FullAuditedAggregateRoot<Guid> //Using Guid as the key/iden
protected Issue()
{
/* This constructor is for ORMs to be used while getting the entity from database.
/* This constructor is for ORMs to be used while getting the entity from the database.
* - No need to initialize the Labels collection
since it will be overrided from the database.
since it will be overridden from the database.
- It's protected since proxying and deserialization tools
may not work with private constructors.
*/
@ -104,7 +104,7 @@ public class Issue : FullAuditedAggregateRoot<Guid> //Using Guid as the key/iden
return this;
}
/* AddLabel & RemoveLabel methods manages the Labels collection
/* AddLabel & RemoveLabel methods manage the Labels collection
* in a safe way (prevents adding the same label twice) */
public virtual Issue AddLabel(Guid labelId)
@ -170,4 +170,4 @@ public class IssueLabel : Entity
## See Also
* [Video tutorial](https://abp.io/video-courses/essentials/entities)
* [Video tutorial](https://abp.io/video-courses/essentials/entities)

12
docs/en/framework/architecture/modularity/basics.md

@ -13,7 +13,7 @@ ABP was designed to support to build fully modular applications and systems wher
* The [modular monolith application development tutorial](../../../tutorials/modular-crm/index.md) explains and demonstrates how to build **modular monolith applications** with ABP.
* [Pre-built application modules](../../../modules/index.md) are **ready to use** in any kind of application.
* [Module startup template](../../../solution-templates/application-module/index.md) is a jump start way to **create a new reusable application module**.
* [Module development best practice guide](../best-practices/index.md) explains some **best practices** to develop **re-usable application modules** based on **DDD** principles and layers. A module designed based on this guide will be **database independent** and can be deployed as a **microservice** if needed.
* [Module development best practice guide](../best-practices/index.md) explains some **best practices** to develop **re-usable application modules** based on **DDD** principles and layers. A module designed based on this guide will be **database-independent** and can be deployed as a **microservice** if needed.
* [ABP CLI](../../../cli/index.md) has commands to support modular development.
* All other framework features are compatible to the modularity system.
@ -46,7 +46,7 @@ public class BlogModule : AbpModule
}
````
You can register dependencies one by one as stated in Microsoft's [documentation](../../fundamentals/dependency-injection.md). But ABP has a **conventional dependency registration system** which automatically register all services in your assembly. See the [dependency Injection](../../fundamentals/dependency-injection.md) documentation for more about the dependency injection system.
You can register dependencies one by one as stated in Microsoft's [documentation](../../fundamentals/dependency-injection.md). But ABP has a **conventional dependency registration system** which automatically registers all services in your assembly. See the [dependency injection](../../fundamentals/dependency-injection.md) documentation for more about the dependency injection system.
You can also configure other services and modules in this way. Example:
@ -186,7 +186,7 @@ Contributor order is the order of the `Contributors` list. The four built-in con
Lastly, you can override ``OnApplicationShutdown`` method if you want to execute some code while application is being shutdown.
> This methods has asynchronous version too. If you want to make asynchronous calls inside this method, override the asynchronous version instead of the synchronous one.
> This method has an asynchronous version too. If you want to make asynchronous calls inside this method, override the asynchronous version instead of the synchronous one.
## Module Dependencies
@ -201,7 +201,7 @@ public class BlogModule
}
````
You can use multiple ``DependsOn`` attribute or pass multiple module types to a single ``DependsOn`` attribute depending on your preference.
You can use multiple ``DependsOn`` attributes or pass multiple module types to a single ``DependsOn`` attribute depending on your preference.
A depended module may depend on another module, but you only need to define your direct dependencies. ABP investigates the dependency graph for the application at startup and initializes/shutdowns modules in the correct order.
@ -224,13 +224,13 @@ In this example, we assume that the `BlogService` class is inside one assembly (
Notice that `BlogService` is only an arbitrary selected type in the target assembly. It is just used to indicate the related assembly. You could use any type in the assembly.
> WARNING: If you need to use the `AdditionalAssembly`, be sure that you don't design your system in a wrong way. With this example above, the `BlogService` class' assembly should normally have its own module class and the `BlogModule` should depend on it using the `DependsOn` attribute. Do not use the `AdditionalAssembly` attribute when you can already use the `DependsOn` attribute.
> WARNING: If you need to use the `AdditionalAssembly`, be sure that you don't design your system in a wrong way. With the example above, the `BlogService` class' assembly should normally have its own module class and the `BlogModule` should depend on it using the `DependsOn` attribute. Do not use the `AdditionalAssembly` attribute when you can already use the `DependsOn` attribute.
## Framework Modules vs Application Modules
There are **two types of modules.** They don't have any structural difference but categorized by functionality and purpose:
- **Framework modules**: These are **core modules of the framework** like caching, emailing, theming, security, serialization, validation, EF Core integration, MongoDB integration... etc. They do not have application/business functionalities but makes your daily development easier by providing common infrastructure, integration and abstractions.
- **Framework modules**: These are **core modules of the framework** like caching, emailing, theming, security, serialization, validation, EF Core integration, MongoDB integration... etc. They do not have application/business functionalities but make your daily development easier by providing common infrastructure, integration and abstractions.
- **Application modules**: These modules implement **specific application/business functionalities** like blogging, document management, identity management, tenant management... etc. They generally have their own entities, services, APIs and UI components. See [pre-built application modules](../../../modules).
## See Also

29
docs/en/studio/release-notes.md

@ -9,7 +9,34 @@
This document contains **brief release notes** for each ABP Studio release. Release notes only include **major features** and **visible enhancements**. Therefore, they don't include all the development done in the related version.
## 3.1.1 (2026-08-28) Latest
## 3.1.4 (2026-10-05) Latest
* Update built-in AI Assistant default models
* Fix sidebar flyout backdrop so Switch branch dimming works
* Support running several ABP Studio instances side
* Show .abpignore paths to the AI without exposing contents
* Open macOS folders in Finder instead of Terminal
* Fix Containers Start staying disabled after bind
* Fix missing scroll on the browser start page application list
* Use classic console colors for the light-theme terminal palette
## 3.1.3 (2026-09-22)
* Upgrade Studio to Avalonia 12
* Bump ABP Studio version to 3.1.3 and update related properties
## 3.1.2 (2026-09-22)
* UI/UX Improvements
* Auto-merge forward rel-3.0 → rel-3.1 by: //github.com/volosoft/abp-studio/pull/5335
* Add grouped sidebar navigation to classic and modern solution wizards
* Fix update toasts and assistant response copy actions
* Add notification for human authors on merge conflicts in auto-merge w…
* Studio browser: persistent profiles, history, pinning, find, and device preview
* Hide provider dashboard links from AI error messages
* Fix macOS .zshrc corruption from interactive shell env capture
## 3.1.1 (2026-08-28)
* Refactor release version resolution logic to ensure proper tag handling
* Fix chmod command syntax in set-executable-permissions scripts for Li…

1
docs/en/studio/version-mapping.md

@ -11,6 +11,7 @@ This document provides a general overview of the relationship between various ve
| **ABP Studio Version** | **ABP Version of Startup Template** |
|------------------------|---------------------------|
| 3.1.2 - 3.1.4 | 10.6.1 |
| 3.0.9 - 3.1.1 | 10.6.0 |
| 3.0.6 - 3.0.8 | 10.5.0 |
| 3.0.4 - 3.0.5 | 10.4.1 |

34
framework/src/Volo.Abp.BlobStoring.FileSystem/Volo/Abp/BlobStoring/FileSystem/DefaultBlobFilePathCalculator.cs

@ -1,4 +1,6 @@
using System.IO;
using System;
using System.IO;
using System.Linq;
using Volo.Abp.DependencyInjection;
using Volo.Abp.MultiTenancy;
@ -16,7 +18,7 @@ public class DefaultBlobFilePathCalculator : IBlobFilePathCalculator, ITransient
public virtual string Calculate(BlobProviderArgs args)
{
var fileSystemConfiguration = args.Configuration.GetFileSystemConfiguration();
var blobPath = fileSystemConfiguration.BasePath;
var blobPath = Path.GetFullPath(fileSystemConfiguration.BasePath);
if (CurrentTenant.Id == null)
{
@ -29,11 +31,33 @@ public class DefaultBlobFilePathCalculator : IBlobFilePathCalculator, ITransient
if (fileSystemConfiguration.AppendContainerNameToBasePath)
{
blobPath = Path.Combine(blobPath, args.ContainerName);
blobPath = CombineRelativePath(blobPath, args.ContainerName, nameof(args.ContainerName));
}
blobPath = Path.Combine(blobPath, args.BlobName);
return CombineRelativePath(blobPath, args.BlobName, nameof(args.BlobName));
}
protected virtual string CombineRelativePath(string rootPath, string relativePath, string parameterName)
{
if (Path.IsPathRooted(relativePath))
{
throw new ArgumentException($"The {parameterName} must be a relative path.", parameterName);
}
var segments = relativePath.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
if (segments.Any(segment => segment == "." || segment == ".."))
{
throw new ArgumentException($"The {parameterName} must not contain '.' or '..' segments.", parameterName);
}
var fullRootPath = Path.GetFullPath(rootPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var fullPath = Path.GetFullPath(Path.Combine(fullRootPath, relativePath));
if (!fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).StartsWith(fullRootPath + Path.DirectorySeparatorChar, StringComparison.Ordinal))
{
throw new ArgumentException($"The {parameterName} must point to a location inside the storage directory.", parameterName);
}
return blobPath;
return fullPath;
}
}

111
framework/test/Volo.Abp.BlobStoring.FileSystem.Tests/Volo/Abp/BlobStoring/FileSystem/BlogFilePathCalculator_Tests.cs

@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using Shouldly;
using Volo.Abp.MultiTenancy;
using Xunit;
@ -17,38 +18,128 @@ public class BlogFilePathCalculator_Tests : AbpBlobStoringFileSystemTestBase
_currentTenant = GetRequiredService<ICurrentTenant>();
}
private static readonly string BasePath = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "my-files"));
[Fact]
public void Default_Settings()
{
var separator = Path.DirectorySeparatorChar;
_calculator.Calculate(
GetArgs($"C:{separator}my-files", "my-container", "my-blob")
).ShouldBe($"C:{separator}my-files{separator}host{separator}my-container{separator}my-blob");
GetArgs(BasePath, "my-container", "my-blob")
).ShouldBe(Path.Combine(BasePath, "host", "my-container", "my-blob"));
}
[Fact]
public void Default_Settings_With_TenantId()
{
var separator = Path.DirectorySeparatorChar;
var tenantId = Guid.NewGuid();
using (_currentTenant.Change(tenantId))
{
_calculator.Calculate(
GetArgs($"C:{separator}my-files", "my-container", "my-blob")
).ShouldBe($"C:{separator}my-files{separator}tenants{separator}{tenantId:D}{separator}my-container{separator}my-blob");
GetArgs(BasePath, "my-container", "my-blob")
).ShouldBe(Path.Combine(BasePath, "tenants", tenantId.ToString("D"), "my-container", "my-blob"));
}
}
[Fact]
public void AppendContainerNameToBasePath_Set_To_False()
{
var separator = Path.DirectorySeparatorChar;
_calculator.Calculate(
GetArgs(BasePath, "my-container", "my-blob", appendContainerNameToBasePath: false)
).ShouldBe(Path.Combine(BasePath, "host", "my-blob"));
}
[Fact]
public void Relative_BasePath()
{
_calculator.Calculate(
GetArgs("my-files", "my-container", "my-blob")
).ShouldBe(Path.GetFullPath(Path.Combine("my-files", "host", "my-container", "my-blob")));
}
[Theory]
[InlineData("my-folder/my-blob")]
[InlineData("my-folder/my-sub-folder/my-blob")]
[InlineData("my..blob")]
[InlineData("..my-blob")]
public void Should_Allow_BlobName_Inside_Container(string blobName)
{
_calculator.Calculate(
GetArgs(BasePath, "my-container", blobName)
).ShouldBe(Path.GetFullPath(Path.Combine(BasePath, "host", "my-container", blobName)));
}
[Theory]
[InlineData("../my-blob")]
[InlineData("../../my-blob")]
[InlineData("../../../my-blob")]
[InlineData("my-folder/../../my-blob")]
[InlineData("my-folder/../my-blob")]
[InlineData("./my-blob")]
[InlineData(".")]
[InlineData("./")]
[InlineData("my-folder/..")]
public void Should_Throw_If_BlobName_Contains_Navigation_Segments(string blobName)
{
Should.Throw<ArgumentException>(() => _calculator.Calculate(GetArgs(BasePath, "my-container", blobName)));
Should.Throw<ArgumentException>(() => _calculator.Calculate(GetArgs(BasePath, "my-container", blobName.Replace('/', Path.DirectorySeparatorChar))));
}
[Fact]
public void Should_Throw_If_BlobName_Is_Rooted()
{
Should.Throw<ArgumentException>(() => _calculator.Calculate(GetArgs(BasePath, "my-container", Path.Combine(BasePath, "host", "my-container", "my-blob"))));
Should.Throw<ArgumentException>(() => _calculator.Calculate(GetArgs(BasePath, "my-container", Path.Combine(Path.GetTempPath(), "my-blob"))));
Should.Throw<ArgumentException>(() => _calculator.Calculate(GetArgs(BasePath, "my-container", Path.DirectorySeparatorChar + "my-blob")));
}
[Theory]
[InlineData("C:my-blob")]
[InlineData("\\my-blob")]
[InlineData("\\\\server\\share\\my-blob")]
[InlineData("\\\\?\\C:\\my-blob")]
public void Should_Throw_If_BlobName_Is_Rooted_On_Windows(string blobName)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return;
}
Should.Throw<ArgumentException>(() => _calculator.Calculate(GetArgs(BasePath, "my-container", blobName)));
}
[Fact]
public void Should_Throw_If_BlobName_Points_To_Another_Tenant()
{
var tenantId = Guid.NewGuid();
var otherTenantId = Guid.NewGuid();
using (_currentTenant.Change(tenantId))
{
Should.Throw<ArgumentException>(() => _calculator.Calculate(
GetArgs(BasePath, "my-container", $"../../{otherTenantId:D}/my-container/my-blob")));
Should.Throw<ArgumentException>(() => _calculator.Calculate(
GetArgs(BasePath, "my-container", $"../{otherTenantId:D}/my-blob", appendContainerNameToBasePath: false)));
}
}
[Theory]
[InlineData("../my-container")]
[InlineData("../../tenants/my-container")]
[InlineData("my-folder/../my-container")]
[InlineData(".")]
public void Should_Throw_If_ContainerName_Contains_Navigation_Segments(string containerName)
{
Should.Throw<ArgumentException>(() => _calculator.Calculate(GetArgs(BasePath, containerName, "my-blob")));
}
[Fact]
public void Should_Ignore_ContainerName_If_AppendContainerNameToBasePath_Set_To_False()
{
_calculator.Calculate(
GetArgs($"C:{separator}my-files", "my-container", "my-blob", appendContainerNameToBasePath: false)
).ShouldBe($"C:{separator}my-files{separator}host{separator}my-blob");
GetArgs(BasePath, "../my-container", "my-blob", appendContainerNameToBasePath: false)
).ShouldBe(Path.Combine(BasePath, "host", "my-blob"));
}
private static BlobProviderArgs GetArgs(

70
framework/test/Volo.Abp.BlobStoring.FileSystem.Tests/Volo/Abp/BlobStoring/FileSystem/FileSystemBlobContainer_Path_Tests.cs

@ -0,0 +1,70 @@
using System;
using System.IO;
using System.Threading.Tasks;
using Shouldly;
using Volo.Abp.BlobStoring.TestObjects;
using Volo.Abp.MultiTenancy;
using Xunit;
namespace Volo.Abp.BlobStoring.FileSystem;
public class FileSystemBlobContainer_Path_Tests : AbpBlobStoringFileSystemTestBase
{
private readonly IBlobContainer<TestContainer1> _container;
private readonly ICurrentTenant _currentTenant;
private readonly string _basePath;
public FileSystemBlobContainer_Path_Tests()
{
_container = GetRequiredService<IBlobContainer<TestContainer1>>();
_currentTenant = GetRequiredService<ICurrentTenant>();
_basePath = GetRequiredService<IBlobContainerConfigurationProvider>()
.Get<TestContainer1>()
.GetFileSystemConfiguration()
.BasePath;
}
[Fact]
public async Task Should_Not_Access_Files_Outside_Container()
{
var outsideFilePath = Path.Combine(_basePath, "host", "outside.txt");
Directory.CreateDirectory(Path.GetDirectoryName(outsideFilePath)!);
File.WriteAllText(outsideFilePath, "outside");
const string blobName = "../outside.txt";
await Should.ThrowAsync<ArgumentException>(() => _container.SaveAsync(blobName, "changed".GetBytes(), overrideExisting: true));
await Should.ThrowAsync<ArgumentException>(() => _container.GetAllBytesOrNullAsync(blobName));
await Should.ThrowAsync<ArgumentException>(() => _container.ExistsAsync(blobName));
await Should.ThrowAsync<ArgumentException>(() => _container.DeleteAsync(blobName));
File.Exists(outsideFilePath).ShouldBeTrue();
File.ReadAllText(outsideFilePath).ShouldBe("outside");
}
[Fact]
public async Task Should_Not_Access_Blobs_Of_Another_Tenant()
{
var tenantId = Guid.NewGuid();
var otherTenantId = Guid.NewGuid();
var containerName = BlobContainerNameAttribute.GetContainerName<TestContainer1>();
using (_currentTenant.Change(otherTenantId))
{
await _container.SaveAsync("my-blob", "other tenant".GetBytes());
}
using (_currentTenant.Change(tenantId))
{
var blobName = $"../../{otherTenantId:D}/{containerName}/my-blob";
await Should.ThrowAsync<ArgumentException>(() => _container.GetAllBytesOrNullAsync(blobName));
await Should.ThrowAsync<ArgumentException>(() => _container.DeleteAsync(blobName));
}
using (_currentTenant.Change(otherTenantId))
{
(await _container.GetAllBytesAsync("my-blob")).ShouldBe("other tenant".GetBytes());
}
}
}

23
modules/blogging/src/Volo.Blogging.Application/Volo/Blogging/Files/FileAppService.cs

@ -4,7 +4,9 @@ using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Net.Mime;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp;
using Volo.Abp.Authorization;
using Volo.Abp.BlobStoring;
using Volo.Abp.Content;
using Volo.Abp.Validation;
@ -24,7 +26,7 @@ namespace Volo.Blogging.Files
public virtual async Task<RawFileDto> GetAsync(string name)
{
Check.NotNullOrWhiteSpace(name, nameof(name));
ValidateFileName(name);
return new RawFileDto
{
@ -34,10 +36,23 @@ namespace Volo.Blogging.Files
public virtual async Task<IRemoteStreamContent> GetFileAsync(string name)
{
ValidateFileName(name);
var fileStream = await BlobContainer.GetAsync(name);
return new RemoteStreamContent(fileStream, name, GetByExtension(Path.GetExtension(name)), disposeStream: true);
}
protected virtual void ValidateFileName(string name)
{
if (string.IsNullOrWhiteSpace(name) ||
name.IndexOfAny(new[] { '/', '\\' }) >= 0 ||
name == "." ||
name == "..")
{
ThrowValidationException("Invalid file name!", nameof(name));
}
}
private static string GetByExtension(string extension)
{
extension = extension.RemovePreFix(".").ToLowerInvariant();
@ -61,6 +76,11 @@ namespace Volo.Blogging.Files
public virtual async Task<FileUploadOutputDto> CreateAsync(FileUploadInputDto input)
{
if (!await AuthorizationService.IsGrantedAnyAsync(BloggingPermissions.Posts.Create, BloggingPermissions.Posts.Update))
{
throw new AbpAuthorizationException();
}
if (input.File == null)
{
ThrowValidationException("Bytes of file can not be null or empty!", nameof(input.File));
@ -85,6 +105,7 @@ namespace Volo.Blogging.Files
}
var uniqueFileName = GenerateUniqueFileName(Path.GetExtension(input.Name));
ValidateFileName(uniqueFileName);
await BlobContainer.SaveAsync(uniqueFileName, input.File.GetStream());

144
modules/blogging/test/Volo.Blogging.Application.Tests/Volo/Blogging/FileAppService_Tests.cs

@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using NSubstitute;
using Shouldly;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Volo.Abp.Authorization;
using Volo.Abp.BlobStoring;
using Volo.Abp.Content;
using Volo.Abp.Validation;
using Volo.Blogging.Files;
using Xunit;
namespace Volo.Blogging
{
public class FileAppService_Tests : BloggingApplicationTestBase
{
private readonly IFileAppService _fileAppService;
private IBlobContainer<BloggingFileContainer> _blobContainer;
private FakeAuthorizationService _authorizationService;
public FileAppService_Tests()
{
_fileAppService = GetRequiredService<IFileAppService>();
}
protected override void AfterAddApplication(IServiceCollection services)
{
_blobContainer = Substitute.For<IBlobContainer<BloggingFileContainer>>();
_blobContainer.GetAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_ => new MemoryStream(new byte[] { 1, 2, 3 }));
services.AddSingleton(_blobContainer);
_authorizationService = new FakeAuthorizationService();
services.Replace(ServiceDescriptor.Singleton<IAuthorizationService>(_authorizationService));
services.Replace(ServiceDescriptor.Singleton<IAbpAuthorizationService>(_authorizationService));
}
[Theory]
[InlineData("my-image.png")]
[InlineData("my..image.png")]
public async Task Should_Get_File(string name)
{
(await _fileAppService.GetAsync(name)).Bytes.ShouldBe(new byte[] { 1, 2, 3 });
(await _fileAppService.GetFileAsync(name)).FileName.ShouldBe(name);
}
[Theory]
[InlineData(" ")]
[InlineData(".")]
[InlineData("..")]
[InlineData("../my-image.png")]
[InlineData("..\\my-image.png")]
[InlineData("my-folder/my-image.png")]
[InlineData("my-folder\\my-image.png")]
public async Task Should_Not_Get_File_With_Invalid_Name(string name)
{
await Should.ThrowAsync<AbpValidationException>(() => _fileAppService.GetAsync(name));
await Should.ThrowAsync<AbpValidationException>(() => _fileAppService.GetFileAsync(name));
await _blobContainer.DidNotReceiveWithAnyArgs().GetAsync(default, default);
}
[Theory]
[InlineData(BloggingPermissions.Posts.Create)]
[InlineData(BloggingPermissions.Posts.Update)]
public async Task Should_Upload_Image_With_Create_Or_Update_Permission(string permission)
{
_authorizationService.GrantedPolicies.Add(permission);
var output = await _fileAppService.CreateAsync(CreateUploadInput());
output.Name.ShouldEndWith(".png");
output.WebUrl.ShouldBe("/api/blogging/files/www/" + output.Name);
await _blobContainer.Received(1).SaveAsync(output.Name, Arg.Any<Stream>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Should_Not_Upload_Image_Without_Permission()
{
_authorizationService.GrantedPolicies.Add(BloggingPermissions.Posts.Delete);
await Should.ThrowAsync<AbpAuthorizationException>(() => _fileAppService.CreateAsync(CreateUploadInput()));
await _blobContainer.DidNotReceiveWithAnyArgs().SaveAsync(default, default(Stream), default, default);
}
[Fact]
public async Task Should_Not_Upload_Image_With_Invalid_Name()
{
_authorizationService.GrantedPolicies.Add(BloggingPermissions.Posts.Create);
var input = CreateUploadInput();
input.Name = "my-image.png\\my-folder";
await Should.ThrowAsync<AbpValidationException>(() => _fileAppService.CreateAsync(input));
await _blobContainer.DidNotReceiveWithAnyArgs().SaveAsync(default, default(Stream), default, default);
}
private static FileUploadInputDto CreateUploadInput()
{
var stream = new MemoryStream();
using (var image = new Image<Rgba32>(1, 1))
{
image.SaveAsPng(stream);
}
stream.Position = 0;
return new FileUploadInputDto
{
Name = "my-image.png",
File = new RemoteStreamContent(stream, "my-image.png", "image/png")
};
}
private class FakeAuthorizationService : IAbpAuthorizationService
{
public HashSet<string> GrantedPolicies { get; } = new HashSet<string>();
public IServiceProvider ServiceProvider => null;
public ClaimsPrincipal CurrentPrincipal { get; } = new ClaimsPrincipal();
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements)
{
return Task.FromResult(AuthorizationResult.Success());
}
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
{
return Task.FromResult(GrantedPolicies.Contains(policyName) ? AuthorizationResult.Success() : AuthorizationResult.Failed());
}
}
}
}
Loading…
Cancel
Save