如何为私有 PyPI 仓库配置认证并扫描内部包?
解读
在国内企业级 Python 交付链路里,代码与制品安全合规是红线。私有 PyPI(Nexus、Artifactory、阿里云 CodeArtifact、腾讯 CODING 制品库等)既要让 CI 顺利拉包,又要防止“投毒”与许可证污染。面试官问“配置认证并扫描内部包”,表面看是运维动作,实则考察候选人能否把“测试框架—制品仓库—安全策略”串成闭环:用 Pytest 驱动自动化测试的同时,保证依赖来源可信、漏洞可追踪、问题可阻断。回答必须体现三点:
- 认证方式符合国内常见私有仓库场景(用户名/密码、临时 Token、OIDC 动态身份);
- 扫描动作可嵌入 pytest 生命周期,用 fixture 或插件把“包扫描”变成测试用例;
- 出现高危漏洞时能中断流水线,而非“只报警不拦截”。
知识点
- pip 认证机制:index-url、extra-index-url、--trusted-host、netrc、keyring、pip.conf、PYPIRC、PIP_INDEX_URL 环境变量。
- 国内私有仓库差异:阿里云 CodeArtifact 需
aws codeartifact login生成临时 Token;JFrog Artifactory 用/artifactory/api/pypi/<repo>/simple并支持 Project-Key 隔离;腾讯 CODING 支持个人令牌+项目令牌双因子。 - 安全扫描工具:pip-audit、safety、Grype、Syft、Trivy、Snyk CLI,均可输出 JSON 或 SARIF。
- pytest 插件体系:pytest-xdist(并行)、pytest-html(报告)、pytest-timeout(超时)、自定义 fixture 与 hook(pytest_configure、pytest_sessionstart、pytest_runtestloop)。
- 失败即阻断策略:pytest.exit(msg, returncode=2) 或 raise Failed 中断整个会话;CI 侧通过
if-no-files-found: error与continue-on-error: false保证红线。 - 国内合规要求:信创环境需离线漏洞库;等保 2.0 要求“第三方组件检测”留存报告 6 个月以上;SBOM(软件物料清单)需包含哈希与许可证。
答案
分三步落地:认证 → 扫描 → 阻断,全部用 pytest 驱动,保证“测试即治理”。
第一步:在 CI 机器上配置私有仓库认证
- 针对阿里云 CodeArtifact
aws codeartifact login --tool pip --repository myrepo --domain mydomain --domain-owner 123456789012 --region cn-shanghai
该命令自动把临时 Token 写进 ~/.config/pip/pip.conf,有效期 12 小时,CI 每次 job 重新获取,避免长期 AK/SK 泄露。
- 针对 JFrog Artifactory
export ARTIFACTORY_USER=ci-user
export ARTIFACTORY_PASS=$(printenv JFROG_CI_TOKEN) # 由 OIDC 注入,有效期 30 分钟
pip config set global.extra-index-url https://${ARTIFACTORY_USER}:${ARTIFACTORY_PASS}@artifactory.company.cn/artifactory/api/pypi/pypi-local/simple
pip config set global.trusted-host artifactory.company.cn
- 针对腾讯 CODING
pip config set global.extra-index-url https://${CODING_USER}:${CODING_PERSONAL_TOKEN}@company-pypi.pkg.coding.net/pypi/pypi/simple
以上三种方式均不硬编码密码到代码库,符合国内企业内部安全基线。
第二步:在 pytest 中把“依赖扫描”变成测试用例
新建 tests/test_security.py,利用 session 级 fixture 一次性扫描当前虚拟环境所有包,并输出 SBOM 与漏洞报告。
import json, subprocess, pytest
from pathlib import Path
@pytest.fixture(scope="session")
def sbom_file(tmp_path_factory):
"""生成 CycloneDX SBOM"""
sbom = tmp_path_factory.mktemp("security") / "sbom.json"
subprocess.run(
["syft", "packages", "dir:.", "-o", "cyclonedx-json", "--file", str(sbom)],
check=True,
)
return sbom
@pytest.fixture(scope="session")
def vuln_file(sbom_file, tmp_path_factory):
"""基于 SBOM 做漏洞扫描"""
vuln = tmp_path_factory.getbasetemp() / "vuln.json"
subprocess.run(
["grype", "sbom:" + str(sbom_file), "-o", "json", "--file", str(vuln)],
check=True,
)
return vuln
def test_no_high_or_critical_vuln(vuln_file):
"""阻断性测试:发现高危或严重漏洞即失败"""
data = json.loads(vuln_file.read_text())
high = [r for r in data["matches"] if r["vulnerability"]["severity"] in ("High", "Critical")]
if high:
pkg_list = "\n".join(
f"{r['artifact']['name']} {r['artifact']['version']} -> {r['vulnerability']['id']}"
for r in high
)
pytest.fail(f"发现 {len(high)} 个高危/严重漏洞,请立即修复:\n{pkg_list}")
运行 pytest -q 即可在测试阶段完成扫描,无需额外脚本。
若需并行,可在 tox.ini 里加 deps = -rrequirements.txt 先装包,再跑 pytest,保证扫描的就是最终部署环境。
第三步:CI 侧红线配置
GitLab CI 示例:
security-test:
stage: test
image: python:3.11
variables:
PIP_INDEX_URL: "https://__token__:${CI_JOB_TOKEN}@git.company.cn/api/pypi/pypi/simple"
before_script:
- pip install -U pip pytest syft grype
script:
- pytest tests/test_security.py -v --tb=short
artifacts:
reports:
cyclonedx: sbom.json
junit: junit.xml
expire_in: 6 month
allow_failure: false # 一旦 security 测试失败,整个 pipeline 停止
GitHub Actions 同理,使用 continue-on-error: false 即可。
通过以上三步,实现“拉包有认证、扫描即测试、漏洞即失败”,既满足国内私有仓库的合规要求,又把安全能力内嵌到 pytest 框架,无需维护额外脚本。
拓展思考
- 多仓库优先级污染:当 extra-index-url 与官方 PyPI 并存时,pip 默认按“先找到先安装”顺序解析,可能被同名包“劫持”。可在 pip.conf 里增加
index-strategy = unsafe-best-match并配合--no-deps手动解析,或在 CI 中完全屏蔽官方源,只允许私有仓库。 - 许可证合规扫描:除了漏洞,还需检查 GPL 污染。可在同一 pytest session 里再调
license-checker-rse生成许可证报告,并增加test_no_gpl_in_dependencies用例,发现 GPL-3.0 即失败。 - 动态基线:把 SBOM 存入 Git 做快照,下次扫描用
grype --only-fixed对比旧漏洞,实现“增量漏洞”门禁,避免历史漏洞反复阻塞新需求。 - 本地开发体验:为开发者提供
make security目标,一键起虚拟环境、装包、跑 pytest security 用例,保证“本地能过的安全测试,CI 也能过”。 - 信创离线场景:在断网机房预置漏洞库(如 Trivy 的
trivy-offline.db),通过内网 Nexus 代理,pytest 侧设置TRIVY_OFFLINE_SCAN=true,实现离线扫描同样能阻断。