如何扫描并生成 `THIRD-PARTY.txt` 并放入 `META-INF`?
解读
在国内企业级交付与开源合规审计场景中,“第三方依赖清单”是法务、安全、运维三方共同关注的硬指标。面试官抛出此题,意在验证候选人是否真正落地过“构建即合规”的 DevSecOps 流程:既要能一键生成所有依赖的坐标、许可证、版权信息,又要自动归档到最终 JAR 的 META-INF 目录,避免人工拷贝带来的版本漂移。回答时务必把“扫描-聚合-格式化-打包”四步拆清,并给出 CI 失败策略,才能体现工程化思维。
知识点
- Maven 许可证插件:
org.codehaus.mojo:license-maven-plugin:2.0.0是事实标准,支持国内镜像加速,可一次性收集groupId:artifactId:version与许可证名称。 - 聚合范围:
aggregate=true解决多模块项目重复生成问题;includeTransitive=true保证传递依赖不遗漏,防止“少扫”带来的合规风险。 - 输出模板:内置
third-party-file.ftl可自定义为中文表格,满足国内审计要求;通过fileTemplate参数指定即可。 - 生命周期绑定:把目标
add-third-party挂在generate-resources阶段,可确保在repackage之前完成,Spring Boot 打包不会覆盖。 - JAR 内路径:利用
maven-resources-plugin把生成的THIRD-PARTY.txt从target/generated-sources/license拷贝到${project.build.outputDirectory}/META-INF,无需手动jar uf。 - CI 门禁:在 GitLab-CI 或 Jenkins 中增加
-Dlicense.failOnMissing=true -Dlicense.failOnNotUplifted=true,出现 GPL 类高风险许可证即中断构建,实现“左移”治理。
答案
- 在父
pom.xml的<pluginManagement>中统一定义版本,确保多模块单版本管理:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<version>2.0.0</version>
<configuration>
<!-- 生成文件名称 -->
<thirdPartyFilename>THIRD-PARTY.txt</thirdPartyFilename>
<!-- 包含传递依赖 -->
<includeTransitiveDependencies>true</includeTransitiveDependencies>
<!-- 聚合所有子模块 -->
<aggregate>true</aggregate>
<!-- 缺失许可证时中断 -->
<failOnMissing>true</failOnMissing>
<!-- 使用中文友好模板 -->
<fileTemplate>/license/third-party-file.ftl</fileTemplate>
<!-- 输出目录 -->
<outputDirectory>${project.build.directory}/generated-sources/license</outputDirectory>
</configuration>
<executions>
<execution>
<id>generate-third-party</id>
<phase>generate-resources</phase>
<goals>
<goal>aggregate-add-third-party</goal>
</goals>
</execution>
</executions>
</plugin>
- 通过
maven-resources-plugin把清单打进 JAR 的META-INF:
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>copy-third-party</id>
<phase>process-resources</phase>
<goals><goal>copy-resources</goal></goals>
<configuration>
<outputDirectory>${project.build.outputDirectory}/META-INF</outputDirectory>
<resources>
<resource>
<directory>${project.build.directory}/generated-sources/license</directory>
<includes><include>THIRD-PARTY.txt</include></includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
- 运行
mvn clean package后,验证your-service.jar!/META-INF/THIRD-PARTY.txt存在且内容完整;在 CI 流水线追加mvn license:aggregate-add-third-party -Dlicense.failOnBlacklist=true即可强制门禁。
拓展思考
- 双清单策略:对外交付包放
THIRD-PARTY.txt,对内安全团队额外输出license.xml与dependency-check-report.html,实现**“一份构建,两份报告”**。 - 私有仓库合规兜底:当中央仓缺失许可证时,可在 Nexus 私服 的
attributes里手动补录,插件会优先读取私服元数据,避免构建中断。 - 容器镜像延续:在 Spring Boot 分层 JAR 模式下,
META-INF/THIRD-PARTY.txt会落入boot-inf/classes/META-INF,需通过 Dockerfile 的LABEL指令把该文件映射到镜像层,方便docker inspect直接查看,满足国内金融云“镜像合规扫描”要求。