修改问题
这个提交包含在:
+3
@@ -15,6 +15,8 @@ public class PrivateBusinessFileAuthorizationGateway {
|
||||
private AuthorizationOwner governance;
|
||||
@DubboReference(group = "aixun-datagov-private-file-dataops", version = "1.0.0", check = false, retries = 0)
|
||||
private AuthorizationOwner dataops;
|
||||
@DubboReference(group = "aixun-datagov-private-file-integration", version = "1.0.0", check = false, retries = 0)
|
||||
private AuthorizationOwner integration;
|
||||
|
||||
AuthorizationDecision require(AuthorizationQuery query) {
|
||||
if (!Boolean.TRUE.equals(SaManager.getConfig().getCheckSameToken()))
|
||||
@@ -25,6 +27,7 @@ public class PrivateBusinessFileAuthorizationGateway {
|
||||
case "dataproduct" -> dataproduct;
|
||||
case "governance" -> governance;
|
||||
case "dataops" -> dataops;
|
||||
case "integration" -> integration;
|
||||
default -> throw new IllegalStateException("PRIVATE_FILE_OWNER_NOT_CONFIGURED");
|
||||
};
|
||||
AuthorizationDecision decision;
|
||||
|
||||
+11
-2
@@ -19,6 +19,9 @@ import java.util.function.Supplier;
|
||||
/** The operation row commits independently of the consuming business transaction. */
|
||||
@Repository
|
||||
public class PrivateBusinessFileJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
static final String PRIVATE_SERVICE = "datagov-local-pvt";
|
||||
private final JdbcTemplate jdbc;
|
||||
private final TransactionTemplate transactions;
|
||||
@@ -47,13 +50,19 @@ public class PrivateBusinessFileJdbcRepository {
|
||||
Stored reserve(StageRequest request, String descriptorSha, String storageKey) {
|
||||
Context c = request.context();
|
||||
// The unique operation scope excludes Actor: a different currently authorized reviewer can recover.
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(sys_oss_business_binding) */ INTO sys_oss_business_binding
|
||||
(organization_id,department_id,operation_key,descriptor_sha256,payload_sha256,oss_id,
|
||||
storage_key,target_json,state,next_offset,producer_actor,created_at,updated_at,row_version)
|
||||
VALUES (?,?,?,?,?,?,?,?,'PREPARING',0,?,CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6),0)
|
||||
|
||||
""", c.organizationId(), c.departmentId(), request.operationKey(), descriptorSha,
|
||||
""", """
|
||||
INSERT IGNORE INTO sys_oss_business_binding
|
||||
(organization_id,department_id,operation_key,descriptor_sha256,payload_sha256,oss_id,
|
||||
storage_key,target_json,state,next_offset,producer_actor,created_at,updated_at,row_version)
|
||||
VALUES (?,?,?,?,?,?,?,?,'PREPARING',0,?,CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6),0)
|
||||
|
||||
"""), c.organizationId(), c.departmentId(), request.operationKey(), descriptorSha,
|
||||
request.payloadSha256(), IdGeneratorUtil.nextLongId(), storageKey,
|
||||
JsonUtils.toJsonString(request.target()), c.actorId());
|
||||
Stored stored = find(new WriteQuery(c, request.operationKey()));
|
||||
|
||||
+5
-2
@@ -25,9 +25,10 @@ public class PrivateBusinessFileService {
|
||||
|
||||
public WriteStatus stage(StageRequest request) {
|
||||
String name=request.target().originalName().toLowerCase(java.util.Locale.ROOT);
|
||||
if(name.endsWith(".xml")&&!reportingFile(request.target()))throw new IllegalArgumentException("PRIVATE_FILE_TYPE");
|
||||
if(name.endsWith(".doc")&&!ingestionOriginal(request.target())) throw new IllegalArgumentException("PRIVATE_FILE_TYPE");
|
||||
if((name.endsWith(".md")||name.endsWith(".docx")||name.endsWith(".zip"))
|
||||
&&!knowledgeOriginal(request.target())&&!(ingestionOriginal(request.target())&&name.endsWith(".docx"))) throw new IllegalArgumentException("PRIVATE_FILE_TYPE");
|
||||
&&!knowledgeOriginal(request.target())&&!(reportingFile(request.target())&&name.endsWith(".zip"))&&!(ingestionOriginal(request.target())&&name.endsWith(".docx"))) throw new IllegalArgumentException("PRIVATE_FILE_TYPE");
|
||||
storage.validatePrivate(request.target().originalName(), request.target().byteLength());
|
||||
authorization.require(new AuthorizationQuery(request.context(), request.target(), Action.STAGE, null, request.operationKey()));
|
||||
return repository.transaction(() -> {
|
||||
@@ -62,7 +63,8 @@ public class PrivateBusinessFileService {
|
||||
if (stored.state() == WriteState.BOUND || stored.state() == WriteState.STAGED) return stored.view();
|
||||
if (stored.offset() != stored.target().byteLength()) throw new IllegalStateException("PRIVATE_FILE_INCOMPLETE");
|
||||
byte[] bytes = read(stored);
|
||||
storage.validatePrivateContent(stored.target().originalName(), bytes, stored.target().mime());
|
||||
if(reportingFile(stored.target()))storage.validateReportingContent(stored.target().originalName(),bytes,stored.target().mime());
|
||||
else storage.validatePrivateContent(stored.target().originalName(), bytes, stored.target().mime());
|
||||
authorize(query.context(), stored, Action.FINISH);
|
||||
repository.progress(stored, stored.offset(), WriteState.STAGED);
|
||||
return new WriteStatus(stored.operationKey(), WriteState.STAGED, stored.binding(), stored.offset());
|
||||
@@ -110,6 +112,7 @@ public class PrivateBusinessFileService {
|
||||
}
|
||||
private static boolean knowledgeOriginal(Target t) { return "governance".equals(t.businessOwner())&&"WORKBENCH_KNOWLEDGE_ATTACHMENT".equals(t.objectType())&&"KNOWLEDGE_ORIGINAL".equals(t.purpose())&&t.use()==FileUse.EVIDENCE; }
|
||||
private static boolean ingestionOriginal(Target t) { return "dataops".equals(t.businessOwner())&&"INGESTION_ORIGINAL_FILE".equals(t.objectType())&&"INGESTION_ORIGINAL_FILE".equals(t.purpose())&&t.use()==FileUse.EVIDENCE; }
|
||||
private static boolean reportingFile(Target t) { return "integration".equals(t.businessOwner())&&"REGULATORY_REPORTING_ARTIFACT".equals(t.objectType())&&"REGULATORY_REPORTING".equals(t.purpose())&&(t.use()==FileUse.EVIDENCE||t.use()==FileUse.DELIVERY_PACKAGE); }
|
||||
|
||||
public FileResolution resolveFile(FileQuery query) {
|
||||
return repository.transaction(() -> {
|
||||
|
||||
+11
-2
@@ -92,7 +92,7 @@ public class DataGovLocalFileStorage {
|
||||
public void validatePrivate(String originalName, long length) {
|
||||
if (!enabled || length <= 0 || length > maxBytes) throw new IllegalArgumentException("PRIVATE_FILE_SIZE");
|
||||
String ext = suffix(originalName);
|
||||
if (!ALLOWED_SUFFIXES.contains(ext) && !Set.of(".jsonl",".md",".docx",".doc",".zip").contains(ext))
|
||||
if (!ALLOWED_SUFFIXES.contains(ext) && !Set.of(".jsonl",".md",".docx",".doc",".zip",".xml").contains(ext))
|
||||
throw new IllegalArgumentException("PRIVATE_FILE_TYPE");
|
||||
}
|
||||
|
||||
@@ -165,9 +165,18 @@ public class DataGovLocalFileStorage {
|
||||
}
|
||||
if (!detected.equals(mime)) throw new IllegalArgumentException("PRIVATE_FILE_MIME");
|
||||
}
|
||||
/** Called only after Resource confirms the reporting business owner and immutable target. */
|
||||
public void validateReportingContent(String name,byte[] bytes,String mime){
|
||||
validatePrivate(name,bytes.length);
|
||||
String ext=suffix(name);
|
||||
if(".xml".equals(ext)||".zip".equals(ext)){
|
||||
if(!mime.equals(".xml".equals(ext)?"application/xml":"application/zip"))throw new IllegalArgumentException("PRIVATE_FILE_MIME");
|
||||
ReportingArchiveSafety.check(bytes,".xml".equals(ext),this::validatePrivateContent);
|
||||
}else validatePrivateContent(name,bytes,mime);
|
||||
}
|
||||
|
||||
private Path privatePath(String key) throws IOException {
|
||||
if (!enabled || key == null || !key.matches("private-[a-f0-9-]{36}\\.(txt|csv|json|jsonl|pdf|png|jpg|jpeg|md|docx|doc|zip)"))
|
||||
if (!enabled || key == null || !key.matches("private-[a-f0-9-]{36}\\.(txt|csv|json|jsonl|pdf|png|jpg|jpeg|md|docx|doc|zip|xml)"))
|
||||
throw new IOException("PRIVATE_FILE_KEY");
|
||||
Path path = resolve(key);
|
||||
for (Path part = root; part != null; part = part.getParent())
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package cn.aixunkeji.resource.storage;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy;
|
||||
|
||||
final class ReportingArchiveSafety {
|
||||
private ReportingArchiveSafety() { }
|
||||
@FunctionalInterface interface ContentCheck { void check(String name,byte[] bytes,String mime); }
|
||||
static void check(byte[] bytes,boolean xml){
|
||||
check(bytes,xml,(name,data,mime)->{});
|
||||
}
|
||||
static void check(byte[] bytes,boolean xml,ContentCheck content){
|
||||
if(bytes==null||bytes.length==0||bytes.length>10*1024*1024)throw invalid();
|
||||
if(xml){xml(bytes);return;}
|
||||
int count=0,xmls=0,attachments=0;long expanded=0,attachmentBytes=0;var names=new HashSet<String>();
|
||||
try(var zip=new ZipInputStream(new ByteArrayInputStream(bytes))){
|
||||
for(var e=zip.getNextEntry();e!=null;e=zip.getNextEntry()){
|
||||
String n=e.getName();
|
||||
if(++count>500||n.length()>240||!names.add(n.toLowerCase(Locale.ROOT))||n.contains("\\")||n.contains("..")||n.startsWith("/")||n.contains(":"))throw invalid();
|
||||
if(e.isDirectory()){if(!"unStruct/".equals(n))throw invalid();continue;}
|
||||
byte[] data=zip.readNBytes(10*1024*1024+1);expanded+=data.length;
|
||||
if(data.length>10*1024*1024||expanded>50*1024*1024||expanded>Math.max(1024*1024,bytes.length*100L))throw invalid();
|
||||
if(n.matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}\\.xml")){xml(data);xmls++;}
|
||||
else {
|
||||
if(!n.startsWith("unStruct/"))throw invalid();
|
||||
String name=n.substring(9);ReportingAttachmentPolicy.verify(name,data);
|
||||
attachmentBytes+=data.length;
|
||||
if(++attachments>ReportingAttachmentPolicy.MAX_FILES||attachmentBytes>ReportingAttachmentPolicy.MAX_BYTES)throw invalid();
|
||||
content.check(name,data,ReportingAttachmentPolicy.mime(name));
|
||||
}
|
||||
}
|
||||
if(xmls==0)throw invalid();
|
||||
}catch(java.io.IOException e){throw invalid();}
|
||||
}
|
||||
private static void xml(byte[] bytes){try{
|
||||
var f=DocumentBuilderFactory.newInstance();f.setNamespaceAware(true);f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);
|
||||
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);f.setFeature("http://xml.org/sax/features/external-general-entities",false);f.setFeature("http://xml.org/sax/features/external-parameter-entities",false);
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA,"");f.setXIncludeAware(false);f.setExpandEntityReferences(false);
|
||||
var b=f.newDocumentBuilder();b.setErrorHandler(new org.xml.sax.helpers.DefaultHandler(){@Override public void fatalError(org.xml.sax.SAXParseException e)throws org.xml.sax.SAXException{throw e;}});
|
||||
if(b.parse(new ByteArrayInputStream(bytes)).getDocumentElement()==null)throw invalid();
|
||||
}catch(Exception e){throw invalid();}}
|
||||
private static IllegalArgumentException invalid(){return new IllegalArgumentException("REPORTING_ARCHIVE_INVALID");}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package cn.aixunkeji.resource.storage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ReportingArchiveSafetyTest {
|
||||
byte[] packageWith(String name,byte[] bytes)throws Exception{var output=new ByteArrayOutputStream();try(var zip=new ZipOutputStream(output)){zip.putNextEntry(new ZipEntry("R.xml"));zip.write("<Package/>".getBytes(StandardCharsets.UTF_8));zip.closeEntry();zip.putNextEntry(new ZipEntry(name));zip.write(bytes);zip.closeEntry();}return output.toByteArray();}
|
||||
@Test void attachmentMustMatchDigestAndPassContentValidation()throws Exception{byte[] body="evidence".getBytes(StandardCharsets.UTF_8);String name=cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.md5(body)+"_proof.txt";var calls=new java.util.ArrayList<String>();ReportingArchiveSafety.check(packageWith("unStruct/"+name,body),false,(n,b,m)->{calls.add(n);assertEquals("text/plain",m);assertArrayEquals(body,b);});assertEquals(java.util.List.of(name),calls);assertThrows(IllegalArgumentException.class,()->ReportingArchiveSafety.check(packageWith("unStruct/"+name,new byte[]{1}),false));assertThrows(IllegalArgumentException.class,()->ReportingArchiveSafety.check(packageWith("unStruct/"+name,body),false,(n,b,m)->{throw new IllegalArgumentException("CONTENT_INVALID");}));}
|
||||
byte[] zip(String name,String body)throws Exception{var output=new ByteArrayOutputStream();try(var zip=new ZipOutputStream(output)){zip.putNextEntry(new ZipEntry(name));zip.write(body.getBytes(StandardCharsets.UTF_8));zip.closeEntry();}return output.toByteArray();}
|
||||
@Test void acceptsFlatXmlPackage()throws Exception{assertDoesNotThrow(()->ReportingArchiveSafety.check(zip("R.xml","<Package><Records/></Package>"),false));}
|
||||
@Test void rejectsExternalEntities()throws Exception{assertThrows(IllegalArgumentException.class,()->ReportingArchiveSafety.check(zip("R.xml","<!DOCTYPE x [<!ENTITY a SYSTEM 'file:///etc/passwd'>]><x>&a;</x>"),false));}
|
||||
@Test void rejectsTraversalAndNonXmlPayload()throws Exception{assertThrows(IllegalArgumentException.class,()->ReportingArchiveSafety.check(zip("../R.xml","<x/>"),false));assertThrows(IllegalArgumentException.class,()->ReportingArchiveSafety.check(zip("run.sh","echo test"),false));}
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户