iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Modern Web

AI 驅動的 Web 資安新時代系列 第 16

Day16 - 程式碼安全審查:AI Agent 在 CI/CD Pipeline 裡守門

  • 分享至 

  • xImage
  •  

在現代開發流程中,CI/CD Pipeline(持續整合 / 持續部署)幾乎是標準配置。

然而,多數團隊只檢查「測試是否通過」與「功能是否正常」,卻忽略了 程式碼安全性

這意味著:

  • 一段危險的 SQL Injection 代碼,可能在無人察覺下進入生產環境。
  • 一個過時的第三方套件漏洞,可能讓整個服務曝露在風險之中。

如果我們在 Pipeline 中嵌入 AI Agent,就能讓它自動扮演「安全守門員」的角色:

  • 在程式碼合併前進行安全檢查
  • 自動分析潛在弱點
  • 給出修補建議

AI Agent 工作流程

  1. 提交程式碼 → 開發者 push 到 GitHub/GitLab
  2. CI/CD 啟動 → Pipeline 執行 server.js 模擬檢查任務
  3. AI Agent 分析agent.js 呼叫 Gemini,判斷安全性
  4. 結果回饋 → 若發現漏洞,阻擋部署並提示修補建議

模擬有漏洞的程式碼

模擬一個「有 SQL Injection 風險」的 API,作為被 AI Agent 審查的範例

const express = require("express");
const app = express();

app.get("/user", (req, res) => {
  // 這裡有 SQL Injection 風險
  const query = "SELECT * FROM users WHERE id = " + req.query.id;
  res.send("執行查詢: " + query);
});

app.listen(4000, () => {
  console.log("Vulnerable app running at http://localhost:4000");
});

server– 模擬程式碼輸入

模擬在 CI/CD pipeline 中,收集到的程式碼(或 PR 中的差異),並提供給 AI Agent 分析

  • 建立一個簡單的 API /code,回傳需要審查的程式碼。
  • 在真實 CI/CD pipeline 裡,可以改成自動抓取 PR diffgit commit 檔案
import express from "express";
import fs from "fs";

const app = express();
app.use(express.json());

// 模擬 CI/CD 收到的程式碼 (例如 PR 內的檔案)
app.get("/code", (req, res) => {
  const code = fs.readFileSync("./sample_vulnerable_code.js", "utf-8");
  res.send({ code });
});

app.listen(3000, () => {
  console.log("Server running at http://localhost:3000");
});

AI Agent 安全審查

1、從 server.js 抓取程式碼

透過 API 取得程式碼,模擬在 CI/CD pipeline 中收集到的檔案。

async function getCode() {
  const res = await fetch("http://localhost:3000/code");
  const data = await res.json();
  return data.code;
}

2、Gemini 進行安全審查

將程式碼交給 Gemini 模型,請它檢查是否存在漏洞,並提供修補建議。

async function auditCode(code) {
  const prompt = `
	你是一個程式碼安全審查 AI,請檢查以下程式碼是否存在漏洞。
	需求:
	1. 標記可能的弱點(例如 SQL Injection, XSS, 弱密碼, 過時套件)
	2. 提供修補建議
	---
	程式碼:
	${code}
	`;

  const result = await model.generateContent(prompt);
  console.log("=== AI 審查結果 ===");
  console.log(result.response.text());
}

3、主流程

串接前兩步:先抓程式碼,再交給 AI Agent 審查,最後輸出結果。

(async () => {
  const code = await getCode();
  await auditCode(code);
})();

上一篇
Day15 - AI Agent 自動生成滲透測試腳本(SQLi / XSS 範例)
系列文
AI 驅動的 Web 資安新時代16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言