package com.ruoyi.system; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.storage.BusinessFileStorage; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.system.domain.SysNotice; import com.ruoyi.system.mapper.SysNoticeMapper; import com.ruoyi.system.service.impl.ManagedFileService; import com.ruoyi.system.service.impl.SysNoticeServiceImpl; import java.io.*; import java.nio.file.*; import java.util.*; import org.junit.jupiter.api.*; import org.mockito.MockedStatic; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.support.TransactionTemplate; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; class ManagedFileTest { JdbcTemplate db;BusinessFileStorage storage;ManagedFileService files;TransactionTemplate tx;MockedStatic security;Map objects;long actor=2;Set grants; static final String A="11111111-1111-4111-8111-111111111111",B="22222222-2222-4222-8222-222222222222"; @BeforeEach void setup()throws Exception{ var ds=new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa","");db=new JdbcTemplate(ds);tx=new TransactionTemplate(new DataSourceTransactionManager(ds)); db.execute("create table sys_user(user_id bigint primary key,nick_name varchar(64))");db.execute("insert into sys_user values(1,'管理员'),(2,'上传人'),(3,'同事')"); db.execute("create table sys_notice(notice_id int primary key,status varchar(1))");db.execute("insert into sys_notice values(10,'0'),(20,'1')"); Path root=Path.of(System.getProperty("user.dir"));if(!Files.exists(root.resolve("sql")))root=root.getParent();String sql=Files.readString(root.resolve("sql/projectdev/20261028_notice_files.sql"));sql=sql.substring(0,sql.indexOf("INSERT INTO sys_menu")).replaceAll("(?m)^--.*$","").replace(" ENGINE=InnoDB DEFAULT CHARSET=utf8mb4","");for(String statement:sql.split(";"))if(!statement.isBlank())db.execute(statement); objects=new HashMap<>();storage=mock(BusinessFileStorage.class);when(storage.isEnabled()).thenReturn(true);when(storage.exists(anyString(),isNull())).thenAnswer(c->objects.containsKey(c.getArgument(0)));when(storage.openStream(anyString())).thenAnswer(c->{var bytes=objects.get(c.getArgument(0));if(bytes==null)throw new FileNotFoundException();return new ByteArrayInputStream(bytes);});doAnswer(c->{objects.put(c.getArgument(0),((InputStream)c.getArgument(1)).readAllBytes());return null;}).when(storage).saveStream(anyString(),any(),anyLong(),anyString());doAnswer(c->{objects.remove(c.getArgument(0));return null;}).when(storage).discardFailedUpload(anyString(),isNull()); files=new ManagedFileService(db,storage);grants=new HashSet<>(Set.of("system:file:list","system:file:upload","system:file:download","system:file:remove","system:notice:add","system:notice:edit"));security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getUserId).thenAnswer(c->actor);security.when(SecurityUtils::getUsername).thenAnswer(c->"user"+actor);security.when(SecurityUtils::isAdmin).thenAnswer(c->actor==1);security.when(()->SecurityUtils.hasPermi(anyString())).thenAnswer(c->grants.contains(c.getArgument(0))); } @AfterEach void close(){security.close();} MockMultipartFile document(String name){return new MockMultipartFile("file",name,"application/octet-stream","isolated file bytes".getBytes());} @Test void sharedFilesRequireDownloadAndOnlyUploaderWithDeleteAuthorityOrAdministratorMayRemove()throws Exception{ var file=files.upload(false,A,document("文件.zip"));assertEquals(A,file.id());assertEquals("上传人",file.uploadedBy());assertEquals(1L,files.page("文件",false,1,20).get("total")); actor=3;assertEquals(1L,files.page("",false,1,20).get("total"));assertEquals(0L,files.page("",true,1,20).get("total"));try(var read=files.open(A).input()){assertArrayEquals("isolated file bytes".getBytes(),read.readAllBytes());}assertThrows(ServiceException.class,()->files.remove(A)); grants.remove("system:file:download");assertThrows(ServiceException.class,()->files.open(A));actor=1;files.remove(A);assertThrows(ServiceException.class,()->files.open(A));assertEquals(0L,files.page("",false,1,20).get("total")); } @Test void noticeDraftsCannotBeStolenAndPublishedAttachmentsAreReadableWithoutFileLibraryPermissions()throws Exception{ files.upload(true,A,document("说明.pdf"));assertTrue(files.alive(true,A));actor=3;assertThrows(ServiceException.class,()->files.open(A));assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->files.bindNotice(10,List.of(A)))); actor=2;tx.executeWithoutResult(s->files.bindNotice(10,List.of(A)));assertFalse(files.alive(true,A));grants.clear();actor=3;assertEquals(1,files.noticeFiles(10).size());try(var in=files.open(A).input()){assertTrue(in.readAllBytes().length>0);}assertThrows(ServiceException.class,()->files.noticeFiles(20)); actor=2;grants.add("system:notice:edit");assertThrows(ServiceException.class,()->files.remove(A));assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->files.bindNotice(20,List.of(A))));assertEquals(1,files.noticeFiles(10).size()); db.update("update sys_notice set status='1' where notice_id=10");actor=3;grants.clear();assertThrows(ServiceException.class,()->files.open(A));actor=2;grants.add("system:notice:edit");assertEquals(1,files.noticeFiles(10).size()); } @Test void noticeUpdatesKeepExistingAttachmentsForOldClientsAndValidateBeforeReplacingAllLinks(){ files.upload(true,A,document("附件.txt"));tx.executeWithoutResult(s->files.bindNotice(10,List.of(A)));files.bindNotice(10,null);assertEquals(1,files.noticeFiles(10).size()); assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->files.bindNotice(10,List.of(B))));assertEquals(1,files.noticeFiles(10).size()); tx.executeWithoutResult(s->files.bindNotice(10,List.of()));assertEquals(0,files.noticeFiles(10).size());assertTrue(files.alive(true,A));files.remove(A);assertThrows(ServiceException.class,()->files.open(A)); } @Test void invalidAttachmentRollsBackNewNoticeAndUploadMetadataFailureRollsBackNewObject(){ var mapper=mock(SysNoticeMapper.class);when(mapper.insertNotice(any())).thenAnswer(c->{SysNotice notice=c.getArgument(0);notice.setNoticeId(30L);db.update("insert into sys_notice values(30,'0')");return 1;});var notices=new SysNoticeServiceImpl();ReflectionTestUtils.setField(notices,"noticeMapper",mapper);ReflectionTestUtils.setField(notices,"files",files);var notice=new SysNotice();notice.setAttachmentIds(List.of(B));assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->notices.insertNotice(notice)));assertEquals(0,db.queryForObject("select count(*) from sys_notice where notice_id=30",Integer.class)); assertThrows(IllegalStateException.class,()->tx.executeWithoutResult(s->{files.upload(false,A,document("test.txt"));throw new IllegalStateException("rollback");}));assertFalse(objects.containsKey("managed-file/"+A+".bin"));assertEquals(0,db.queryForObject("select count(*) from sys_managed_file",Integer.class)); } @Test void uploadRetriesAreIdempotentAndFileNamesAreSafeWithoutRequiringAnExtension()throws Exception{ files.upload(false,A,document("LICENSE"));files.upload(false,A,document("LICENSE"));verify(storage,times(1)).saveStream(anyString(),any(),anyLong(),anyString()); assertThrows(ServiceException.class,()->files.upload(false,A,document("different.txt")));assertThrows(ServiceException.class,()->ManagedFileService.safeName("../secret"));assertThrows(ServiceException.class,()->ManagedFileService.safeName("a\r\nHeader.txt"));assertThrows(ServiceException.class,()->files.open("../")); var large=mock(org.springframework.web.multipart.MultipartFile.class);when(large.isEmpty()).thenReturn(false);when(large.getSize()).thenReturn((long)ManagedFileService.MAX_BYTES+1);assertThrows(ServiceException.class,()->files.upload(false,B,large)); } @Test void fileLibraryObjectCannotBeReclassifiedAsPublicNoticeEvidence(){files.upload(false,A,document("private.txt"));assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->files.bindNotice(10,List.of(A))));assertTrue(files.noticeFiles(10).isEmpty());} }