ci.yml 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. name: CI
  2. on:
  3. push:
  4. branches: [main]
  5. pull_request:
  6. branches: [main]
  7. workflow_dispatch:
  8. # Run on PRs targeting main, but skip for repo owner (runs local tests)
  9. # Skip CI for PRs authored by repo owner (they run tests locally)
  10. # Uses PR author instead of triggering actor so rebasing by owner doesn't skip CI
  11. env:
  12. PYTHON_VERSION: '3.11'
  13. NODE_VERSION: '22'
  14. # Cancel in-progress runs for the same branch
  15. concurrency:
  16. group: ${{ github.workflow }}-${{ github.ref }}
  17. cancel-in-progress: true
  18. # Minimum permissions for all jobs
  19. permissions:
  20. contents: read
  21. jobs:
  22. # ============================================================================
  23. # Backend Checks
  24. # ============================================================================
  25. backend-lint:
  26. name: Backend Lint
  27. runs-on: ubuntu-latest
  28. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  29. steps:
  30. - uses: actions/checkout@v6
  31. - name: Set up Python
  32. uses: actions/setup-python@v6
  33. with:
  34. python-version: ${{ env.PYTHON_VERSION }}
  35. - name: Install ruff
  36. # Install the exact pin from requirements-dev.txt rather than the latest
  37. # release, so CI and contributors run the same linter. `pip install ruff`
  38. # silently drifted ahead of every local venv.
  39. run: pip install "$(grep -E '^ruff==' requirements-dev.txt)"
  40. - name: Run ruff check
  41. run: ruff check backend/
  42. - name: Run ruff format check
  43. run: ruff format --check backend/
  44. backend-typecheck:
  45. name: Backend Type Check
  46. runs-on: ubuntu-latest
  47. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  48. steps:
  49. - uses: actions/checkout@v6
  50. - name: Set up Python
  51. uses: actions/setup-python@v6
  52. with:
  53. python-version: ${{ env.PYTHON_VERSION }}
  54. - name: Install the pinned type-check environment
  55. # requirements-typecheck.lock, not requirements.txt: the baseline only
  56. # holds for these exact library versions (see requirements-typecheck.txt).
  57. run: pip install -r requirements-typecheck.lock
  58. - name: Check the lock covers requirements.txt
  59. # A dependency added to requirements.txt but not to the lock would show
  60. # up below as an unresolved import instead of saying what is wrong.
  61. run: |
  62. if ! out=$(pip install --dry-run -r requirements.txt 2>&1); then
  63. echo "$out"
  64. echo "::error::pip could not resolve requirements.txt against the type-check environment."
  65. exit 1
  66. fi
  67. if echo "$out" | grep '^Would install'; then
  68. echo "::error::requirements-typecheck.lock is missing packages from requirements.txt. Regenerate it as described in requirements-typecheck.txt."
  69. exit 1
  70. fi
  71. - name: Run basedpyright
  72. # Errors recorded in .basedpyright/baseline.json pass; any new one fails.
  73. # Lock mode also fails when a baselined error was fixed but the smaller
  74. # baseline was not committed.
  75. run: basedpyright --pythonpath "$(which python)" --baselinemode=lock
  76. backend-security:
  77. name: Backend Security
  78. runs-on: ubuntu-latest
  79. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  80. continue-on-error: true
  81. steps:
  82. - uses: actions/checkout@v6
  83. - name: Set up Python
  84. uses: actions/setup-python@v6
  85. with:
  86. python-version: ${{ env.PYTHON_VERSION }}
  87. - name: Install dependencies
  88. run: |
  89. # Upgrade setuptools too: the runner's Python toolcache ships an old
  90. # setuptools that trips pip-audit (PYSEC-2026-3447, fixed in 83.0.0).
  91. # A fix exists, so we upgrade rather than --ignore-vuln.
  92. python -m pip install --upgrade pip setuptools
  93. pip install -r requirements.lock
  94. pip install pip-audit
  95. - name: Run pip-audit
  96. run: |
  97. # CVE-2026-4539: low-severity ReDoS in Pygments AdlLexer (indirect dep via mkdocs-material/pytest/rich).
  98. # No fix available yet. Remove --ignore-vuln once Pygments releases a patched version.
  99. #
  100. # CVE-2025-45768 (PYSEC-2025-183 / GHSA-65pc-fj4g-8rjx): disputed by PyJWT maintainers.
  101. # Advisory says "key length is chosen by the application that uses the library" — no
  102. # PyJWT fix exists or will exist. Bambuddy is safe: backend/app/core/auth.py:184 uses
  103. # secrets.token_urlsafe(64) (~86 chars of entropy) for auto-generated secrets and
  104. # rejects file-loaded secrets shorter than 32 chars at :177. Keep ignored permanently.
  105. pip-audit --desc on \
  106. --ignore-vuln CVE-2026-4539 \
  107. --ignore-vuln CVE-2025-45768
  108. backend-tests:
  109. name: Backend Tests (shard ${{ matrix.shard }}/4)
  110. runs-on: ubuntu-latest
  111. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  112. needs: backend-lint
  113. strategy:
  114. # Don't cancel sibling shards if one fails — we want every shard's
  115. # failure list, not just the first one, so a single PR push shows
  116. # all broken tests in one go.
  117. fail-fast: false
  118. matrix:
  119. shard: [1, 2, 3, 4]
  120. steps:
  121. - uses: actions/checkout@v6
  122. - name: Set up Python
  123. uses: actions/setup-python@v6
  124. with:
  125. python-version: ${{ env.PYTHON_VERSION }}
  126. - name: Cache pip
  127. uses: actions/cache@v5
  128. with:
  129. path: ~/.cache/pip
  130. key: ${{ runner.os }}-pip-${{ hashFiles('requirements.lock', 'requirements-dev.txt') }}
  131. restore-keys: |
  132. ${{ runner.os }}-pip-
  133. - name: Install dependencies
  134. run: |
  135. python -m pip install --upgrade pip
  136. # The pinned versions that ship (Docker, installers), not whatever is newest.
  137. pip install -r requirements.lock
  138. pip install -r requirements-dev.txt
  139. - name: Run tests (shard ${{ matrix.shard }}/4)
  140. timeout-minutes: 15
  141. run: |
  142. cd backend
  143. # -v dropped: 5300+ "PASSED foo::bar" lines per worker eat 30-60s
  144. # of stdout I/O time on 2-vCPU runners. --tb=short is enough.
  145. #
  146. # --splits 4 --group N slices the suite across the 4 matrix shards.
  147. # Without a durations file pytest-split balances by test COUNT, which
  148. # is not the same thing as time: measured 2026-08-31, that put 658s of
  149. # the suite's 1046s into shard 1 and 101s into shard 4 -- a 6.5x spread
  150. # that walked shard 1 into the old 10-minute timeout on a docs-only
  151. # commit. tests/.test_durations is committed so the split is balanced
  152. # by measured time instead (1.01x spread). Shard test counts are
  153. # lopsided by design once it is used: shard 4 takes thousands of fast
  154. # unit tests, shard 1 keeps the slow integration ones.
  155. #
  156. # --durations-path must be explicit: pytest-split defaults it to
  157. # $CWD/.test_durations, and this job runs from backend/ while the
  158. # Docker job below runs from the image root. Left implicit, one of
  159. # them silently finds no file and falls back to the count split.
  160. # Regenerate after adding slow tests:
  161. # cd backend && python -m pytest tests/ --store-durations \
  162. # --durations-path tests/.test_durations
  163. python -m pytest tests/ \
  164. --tb=short \
  165. --timeout=60 --timeout-method=thread \
  166. -n auto \
  167. --splits 4 --group ${{ matrix.shard }} \
  168. --durations-path tests/.test_durations
  169. # ============================================================================
  170. # Frontend Checks
  171. # ============================================================================
  172. frontend-lint:
  173. name: Frontend Lint
  174. runs-on: ubuntu-latest
  175. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  176. steps:
  177. - uses: actions/checkout@v6
  178. - name: Set up Node.js
  179. uses: actions/setup-node@v6
  180. with:
  181. node-version: ${{ env.NODE_VERSION }}
  182. cache: 'npm'
  183. cache-dependency-path: frontend/package-lock.json
  184. - name: Install dependencies
  185. working-directory: frontend
  186. run: npm ci
  187. - name: Run ESLint
  188. working-directory: frontend
  189. run: npm run lint
  190. frontend-security:
  191. name: Frontend Security
  192. runs-on: ubuntu-latest
  193. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  194. continue-on-error: true
  195. steps:
  196. - uses: actions/checkout@v6
  197. - name: Set up Node.js
  198. uses: actions/setup-node@v6
  199. with:
  200. node-version: ${{ env.NODE_VERSION }}
  201. cache: 'npm'
  202. cache-dependency-path: frontend/package-lock.json
  203. - name: Install dependencies
  204. working-directory: frontend
  205. run: npm ci
  206. - name: Run npm audit
  207. working-directory: frontend
  208. run: |
  209. # Only audit production dependencies and filter out npm-internal packages.
  210. # npm 10.x audit/ls reports vulns in its own bundled deps (npm, tar, minimatch)
  211. # so we parse package-lock.json directly to get the real prod dep list.
  212. npm audit --omit=dev --json > /tmp/audit.json 2>/dev/null || true
  213. python3 -c "
  214. import json, sys
  215. data = json.load(open('/tmp/audit.json'))
  216. lock = json.load(open('package-lock.json'))
  217. prod = set()
  218. for path, info in lock.get('packages', {}).items():
  219. if path and not info.get('dev') and not info.get('devOptional'):
  220. prod.add(path.split('node_modules/')[-1])
  221. vulns = data.get('vulnerabilities', {})
  222. # Documented advisory exceptions: high/critical findings whose only offered
  223. # 'fix' is a semver-major change and which do not apply to how Bambuddy ships.
  224. # Keyed by GHSA id. An entry only holds while the fix stays major-only (see
  225. # fix_is_major below) - once upstream backports, the gate fails until we take
  226. # the patch. That is what retired the one entry this list used to carry:
  227. # GHSA-qwww-vcr4-c8h2 (React Router RSC-mode CSRF) shipped in 7.18.2, so the
  228. # pin moved rather than the exception staying.
  229. ALLOWLIST = set()
  230. def advisory_ids(name, seen=None):
  231. seen = seen if seen is not None else set()
  232. if name in seen:
  233. return set()
  234. seen.add(name)
  235. ids = set()
  236. for item in vulns.get(name, {}).get('via', []):
  237. if isinstance(item, dict):
  238. url = item.get('url', '')
  239. if '/advisories/' in url:
  240. ids.add(url.rsplit('/', 1)[-1])
  241. elif isinstance(item, str):
  242. ids |= advisory_ids(item, seen)
  243. return ids
  244. def fix_is_major(v):
  245. fa = v.get('fixAvailable')
  246. return isinstance(fa, dict) and fa.get('isSemVerMajor')
  247. def exempt(name, v):
  248. ids = advisory_ids(name)
  249. return bool(ids) and ids <= ALLOWLIST and fix_is_major(v)
  250. fixable = {n: v for n, v in vulns.items()
  251. if n in prod and v.get('severity') in ('high', 'critical')
  252. and v.get('fixAvailable') and not exempt(n, v)}
  253. skipped = len(vulns) - len({n: v for n, v in vulns.items() if n in prod})
  254. if fixable:
  255. for name, v in fixable.items():
  256. print(f'FIXABLE {v[\"severity\"].upper()}: {name}')
  257. sys.exit(1)
  258. total = sum(1 for n, v in vulns.items() if n in prod and v.get('severity') in ('high', 'critical'))
  259. exempted = sorted(n for n, v in vulns.items() if n in prod and exempt(n, v))
  260. print(f'npm audit: {total} high/critical (0 fixable), {len(vulns)} total ({skipped} npm-internal filtered)')
  261. if exempted:
  262. print('exempted (documented, unreachable): ' + ', '.join(exempted))
  263. "
  264. frontend-typecheck:
  265. name: Frontend Type Check
  266. runs-on: ubuntu-latest
  267. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  268. steps:
  269. - uses: actions/checkout@v6
  270. - name: Set up Node.js
  271. uses: actions/setup-node@v6
  272. with:
  273. node-version: ${{ env.NODE_VERSION }}
  274. cache: 'npm'
  275. cache-dependency-path: frontend/package-lock.json
  276. - name: Install dependencies
  277. working-directory: frontend
  278. run: npm ci
  279. # `tsc -b`, not `tsc --noEmit`: the root tsconfig only holds project
  280. # references, so plain `tsc` checks zero files. Kept out of `npm run
  281. # build` because every installer runs that on the user's machine, and
  282. # the type check alone needs ~1 GB of Node heap (#3181).
  283. - name: Run TypeScript check
  284. working-directory: frontend
  285. run: npm run typecheck
  286. frontend-tests:
  287. name: Frontend Tests
  288. runs-on: ubuntu-latest
  289. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  290. needs: [frontend-lint, frontend-typecheck]
  291. steps:
  292. - uses: actions/checkout@v6
  293. - name: Set up Node.js
  294. uses: actions/setup-node@v6
  295. with:
  296. node-version: ${{ env.NODE_VERSION }}
  297. cache: 'npm'
  298. cache-dependency-path: frontend/package-lock.json
  299. - name: Install dependencies
  300. working-directory: frontend
  301. run: npm ci
  302. - name: Run tests
  303. timeout-minutes: 10
  304. working-directory: frontend
  305. run: npm run test:run
  306. frontend-build:
  307. name: Frontend Build
  308. runs-on: ubuntu-latest
  309. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  310. needs: [frontend-tests]
  311. steps:
  312. - uses: actions/checkout@v6
  313. - name: Set up Node.js
  314. uses: actions/setup-node@v6
  315. with:
  316. node-version: ${{ env.NODE_VERSION }}
  317. cache: 'npm'
  318. cache-dependency-path: frontend/package-lock.json
  319. - name: Install dependencies
  320. working-directory: frontend
  321. run: npm ci
  322. - name: Build
  323. working-directory: frontend
  324. run: npm run build
  325. # ============================================================================
  326. # Docker Tests (matches test_docker.sh)
  327. # ============================================================================
  328. # Run the FULL backend test suite inside the test image, sharded 4-way
  329. # so wall-clock matches the host-side backend-tests job. Catches the
  330. # rare-but-real cases where a test passes on the GHA host but fails in
  331. # the python:3.13-slim test image (system-binary version differences,
  332. # locale/timezone, container vs host user, cwd assumptions). Without
  333. # sharding this was a 5-10 min single-runner job; with sharding it's
  334. # ~120-150s per shard running in parallel, gated by max(shard).
  335. docker-backend-tests:
  336. name: Docker Backend Tests (shard ${{ matrix.shard }}/4)
  337. runs-on: ubuntu-latest
  338. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  339. timeout-minutes: 15
  340. strategy:
  341. fail-fast: false
  342. matrix:
  343. shard: [1, 2, 3, 4]
  344. steps:
  345. - uses: actions/checkout@v6
  346. - name: Set up Docker Buildx
  347. uses: docker/setup-buildx-action@v4
  348. # Build the backend-test image with GHA BuildKit cache backend so
  349. # the pip-install layer is shared across the 4 matrix shards AND
  350. # across CI runs. First run on a given requirements.txt is cold
  351. # (~60-90s); subsequent runs are ~5-10s.
  352. - name: Build backend test image (cached)
  353. uses: docker/build-push-action@v7
  354. with:
  355. context: .
  356. file: Dockerfile.test
  357. target: backend-test
  358. load: true
  359. tags: bambuddy-backend-test:latest
  360. cache-from: type=gha,scope=backend-test
  361. cache-to: type=gha,scope=backend-test,mode=max
  362. - name: Run backend tests in Docker (shard ${{ matrix.shard }}/4)
  363. run: |
  364. docker run --rm \
  365. -e TESTING=1 \
  366. -e PYTHONUNBUFFERED=1 \
  367. bambuddy-backend-test:latest \
  368. pytest backend/tests/ \
  369. --tb=short \
  370. --timeout=60 --timeout-method=thread \
  371. -p no:cacheprovider \
  372. -n auto \
  373. --splits 4 --group ${{ matrix.shard }} \
  374. --durations-path backend/tests/.test_durations
  375. docker-test:
  376. name: Docker Build
  377. runs-on: ubuntu-latest
  378. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  379. timeout-minutes: 20
  380. needs: [backend-tests, frontend-build]
  381. steps:
  382. - uses: actions/checkout@v6
  383. # Test 1: Docker Build
  384. - name: Build production image
  385. run: docker build -t bambuddy:test .
  386. - name: Verify backend imports
  387. run: docker run --rm bambuddy:test python -c "import backend.app.main; print('Backend imports OK')"
  388. - name: Verify static files exist
  389. run: docker run --rm bambuddy:test test -d /app/static
  390. # Test 4: Integration Tests
  391. - name: Build integration container
  392. run: docker compose -f docker-compose.test.yml build integration
  393. - name: Start integration container
  394. run: |
  395. docker compose -f docker-compose.test.yml up -d integration
  396. echo "Waiting for container to be healthy..."
  397. for i in {1..30}; do
  398. if docker compose -f docker-compose.test.yml ps integration | grep -q "healthy"; then
  399. echo "Container is healthy"
  400. break
  401. fi
  402. sleep 2
  403. done
  404. - name: Test health endpoint
  405. run: |
  406. HEALTH=$(docker compose -f docker-compose.test.yml exec -T integration curl -s http://localhost:8000/health)
  407. echo "$HEALTH"
  408. echo "$HEALTH" | grep -q "healthy"
  409. - name: Test API endpoint
  410. run: |
  411. docker compose -f docker-compose.test.yml exec -T integration curl -s http://localhost:8000/api/v1/settings
  412. - name: Test static files served
  413. run: |
  414. STATUS=$(docker compose -f docker-compose.test.yml exec -T integration curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/)
  415. echo "Static files HTTP status: $STATUS"
  416. [ "$STATUS" = "200" ]
  417. # Test 5: Integration Test Suite (pytest)
  418. - name: Build integration test runner
  419. run: docker compose -f docker-compose.test.yml build integration-test-runner
  420. - name: Run integration test suite
  421. run: docker compose -f docker-compose.test.yml run --rm integration-test-runner
  422. - name: Show logs on failure
  423. if: failure()
  424. run: docker compose -f docker-compose.test.yml logs
  425. - name: Cleanup
  426. if: always()
  427. run: docker compose -f docker-compose.test.yml down -v --remove-orphans