ci.yml 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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.txt
  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.txt') }}
  131. restore-keys: |
  132. ${{ runner.os }}-pip-
  133. - name: Install dependencies
  134. run: |
  135. python -m pip install --upgrade pip
  136. pip install -r requirements.txt
  137. pip install -r requirements-dev.txt
  138. - name: Run tests (shard ${{ matrix.shard }}/4)
  139. timeout-minutes: 15
  140. run: |
  141. cd backend
  142. # -v dropped: 5300+ "PASSED foo::bar" lines per worker eat 30-60s
  143. # of stdout I/O time on 2-vCPU runners. --tb=short is enough.
  144. #
  145. # --splits 4 --group N slices the suite across the 4 matrix shards.
  146. # Without a durations file pytest-split balances by test COUNT, which
  147. # is not the same thing as time: measured 2026-08-31, that put 658s of
  148. # the suite's 1046s into shard 1 and 101s into shard 4 -- a 6.5x spread
  149. # that walked shard 1 into the old 10-minute timeout on a docs-only
  150. # commit. tests/.test_durations is committed so the split is balanced
  151. # by measured time instead (1.01x spread). Shard test counts are
  152. # lopsided by design once it is used: shard 4 takes thousands of fast
  153. # unit tests, shard 1 keeps the slow integration ones.
  154. #
  155. # --durations-path must be explicit: pytest-split defaults it to
  156. # $CWD/.test_durations, and this job runs from backend/ while the
  157. # Docker job below runs from the image root. Left implicit, one of
  158. # them silently finds no file and falls back to the count split.
  159. # Regenerate after adding slow tests:
  160. # cd backend && python -m pytest tests/ --store-durations \
  161. # --durations-path tests/.test_durations
  162. python -m pytest tests/ \
  163. --tb=short \
  164. --timeout=60 --timeout-method=thread \
  165. -n auto \
  166. --splits 4 --group ${{ matrix.shard }} \
  167. --durations-path tests/.test_durations
  168. # ============================================================================
  169. # Frontend Checks
  170. # ============================================================================
  171. frontend-lint:
  172. name: Frontend Lint
  173. runs-on: ubuntu-latest
  174. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  175. steps:
  176. - uses: actions/checkout@v6
  177. - name: Set up Node.js
  178. uses: actions/setup-node@v6
  179. with:
  180. node-version: ${{ env.NODE_VERSION }}
  181. cache: 'npm'
  182. cache-dependency-path: frontend/package-lock.json
  183. - name: Install dependencies
  184. working-directory: frontend
  185. run: npm ci
  186. - name: Run ESLint
  187. working-directory: frontend
  188. run: npm run lint
  189. frontend-security:
  190. name: Frontend Security
  191. runs-on: ubuntu-latest
  192. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  193. continue-on-error: true
  194. steps:
  195. - uses: actions/checkout@v6
  196. - name: Set up Node.js
  197. uses: actions/setup-node@v6
  198. with:
  199. node-version: ${{ env.NODE_VERSION }}
  200. cache: 'npm'
  201. cache-dependency-path: frontend/package-lock.json
  202. - name: Install dependencies
  203. working-directory: frontend
  204. run: npm ci
  205. - name: Run npm audit
  206. working-directory: frontend
  207. run: |
  208. # Only audit production dependencies and filter out npm-internal packages.
  209. # npm 10.x audit/ls reports vulns in its own bundled deps (npm, tar, minimatch)
  210. # so we parse package-lock.json directly to get the real prod dep list.
  211. npm audit --omit=dev --json > /tmp/audit.json 2>/dev/null || true
  212. python3 -c "
  213. import json, sys
  214. data = json.load(open('/tmp/audit.json'))
  215. lock = json.load(open('package-lock.json'))
  216. prod = set()
  217. for path, info in lock.get('packages', {}).items():
  218. if path and not info.get('dev') and not info.get('devOptional'):
  219. prod.add(path.split('node_modules/')[-1])
  220. vulns = data.get('vulnerabilities', {})
  221. # Documented advisory exceptions: high/critical findings whose only offered
  222. # 'fix' is a semver-major change and which do not apply to how Bambuddy ships.
  223. # Keyed by GHSA id. An entry only holds while the fix stays major-only (see
  224. # fix_is_major below) - once upstream backports, the gate fails until we take
  225. # the patch. That is what retired the one entry this list used to carry:
  226. # GHSA-qwww-vcr4-c8h2 (React Router RSC-mode CSRF) shipped in 7.18.2, so the
  227. # pin moved rather than the exception staying.
  228. ALLOWLIST = set()
  229. def advisory_ids(name, seen=None):
  230. seen = seen if seen is not None else set()
  231. if name in seen:
  232. return set()
  233. seen.add(name)
  234. ids = set()
  235. for item in vulns.get(name, {}).get('via', []):
  236. if isinstance(item, dict):
  237. url = item.get('url', '')
  238. if '/advisories/' in url:
  239. ids.add(url.rsplit('/', 1)[-1])
  240. elif isinstance(item, str):
  241. ids |= advisory_ids(item, seen)
  242. return ids
  243. def fix_is_major(v):
  244. fa = v.get('fixAvailable')
  245. return isinstance(fa, dict) and fa.get('isSemVerMajor')
  246. def exempt(name, v):
  247. ids = advisory_ids(name)
  248. return bool(ids) and ids <= ALLOWLIST and fix_is_major(v)
  249. fixable = {n: v for n, v in vulns.items()
  250. if n in prod and v.get('severity') in ('high', 'critical')
  251. and v.get('fixAvailable') and not exempt(n, v)}
  252. skipped = len(vulns) - len({n: v for n, v in vulns.items() if n in prod})
  253. if fixable:
  254. for name, v in fixable.items():
  255. print(f'FIXABLE {v[\"severity\"].upper()}: {name}')
  256. sys.exit(1)
  257. total = sum(1 for n, v in vulns.items() if n in prod and v.get('severity') in ('high', 'critical'))
  258. exempted = sorted(n for n, v in vulns.items() if n in prod and exempt(n, v))
  259. print(f'npm audit: {total} high/critical (0 fixable), {len(vulns)} total ({skipped} npm-internal filtered)')
  260. if exempted:
  261. print('exempted (documented, unreachable): ' + ', '.join(exempted))
  262. "
  263. frontend-typecheck:
  264. name: Frontend Type Check
  265. runs-on: ubuntu-latest
  266. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  267. steps:
  268. - uses: actions/checkout@v6
  269. - name: Set up Node.js
  270. uses: actions/setup-node@v6
  271. with:
  272. node-version: ${{ env.NODE_VERSION }}
  273. cache: 'npm'
  274. cache-dependency-path: frontend/package-lock.json
  275. - name: Install dependencies
  276. working-directory: frontend
  277. run: npm ci
  278. # `tsc -b`, not `tsc --noEmit`: the root tsconfig only holds project
  279. # references, so plain `tsc` checks zero files. Kept out of `npm run
  280. # build` because every installer runs that on the user's machine, and
  281. # the type check alone needs ~1 GB of Node heap (#3181).
  282. - name: Run TypeScript check
  283. working-directory: frontend
  284. run: npm run typecheck
  285. frontend-tests:
  286. name: Frontend Tests
  287. runs-on: ubuntu-latest
  288. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  289. needs: [frontend-lint, frontend-typecheck]
  290. steps:
  291. - uses: actions/checkout@v6
  292. - name: Set up Node.js
  293. uses: actions/setup-node@v6
  294. with:
  295. node-version: ${{ env.NODE_VERSION }}
  296. cache: 'npm'
  297. cache-dependency-path: frontend/package-lock.json
  298. - name: Install dependencies
  299. working-directory: frontend
  300. run: npm ci
  301. - name: Run tests
  302. timeout-minutes: 10
  303. working-directory: frontend
  304. run: npm run test:run
  305. frontend-build:
  306. name: Frontend Build
  307. runs-on: ubuntu-latest
  308. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  309. needs: [frontend-tests]
  310. steps:
  311. - uses: actions/checkout@v6
  312. - name: Set up Node.js
  313. uses: actions/setup-node@v6
  314. with:
  315. node-version: ${{ env.NODE_VERSION }}
  316. cache: 'npm'
  317. cache-dependency-path: frontend/package-lock.json
  318. - name: Install dependencies
  319. working-directory: frontend
  320. run: npm ci
  321. - name: Build
  322. working-directory: frontend
  323. run: npm run build
  324. # ============================================================================
  325. # Docker Tests (matches test_docker.sh)
  326. # ============================================================================
  327. # Run the FULL backend test suite inside the test image, sharded 4-way
  328. # so wall-clock matches the host-side backend-tests job. Catches the
  329. # rare-but-real cases where a test passes on the GHA host but fails in
  330. # the python:3.13-slim test image (system-binary version differences,
  331. # locale/timezone, container vs host user, cwd assumptions). Without
  332. # sharding this was a 5-10 min single-runner job; with sharding it's
  333. # ~120-150s per shard running in parallel, gated by max(shard).
  334. docker-backend-tests:
  335. name: Docker Backend Tests (shard ${{ matrix.shard }}/4)
  336. runs-on: ubuntu-latest
  337. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  338. timeout-minutes: 15
  339. strategy:
  340. fail-fast: false
  341. matrix:
  342. shard: [1, 2, 3, 4]
  343. steps:
  344. - uses: actions/checkout@v6
  345. - name: Set up Docker Buildx
  346. uses: docker/setup-buildx-action@v4
  347. # Build the backend-test image with GHA BuildKit cache backend so
  348. # the pip-install layer is shared across the 4 matrix shards AND
  349. # across CI runs. First run on a given requirements.txt is cold
  350. # (~60-90s); subsequent runs are ~5-10s.
  351. - name: Build backend test image (cached)
  352. uses: docker/build-push-action@v7
  353. with:
  354. context: .
  355. file: Dockerfile.test
  356. target: backend-test
  357. load: true
  358. tags: bambuddy-backend-test:latest
  359. cache-from: type=gha,scope=backend-test
  360. cache-to: type=gha,scope=backend-test,mode=max
  361. - name: Run backend tests in Docker (shard ${{ matrix.shard }}/4)
  362. run: |
  363. docker run --rm \
  364. -e TESTING=1 \
  365. -e PYTHONUNBUFFERED=1 \
  366. bambuddy-backend-test:latest \
  367. pytest backend/tests/ \
  368. --tb=short \
  369. --timeout=60 --timeout-method=thread \
  370. -p no:cacheprovider \
  371. -n auto \
  372. --splits 4 --group ${{ matrix.shard }} \
  373. --durations-path backend/tests/.test_durations
  374. docker-test:
  375. name: Docker Build
  376. runs-on: ubuntu-latest
  377. if: github.event_name == 'push' || github.event.pull_request.user.login != github.repository_owner
  378. timeout-minutes: 20
  379. needs: [backend-tests, frontend-build]
  380. steps:
  381. - uses: actions/checkout@v6
  382. # Test 1: Docker Build
  383. - name: Build production image
  384. run: docker build -t bambuddy:test .
  385. - name: Verify backend imports
  386. run: docker run --rm bambuddy:test python -c "import backend.app.main; print('Backend imports OK')"
  387. - name: Verify static files exist
  388. run: docker run --rm bambuddy:test test -d /app/static
  389. # Test 4: Integration Tests
  390. - name: Build integration container
  391. run: docker compose -f docker-compose.test.yml build integration
  392. - name: Start integration container
  393. run: |
  394. docker compose -f docker-compose.test.yml up -d integration
  395. echo "Waiting for container to be healthy..."
  396. for i in {1..30}; do
  397. if docker compose -f docker-compose.test.yml ps integration | grep -q "healthy"; then
  398. echo "Container is healthy"
  399. break
  400. fi
  401. sleep 2
  402. done
  403. - name: Test health endpoint
  404. run: |
  405. HEALTH=$(docker compose -f docker-compose.test.yml exec -T integration curl -s http://localhost:8000/health)
  406. echo "$HEALTH"
  407. echo "$HEALTH" | grep -q "healthy"
  408. - name: Test API endpoint
  409. run: |
  410. docker compose -f docker-compose.test.yml exec -T integration curl -s http://localhost:8000/api/v1/settings
  411. - name: Test static files served
  412. run: |
  413. STATUS=$(docker compose -f docker-compose.test.yml exec -T integration curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/)
  414. echo "Static files HTTP status: $STATUS"
  415. [ "$STATUS" = "200" ]
  416. # Test 5: Integration Test Suite (pytest)
  417. - name: Build integration test runner
  418. run: docker compose -f docker-compose.test.yml build integration-test-runner
  419. - name: Run integration test suite
  420. run: docker compose -f docker-compose.test.yml run --rm integration-test-runner
  421. - name: Show logs on failure
  422. if: failure()
  423. run: docker compose -f docker-compose.test.yml logs
  424. - name: Cleanup
  425. if: always()
  426. run: docker compose -f docker-compose.test.yml down -v --remove-orphans