security.yml 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. name: Security Audit
  2. on:
  3. schedule:
  4. # Run weekly on Monday at 6:00 UTC
  5. - cron: '0 6 * * 1'
  6. push:
  7. paths:
  8. - 'backend/**'
  9. - 'frontend/**'
  10. - 'spoolbuddy/**'
  11. - 'Dockerfile'
  12. - 'docker-compose*.yml'
  13. - 'requirements.txt'
  14. - 'frontend/package*.json'
  15. - '.github/workflows/security.yml'
  16. pull_request:
  17. paths:
  18. - 'backend/**'
  19. - 'frontend/**'
  20. - 'spoolbuddy/**'
  21. - 'Dockerfile'
  22. - 'docker-compose*.yml'
  23. - 'requirements.txt'
  24. - 'frontend/package*.json'
  25. - '.github/workflows/security.yml'
  26. workflow_dispatch:
  27. # Allow manual trigger
  28. env:
  29. PYTHON_VERSION: '3.11'
  30. NODE_VERSION: '22'
  31. # Default permissions for all jobs
  32. permissions:
  33. contents: read
  34. jobs:
  35. bandit:
  36. name: Python Security Analysis (Bandit)
  37. runs-on: ubuntu-latest
  38. permissions:
  39. contents: read
  40. security-events: write
  41. steps:
  42. - uses: actions/checkout@v6
  43. - name: Set up Python
  44. uses: actions/setup-python@v6
  45. with:
  46. python-version: ${{ env.PYTHON_VERSION }}
  47. - name: Install Bandit
  48. run: pip install bandit[sarif]
  49. - name: Run Bandit
  50. run: |
  51. bandit -r backend/ -f sarif -o bandit-results.sarif --severity-level medium || true
  52. - name: Upload Bandit results to GitHub Security
  53. uses: github/codeql-action/upload-sarif@v4
  54. if: always()
  55. with:
  56. sarif_file: bandit-results.sarif
  57. category: bandit
  58. trivy:
  59. name: Container Security Scan (Trivy)
  60. runs-on: ubuntu-latest
  61. permissions:
  62. contents: read
  63. security-events: write
  64. steps:
  65. - uses: actions/checkout@v6
  66. - name: Build Docker image
  67. run: docker build -t bambuddy:security-scan .
  68. - name: Run Trivy vulnerability scanner
  69. uses: aquasecurity/trivy-action@v0.35.0
  70. with:
  71. image-ref: 'bambuddy:security-scan'
  72. format: 'sarif'
  73. output: 'trivy-results.sarif'
  74. severity: 'CRITICAL,HIGH,MEDIUM'
  75. version: 'v0.69.1'
  76. - name: Upload Trivy results to GitHub Security
  77. uses: github/codeql-action/upload-sarif@v4
  78. if: always() && hashFiles('trivy-results.sarif') != ''
  79. with:
  80. sarif_file: trivy-results.sarif
  81. category: trivy
  82. - name: Run Trivy for Dockerfile/IaC
  83. uses: aquasecurity/trivy-action@v0.35.0
  84. with:
  85. scan-type: 'config'
  86. scan-ref: '.'
  87. format: 'sarif'
  88. output: 'trivy-config-results.sarif'
  89. severity: 'CRITICAL,HIGH,MEDIUM'
  90. version: 'v0.69.1'
  91. - name: Upload Trivy config results
  92. uses: github/codeql-action/upload-sarif@v4
  93. if: always() && hashFiles('trivy-config-results.sarif') != ''
  94. with:
  95. sarif_file: trivy-config-results.sarif
  96. category: trivy-config
  97. backend-audit:
  98. name: Backend Security Audit
  99. runs-on: ubuntu-latest
  100. permissions:
  101. contents: read
  102. issues: write
  103. steps:
  104. - uses: actions/checkout@v6
  105. - name: Set up Python
  106. uses: actions/setup-python@v6
  107. with:
  108. python-version: ${{ env.PYTHON_VERSION }}
  109. - name: Install dependencies
  110. run: |
  111. # Upgrade setuptools too: the runner's Python toolcache ships an old
  112. # setuptools that trips pip-audit (PYSEC-2026-3447, fixed in 83.0.0).
  113. # A fix exists, so we upgrade rather than --ignore-vuln.
  114. python -m pip install --upgrade pip setuptools
  115. pip install -r requirements.txt
  116. pip install pip-audit
  117. - name: Run pip-audit
  118. id: pip-audit
  119. run: |
  120. # CVE-2025-45768 (PYSEC-2025-183 / GHSA-65pc-fj4g-8rjx): disputed by PyJWT maintainers.
  121. # Advisory says "key length is chosen by the application that uses the library" — no
  122. # PyJWT fix exists or will exist. Bambuddy is safe: backend/app/core/auth.py:184 uses
  123. # secrets.token_urlsafe(64) (~86 chars of entropy) for auto-generated secrets and
  124. # rejects file-loaded secrets shorter than 32 chars at :177. Keep ignored permanently.
  125. pip-audit --desc on --format json --output pip-audit-results.json \
  126. --ignore-vuln CVE-2025-45768 \
  127. || echo "vulnerabilities_found=true" >> $GITHUB_OUTPUT
  128. pip-audit --desc on \
  129. --ignore-vuln CVE-2025-45768 \
  130. || true
  131. - name: Upload audit results
  132. if: always()
  133. uses: actions/upload-artifact@v7
  134. with:
  135. name: pip-audit-results
  136. path: pip-audit-results.json
  137. retention-days: 30
  138. - name: Create or close pip security issue
  139. if: always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
  140. uses: actions/github-script@v9
  141. with:
  142. script: |
  143. const fs = require('fs');
  144. // Check for existing open issue
  145. const existingIssues = await github.rest.issues.listForRepo({
  146. owner: context.repo.owner,
  147. repo: context.repo.repo,
  148. state: 'open',
  149. labels: 'security,automated'
  150. });
  151. const existingIssue = existingIssues.data.find(i => i.title.startsWith('Security Alert:') && i.title.includes('Python'));
  152. // If no vulnerabilities found, auto-close any stale issue
  153. if ('${{ steps.pip-audit.outputs.vulnerabilities_found }}' !== 'true') {
  154. if (existingIssue) {
  155. await github.rest.issues.createComment({
  156. owner: context.repo.owner,
  157. repo: context.repo.repo,
  158. issue_number: existingIssue.number,
  159. body: 'All Python vulnerabilities have been resolved. Closing automatically.'
  160. });
  161. await github.rest.issues.update({
  162. owner: context.repo.owner,
  163. repo: context.repo.repo,
  164. issue_number: existingIssue.number,
  165. state: 'closed'
  166. });
  167. console.log(`Auto-closed resolved issue #${existingIssue.number}`);
  168. }
  169. return;
  170. }
  171. let results;
  172. try {
  173. results = JSON.parse(fs.readFileSync('pip-audit-results.json', 'utf8'));
  174. } catch {
  175. console.log('Could not read audit results');
  176. return;
  177. }
  178. // Build vulnerability table
  179. let table = '| Package | Version | Vulnerability | Fix Version |\n';
  180. table += '|---------|---------|---------------|-------------|\n';
  181. for (const vuln of results.dependencies || []) {
  182. for (const v of vuln.vulns || []) {
  183. table += `| ${vuln.name} | ${vuln.version} | ${v.id} | ${v.fix_versions?.join(', ') || 'N/A'} |\n`;
  184. }
  185. }
  186. const vulnCount = results.dependencies?.reduce((acc, d) => acc + (d.vulns?.length || 0), 0) || 0;
  187. if (vulnCount === 0) {
  188. console.log('No vulnerabilities to report');
  189. if (existingIssue) {
  190. await github.rest.issues.createComment({
  191. owner: context.repo.owner,
  192. repo: context.repo.repo,
  193. issue_number: existingIssue.number,
  194. body: 'All Python vulnerabilities have been resolved. Closing automatically.'
  195. });
  196. await github.rest.issues.update({
  197. owner: context.repo.owner,
  198. repo: context.repo.repo,
  199. issue_number: existingIssue.number,
  200. state: 'closed'
  201. });
  202. console.log(`Auto-closed resolved issue #${existingIssue.number}`);
  203. }
  204. return;
  205. }
  206. const title = `Security Alert: ${vulnCount} Python vulnerabilities found`;
  207. const body = `## Automated Security Audit Results
  208. The weekly security audit found vulnerabilities in Python dependencies.
  209. ${table}
  210. ### Recommended Actions
  211. 1. Review each vulnerability
  212. 2. Update affected packages: \`pip install --upgrade <package>\`
  213. 3. Run \`pip-audit\` locally to verify fixes
  214. ---
  215. *This issue was automatically created by the security audit workflow.*`;
  216. if (existingIssue) {
  217. await github.rest.issues.update({
  218. owner: context.repo.owner,
  219. repo: context.repo.repo,
  220. issue_number: existingIssue.number,
  221. body: body
  222. });
  223. console.log(`Updated existing issue #${existingIssue.number}`);
  224. } else {
  225. await github.rest.issues.create({
  226. owner: context.repo.owner,
  227. repo: context.repo.repo,
  228. title: title,
  229. body: body,
  230. labels: ['security', 'automated', 'dependencies']
  231. });
  232. console.log('Created new security issue');
  233. }
  234. frontend-audit:
  235. name: Frontend Security Audit
  236. runs-on: ubuntu-latest
  237. permissions:
  238. contents: read
  239. issues: write
  240. steps:
  241. - uses: actions/checkout@v6
  242. - name: Set up Node.js
  243. uses: actions/setup-node@v6
  244. with:
  245. node-version: ${{ env.NODE_VERSION }}
  246. cache: 'npm'
  247. cache-dependency-path: frontend/package-lock.json
  248. - name: Install dependencies
  249. working-directory: frontend
  250. run: npm ci
  251. - name: Run npm audit
  252. id: npm-audit
  253. working-directory: frontend
  254. run: |
  255. npm audit --omit=dev --json > npm-audit-raw.json 2>/dev/null || true
  256. # Filter audit results to only include actual project dependencies.
  257. # npm 10.x audit/ls reports vulns in its own bundled deps (npm, tar, minimatch)
  258. # so we parse package-lock.json directly to get the real prod dep list.
  259. node -e "
  260. const fs = require('fs');
  261. const raw = fs.readFileSync('npm-audit-raw.json', 'utf8');
  262. let results;
  263. try { results = JSON.parse(raw); } catch { results = { vulnerabilities: {} }; }
  264. const lock = JSON.parse(fs.readFileSync('package-lock.json', 'utf8'));
  265. const prodDeps = new Set();
  266. for (const [path, info] of Object.entries(lock.packages || {})) {
  267. if (path && !info.dev && !info.devOptional) {
  268. prodDeps.add(path.split('node_modules/').pop());
  269. }
  270. }
  271. const vulns = results.vulnerabilities || {};
  272. // Documented advisory exceptions (keyed by GHSA id) - see ci.yml for the
  273. // full rationale and the matching hard gate. GHSA-qwww-vcr4-c8h2: React
  274. // Router RSC-mode CSRF, not reachable from Bambuddy's BrowserRouter SPA
  275. // (@react-router/server not installed); react-router/-dom pinned to 7.18.1
  276. // (the most-patched 7.x), no non-major fix exists. Auto-surfaces again if a
  277. // non-major fix ships.
  278. const ALLOWLIST = new Set(['GHSA-qwww-vcr4-c8h2']);
  279. function advisoryIds(name, seen) {
  280. seen = seen || new Set();
  281. if (seen.has(name)) return new Set();
  282. seen.add(name);
  283. const ids = new Set();
  284. for (const item of (vulns[name] || {}).via || []) {
  285. if (item && typeof item === 'object') {
  286. const url = item.url || '';
  287. if (url.includes('/advisories/')) ids.add(url.split('/').pop());
  288. } else if (typeof item === 'string') {
  289. for (const id of advisoryIds(item, seen)) ids.add(id);
  290. }
  291. }
  292. return ids;
  293. }
  294. function fixIsMajor(info) {
  295. const fa = info.fixAvailable;
  296. return fa && typeof fa === 'object' && fa.isSemVerMajor;
  297. }
  298. function exempt(name, info) {
  299. const ids = advisoryIds(name);
  300. return ids.size > 0 && [...ids].every(id => ALLOWLIST.has(id)) && fixIsMajor(info);
  301. }
  302. const filtered = {};
  303. const flagged = {};
  304. for (const [name, info] of Object.entries(vulns)) {
  305. if (!prodDeps.has(name)) continue;
  306. filtered[name] = info;
  307. if (!exempt(name, info)) flagged[name] = info;
  308. }
  309. results.vulnerabilities = filtered;
  310. fs.writeFileSync('npm-audit-results.json', JSON.stringify(results, null, 2));
  311. const count = Object.keys(flagged).length;
  312. console.log(count > 0
  313. ? count + ' production vulnerabilities found'
  314. : 'No production vulnerabilities (filtered ' + Object.keys(vulns).length + ' npm-internal entries)');
  315. if (count > 0) process.exit(1);
  316. " || echo "vulnerabilities_found=true" >> $GITHUB_OUTPUT
  317. npm audit --omit=dev --audit-level=high || true
  318. - name: Upload audit results
  319. if: always()
  320. uses: actions/upload-artifact@v7
  321. with:
  322. name: npm-audit-results
  323. path: frontend/npm-audit-results.json
  324. retention-days: 30
  325. - name: Create or close npm security issue
  326. if: always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
  327. uses: actions/github-script@v9
  328. with:
  329. script: |
  330. const fs = require('fs');
  331. // Check for existing open issue
  332. const existingIssues = await github.rest.issues.listForRepo({
  333. owner: context.repo.owner,
  334. repo: context.repo.repo,
  335. state: 'open',
  336. labels: 'security,automated'
  337. });
  338. const existingIssue = existingIssues.data.find(i => i.title.startsWith('Security Alert:') && i.title.includes('npm'));
  339. // If filter didn't flag vulnerabilities, auto-close any stale issue
  340. if ('${{ steps.npm-audit.outputs.vulnerabilities_found }}' !== 'true') {
  341. if (existingIssue) {
  342. await github.rest.issues.createComment({
  343. owner: context.repo.owner,
  344. repo: context.repo.repo,
  345. issue_number: existingIssue.number,
  346. body: 'All npm production vulnerabilities have been resolved. Closing automatically.'
  347. });
  348. await github.rest.issues.update({
  349. owner: context.repo.owner,
  350. repo: context.repo.repo,
  351. issue_number: existingIssue.number,
  352. state: 'closed'
  353. });
  354. console.log(`Auto-closed resolved issue #${existingIssue.number}`);
  355. }
  356. return;
  357. }
  358. let results;
  359. try {
  360. results = JSON.parse(fs.readFileSync('frontend/npm-audit-results.json', 'utf8'));
  361. } catch {
  362. console.log('Could not read filtered audit results');
  363. return;
  364. }
  365. const vulns = results.vulnerabilities || {};
  366. const vulnCount = Object.keys(vulns).length;
  367. if (vulnCount === 0) {
  368. console.log('No vulnerabilities to report');
  369. if (existingIssue) {
  370. await github.rest.issues.createComment({
  371. owner: context.repo.owner,
  372. repo: context.repo.repo,
  373. issue_number: existingIssue.number,
  374. body: 'All npm production vulnerabilities have been resolved. Closing automatically.'
  375. });
  376. await github.rest.issues.update({
  377. owner: context.repo.owner,
  378. repo: context.repo.repo,
  379. issue_number: existingIssue.number,
  380. state: 'closed'
  381. });
  382. console.log(`Auto-closed resolved issue #${existingIssue.number}`);
  383. }
  384. return;
  385. }
  386. // Build vulnerability table
  387. let table = '| Package | Severity | Via | Fix |\n';
  388. table += '|---------|----------|-----|-----|\n';
  389. for (const [name, info] of Object.entries(vulns)) {
  390. const via = Array.isArray(info.via) ? info.via.map(v => typeof v === 'string' ? v : v.name).join(', ') : info.via;
  391. table += `| ${name} | ${info.severity} | ${via} | ${info.fixAvailable ? 'Yes' : 'No'} |\n`;
  392. }
  393. const title = `Security Alert: ${vulnCount} npm vulnerabilities found`;
  394. const body = `## Automated Security Audit Results
  395. The weekly security audit found vulnerabilities in npm dependencies.
  396. ${table}
  397. ### Recommended Actions
  398. 1. Review each vulnerability: \`npm audit\`
  399. 2. Auto-fix if possible: \`npm audit fix\`
  400. 3. Manual fix for breaking changes: \`npm audit fix --force\` (review changes!)
  401. ---
  402. *This issue was automatically created by the security audit workflow.*`;
  403. if (existingIssue) {
  404. await github.rest.issues.update({
  405. owner: context.repo.owner,
  406. repo: context.repo.repo,
  407. issue_number: existingIssue.number,
  408. body: body
  409. });
  410. console.log(`Updated existing issue #${existingIssue.number}`);
  411. } else {
  412. await github.rest.issues.create({
  413. owner: context.repo.owner,
  414. repo: context.repo.repo,
  415. title: title,
  416. body: body,
  417. labels: ['security', 'automated', 'dependencies']
  418. });
  419. console.log('Created new security issue');
  420. }