🔒scanning-with-aws-security-agent
- ソース
- GitHub で見る ↗
説明
AWS Security Agent スキャンをワークスペース上で実行します。ソースコードを AWS にアップロードし、マネージド型の Security Agent サービスでスキャンを行い、コードの場所と修正方法を含む、検証済みの優先度付き検出結果を返します。 次のような場合に使用: ユーザーがコードのスキャン、脆弱性の検出、セキュリティスキャンやレビューの実行、セキュリティ問題の確認、スキャンステータスの確認、検出結果の表示、最近のスキャン一覧の取得、またはスキャンの停止を求めているとき。
原文を表示
Run an AWS Security Agent scan on the workspace — uploads the source to AWS, scans it with the managed Security Agent service, and returns ranked, verified findings with code locations and remediations. Use when the user asks to scan code, find vulnerabilities, run a security scan or review, check security issues, check scan status, show findings, list recent scans, or stop a scan.
ユースケース
- ✓コードの脆弱性を検出したいとき
- ✓セキュリティスキャンを実行するとき
- ✓セキュリティ問題を確認するとき
- ✓検出結果を確認したいとき
- ✓スキャンステータスを確認するとき
本文(日本語訳)
AWS Security Agent — コードスキャン
このスキルはリポジトリ全体のスキャンを処理します。
セットアップ(agent space・ロール・バケット)は setup-security-agent スキルが担当します。
.security-agent/config.json が存在しない場合、スキャンワークフローは事前にインラインでセットアップを自動実行します。
アクションマッピング
| ユーザーの意図 | ワークフロー |
|---|---|
| 直接スキャンをリクエスト(「コードをスキャンして」「脆弱性を探して」) | フルスキャン |
| スキャン状況の確認(「スキャンどうなってる」「進捗は」) | Statusワークフロー |
| 結果の確認(「何が見つかった」「結果を見せて」) | Findingsワークフロー |
| スキャン一覧(「最近のスキャン」「スキャン履歴を見せて」) | .security-agent/scans.json を読み込む |
| スキャンの停止 | aws securityagent stop-code-review-job |
積極的な提案に関するルール
- 実行前に必ずユーザーに確認する — スキャンを自動起動しない
- 提案は1行で簡潔に — 長々とした説明はしない
- ユーザーが断った場合、同一セッション内で再度提案しない
ローカル状態
agent_space_id と region を取得するため .security-agent/config.json を読み込みます。
config.json が存在しない場合は、1行でユーザーに伝えます —
「このワークスペースで初回スキャンを実施します — まずセットアップを実行します。」
— その後、継続する前に setup-security-agent ワークフローをインラインで実行します(そのスキルの SKILL.md に記載のステップを参照)。
初回スキャンは「そのまま動く」ように設計されています。
スキャン履歴は .security-agent/scans.json で管理します(最新50件を保持)。
ワークスペースごとの CodeReview ID は config.json → code_reviews[<abs_path>] に保存され、
以降のスキャンでは同じ CodeReview を再利用します。
必要な値の解決方法
以下の CLI 例はプレースホルダーを使用しています。 スキャン開始時に毎回これらの値を解決してください:
| プレースホルダー | 解決方法 |
|---|---|
<id>(agent space) |
config.agent_space_id |
<region> |
config.region(デフォルト: us-east-1) |
<account> |
aws sts get-caller-identity --query Account --output text(同一ターン内でキャッシュする) |
<role-arn> |
arn:aws:iam::<account>:role/SecurityAgentScanRole |
<bucket> |
security-agent-scans-<account>-<region> |
<cr-id> |
config.json → code_reviews[<abs_path>] の code_review_id |
<job_id> |
start-code-review-job が返す codeReviewJobId |
<WORKSPACE_ID> |
printf '%s' "$(pwd)" | md5sum | cut -c1-12 |
これらの値は config に保存するのではなく都度導出することで、実態との乖離が生じないようにしています。
スキャン前チェック
-
config.jsonを読み込む。 存在しない場合 → まずsetup-security-agentワークフローをインラインで実行してから続行する。 -
agent space がまだ存在するか確認する:
aws securityagent batch-get-agent-spaces --agent-space-ids <id>レスポンスで存在しないことが示された場合、
config.jsonからagent_space_idを削除し、setup-security-agentを再実行する。 -
アカウント・ロール ARN・バケット名を解決する(上記の表を参照)。
-
ワークスペース ID を生成する:
WORKSPACE_ID=$(printf '%s' "$(pwd)" | md5sum | cut -c1-12)
ワークフロー: フルスキャン(所要時間 約45分)
変更されたコードのみをスキャンする場合は、代わりに diff-scanning-with-aws-security-agent スキルを使用してください。
脅威モデリング仕様については、threat-modeling-with-aws-security-agent を使用してください。
-
上記のスキャン前チェックを実行する。
-
ワークスペースを ZIP 圧縮する。 一般的なビルド/キャッシュディレクトリを除外し、
.gitignoreを遵守する。ZIP が 2 GB を超えた場合は中止する。cd <absolute-workspace-path> zip -r /tmp/source.zip . \ -x ".git/*" \ -x ".security-agent/*" \ -x "node_modules/*" \ -x "__pycache__/*" \ -x ".venv/*" -x "venv/*" \ -x "dist/*" -x "build/*" -x "target/*" \ -x ".mypy_cache/*" -x ".pytest_cache/*" -x ".tox/*" \ -x ".next/*" -x "cdk.out/*" \ -x ".DS_Store" -x "Thumbs.db" \ -x "*.pyc" -x "*.pyo" ZIP_BYTES=$(stat -f%z /tmp/source.zip 2>/dev/null || stat -c%s /tmp/source.zip) if [ "$ZIP_BYTES" -gt 2147483648 ]; then echo "Zip too large (>2GB)"; exit 1; fi -
ワークスペースごとの固定キーに アップロードする(以前のアップロードを上書き):
aws s3 cp /tmp/source.zip s3://<bucket>/security-scans/source/<WORKSPACE_ID>/source.zip -
ワークスペースごとの CodeReview を取得または作成する。
config.json → code_reviews[<abs_path>]を参照する。-
存在する場合は、その
code_review_idを使用する。 -
存在しない場合は新規作成する:
aws securityagent create-code-review --agent-space-id <id> --title <title> \ --service-role <role-arn> \ --assets sourceCode=[{s3Location=s3://<bucket>/security-scans/source/<WORKSPACE_ID>/source.zip}]codeReviewIdを取得し、config.json → code_reviews[<abs_path>]に保存する。 -
タイトルのデフォルト値:
pre-cr-<git-branch>(git rev-parse --abbrev-ref HEADを使用)。スペースはハイフンに置換する。
-
-
ジョブを開始する:
aws securityagent start-code-review-job --agent-space-id <id> --code-review-id <cr-id>- レスポンスが
ResourceNotFoundExceptionの場合: CodeReview が外部で削除されています。再作成(ステップ 4)してリトライする。
- レスポンスが
-
codeReviewJobIdを取得する。scan-<8桁の16進数>形式でローカルscan_idを生成する。scans.jsonに追記する:{ "scan_id": "scan-...", "code_review_id": "cr-...", "job_id": "cj-...", "agent_space_id": "as-...", "scan_type": "FULL", "title": "pre-cr-main", "path": "/abs/path", "started_at": "2026-06-01T20:00:00Z", "status": "IN_PROGRESS" } -
ユーザーに伝える: 「フルスキャンを開始しました(scan_id: {id})。所要時間は約45分です。5分ごとに確認します — 確認を止める場合は「ポーリングを停止」とお伝えください。」
-
sleep 300を挟みながら ポーリングループ を実行する。
ポーリングループ
スキャン開始後:
-
sleep 300(5分)。これより速くポーリングしない。 -
ステータスを取得する:
aws securityagent batch-get-code-review-jobs --agent-space-id <id> --code-review-job-ids <job_id> -
statusを直前のステータスと比較する。ステータスが変化したとき(例:IN_PROGRESS→COMPLETED)、または終端状態(COMPLETED・FAILED・STOPPED)のときのみユーザーに通知する。 -
「まだ進行中です」を何度も報告しない — それはノイズになる。
-
ユーザーが「ポーリングを停止」または「後で確認する」と言った場合 → ループを停止し、「『スキャン状況』または『結果を表示』でいつでも確認できます。」と伝える。
-
COMPLETEDの場合 → Findings ワークフローを実行する。 -
FAILEDの場合 → ジョブのエラー情報(statusReasonがあれば取得)を取得し、ユーザーに伝え、.security-agent/findings-{scan_id}.mdに簡潔な失敗メモを書き込む。
ワークフロー: 状況確認(アドホック)
ユーザーが「スキャン状況」/「スキャンどうなってる」と言った場合:
- ユーザーが
scan_idを指定した場合はそれを使用する。指定がない場合はscans.jsonの最新エントリを使用する。 batch-get-code-review-jobsを1回呼び出す。scans.jsonのステータスフィールドを更新する。- ステータス・経過時間・現在のステップ(あれば)を報告する。
ワークフロー: Findings(検出結果)
スキャン完了後(またはユーザーのリクエスト時):
1. Findings を取得する(ページネーション対応)
aws securityagent list-findings --agent-space-id <id> --code-review-job-id <job-id>
nextToken が返された場合は、--next-token <token> を付けて全件取得するまで繰り返す。
2. 詳細情報で補完する
aws securityagent batch-get-findings --agent-space-id <id> --finding-ids <id1> <id2> ...
3. フィルタリング(オプション)
ユーザーが最低重大度を指定した場合(例: 「HighとCriticalだけ」)、その条件でフィルタリングする:
- 重大度の順序: CRITICAL > HIGH > MEDIUM > LOW > INFORMATIONAL
4. チャット上での簡潔なサマリー
重大度ごとにグループ化する。各項目にはファイルパスと行番号を記載する:
🟣 CRITICAL: {name}
File: {filePath}:{lineStart}
{description}
🔴 HIGH: {name}
File: {filePath}:{lineStart}
{description}
🟡 MEDIUM: {name}
File: {filePath}:{lineStart}
{description}
🟢 LOW: {name}
File: {filePath}:{lineStart}
{description}
5. 詳細レポートファイルの出力
.security-agent/findings-{scan_id}.md に書き込む。
返されたすべてのフィールド(findingId・name・description・riskLevel・riskType・confidence・status・filePath/lineStart/lineEnd を含む codeLocations・remediationCode(存在する場合)) を含める。
# セキュリティスキャンレポート — {scan_id}
**スキャン種別**: FULL
**タイトル**: {title}
**開始日時**: {started_at}
**検出件数合計**: {count}
## サマリー
| 重大度 | 件数 |
|--------|------|
| CRITICAL | N |
| HIGH | N |
| MEDIUM | N |
| LOW | N |
## Findings(検出結果)
### 🟣 CRITICAL: {name}
- **ID**: {findingId}
- **リスク種別**: {riskType}
- **信頼度**: {confidence}
- **ステータス**: {status}
- **場所**: `{filePath}:{lineStart}-{lineEnd}`
**説明**: {description}
**修正方法**:
{remediationCode または description に記載の修正ガイダンス}
(全 finding について繰り返す)
ユーザーに伝える: 「詳細は .security-agent/findings-{scan_id}.md に出力しました。」
6. フォローアップ
次の質問をする:
- 「CriticalとHighの検出結果から優先的に対応しますか?」
- 「いずれかの検出結果についてさらに詳しく説明しましょうか?」
- 「これらの問題を修正しましょうか?」
修正する場合: finding の description とコードの場所を読み取り、Edit ツールを使用して修正を合成・適用する。
ワークフロー: スキャンの停止
原文(English)を表示
AWS Security Agent — Code Scans
This skill handles full repository scans. Setup (agent space, role, bucket) is handled by the setup-security-agent skill — if .security-agent/config.json is missing, the scan workflow auto-runs setup inline first.
Action mapping
| User intent | Workflow |
|---|---|
| Direct scan request ("scan my code", "find vulnerabilities") | Full Scan |
| Scan status check ("how's the scan", "progress") | Status workflow |
| View findings ("what did it find", "show results") | Findings workflow |
| List scans ("recent scans", "show my scans") | Read .security-agent/scans.json |
| Stop a scan | aws securityagent stop-code-review-job |
Rules for proactive suggestions
- Always ask before running — never auto-trigger scans
- Single-line suggestions, not multi-paragraph pitches
- If the user declines, do not bring it up again in the same session
Local state
Read .security-agent/config.json for agent_space_id and region. If config.json is missing, tell the user one line — "First scan in this workspace — running setup first." — and run the setup-security-agent workflow inline (steps from that skill's SKILL.md) before continuing. First-time scans should "just work."
Track scans in .security-agent/scans.json (keep last 50 entries). The per-workspace CodeReview ID is stored in config.json → code_reviews[<abs_path>] so subsequent scans reuse the same CodeReview.
Resolving the values you need
The CLI examples below use placeholders. Resolve them at the start of every scan:
| Placeholder | How to resolve |
|---|---|
<id> (agent space) |
config.agent_space_id |
<region> |
config.region (default us-east-1) |
<account> |
aws sts get-caller-identity --query Account --output text (cache for the rest of the turn) |
<role-arn> |
arn:aws:iam::<account>:role/SecurityAgentScanRole |
<bucket> |
security-agent-scans-<account>-<region> |
<cr-id> |
code_review_id from config.json → code_reviews[<abs_path>] |
<job_id> |
codeReviewJobId returned by start-code-review-job |
<WORKSPACE_ID> |
printf '%s' "$(pwd)" | md5sum | cut -c1-12 |
These are derived rather than stored in config so they can never drift out of sync with reality.
Pre-scan checks
-
Read
config.json. If missing → run thesetup-security-agentworkflow inline first, then continue. -
Verify agent space still exists:
aws securityagent batch-get-agent-spaces --agent-space-ids <id>If response shows it doesn't exist, clear
agent_space_idfromconfig.jsonand runsetup-security-agentagain. -
Resolve account, role ARN, and bucket name from the table above.
-
Generate workspace ID:
WORKSPACE_ID=$(printf '%s' "$(pwd)" | md5sum | cut -c1-12)
Workflow: Full Scan (~45 min)
For scanning only changed code, use the diff-scanning-with-aws-security-agent skill instead. For threat modeling specs, use threat-modeling-with-aws-security-agent.
-
Run pre-scan checks above.
-
Zip the workspace. Exclude common build/cache directories. Honor
.gitignore. Bail if zip > 2 GB.cd <absolute-workspace-path> zip -r /tmp/source.zip . \ -x ".git/*" \ -x ".security-agent/*" \ -x "node_modules/*" \ -x "__pycache__/*" \ -x ".venv/*" -x "venv/*" \ -x "dist/*" -x "build/*" -x "target/*" \ -x ".mypy_cache/*" -x ".pytest_cache/*" -x ".tox/*" \ -x ".next/*" -x "cdk.out/*" \ -x ".DS_Store" -x "Thumbs.db" \ -x "*.pyc" -x "*.pyo" ZIP_BYTES=$(stat -f%z /tmp/source.zip 2>/dev/null || stat -c%s /tmp/source.zip) if [ "$ZIP_BYTES" -gt 2147483648 ]; then echo "Zip too large (>2GB)"; exit 1; fi -
Upload to the per-workspace stable key (overwrites any prior upload):
aws s3 cp /tmp/source.zip s3://<bucket>/security-scans/source/<WORKSPACE_ID>/source.zip -
Get or create the per-workspace CodeReview. Look up
config.json → code_reviews[<abs_path>].-
If present, use that
code_review_id. -
If absent, create:
aws securityagent create-code-review --agent-space-id <id> --title <title> \ --service-role <role-arn> \ --assets sourceCode=[{s3Location=s3://<bucket>/security-scans/source/<WORKSPACE_ID>/source.zip}]Capture
codeReviewIdand persist toconfig.json → code_reviews[<abs_path>]. -
Title default:
pre-cr-<git-branch>(usegit rev-parse --abbrev-ref HEAD). Replace any spaces with hyphens.
-
-
Start the job:
aws securityagent start-code-review-job --agent-space-id <id> --code-review-id <cr-id>- If the response is
ResourceNotFoundException: the CodeReview was deleted externally. Recreate it (step 4) and retry.
- If the response is
-
Capture
codeReviewJobId. Generate a localscan_idlikescan-<8-hex>. Append toscans.json:{ "scan_id": "scan-...", "code_review_id": "cr-...", "job_id": "cj-...", "agent_space_id": "as-...", "scan_type": "FULL", "title": "pre-cr-main", "path": "/abs/path", "started_at": "2026-06-01T20:00:00Z", "status": "IN_PROGRESS" } -
Tell user: "Full scan started (scan_id: {id}). Takes ~45 minutes. I'll check every 5 minutes — say 'stop polling' to opt out."
-
Run the Polling Loop below with
sleep 300between checks.
Polling Loop
After starting a scan:
-
sleep 300(5 minutes). Do not poll faster than this. -
Call status:
aws securityagent batch-get-code-review-jobs --agent-space-id <id> --code-review-job-ids <job_id> -
Compare
statusto last seen status. Only respond to the user when status CHANGES (e.g.,IN_PROGRESS→COMPLETED) or on terminal state (COMPLETED,FAILED,STOPPED). -
Do not report "still in progress" multiple times — that's noise.
-
If user says "stop polling" or "check later" → stop the loop and tell them: "Say 'scan status' or 'show findings' anytime."
-
On
COMPLETED→ run the Findings workflow. -
On
FAILED→ fetch the job's error info (statusReasonif present), tell the user, write a brief failure note to.security-agent/findings-{scan_id}.md.
Workflow: Status check (ad-hoc)
User says "scan status" / "how's the scan":
- If user names a
scan_id, use it. Otherwise use the most recent entry inscans.json. - Call
batch-get-code-review-jobsonce. - Update
scans.jsonstatus field. - Report: status + elapsed time + current step (if any).
Workflow: Findings
After a scan completes (or on user request):
1. Fetch findings (paginate)
aws securityagent list-findings --agent-space-id <id> --code-review-job-id <job-id>
If nextToken is returned, call again with --next-token <token> until exhausted.
2. Enrich with full details
aws securityagent batch-get-findings --agent-space-id <id> --finding-ids <id1> <id2> ...
3. Filter (optional)
If the user asked for a minimum severity (e.g., "high and above"), filter to that level:
- Severity order: CRITICAL > HIGH > MEDIUM > LOW > INFORMATIONAL.
4. Concise summary in chat
Group by severity. File path + line for each:
🟣 CRITICAL: {name}
File: {filePath}:{lineStart}
{description}
🔴 HIGH: {name}
File: {filePath}:{lineStart}
{description}
🟡 MEDIUM: {name}
File: {filePath}:{lineStart}
{description}
🟢 LOW: {name}
File: {filePath}:{lineStart}
{description}
5. Detailed report file
Write to .security-agent/findings-{scan_id}.md. Include EVERY field returned (findingId, name, description, riskLevel, riskType, confidence, status, codeLocations with filePath/lineStart/lineEnd, and remediationCode if present).
# Security Scan Report — {scan_id}
**Scan type**: FULL
**Title**: {title}
**Started**: {started_at}
**Total findings**: {count}
## Summary
| Severity | Count |
|----------|-------|
| CRITICAL | N |
| HIGH | N |
| MEDIUM | N |
| LOW | N |
## Findings
### 🟣 CRITICAL: {name}
- **ID**: {findingId}
- **Risk type**: {riskType}
- **Confidence**: {confidence}
- **Status**: {status}
- **Location**: `{filePath}:{lineStart}-{lineEnd}`
**Description**: {description}
**Remediation**:
{remediationCode or remediation guidance from description}
(repeat for every finding)
Tell user: "Full details written to .security-agent/findings-{scan_id}.md"
6. Follow-ups
Ask:
- "Would you like to focus on the critical/high findings first?"
- "Should I explain any of these in more detail?"
- "Want me to fix these issues?"
For fixes: read the finding's description and code location, then synthesize and apply the fix via the Edit tool.
Workflow: Stop a scan
User says "stop the scan":
aws securityagent stop-code-review-job --agent-space-id <id> --code-review-job-id <job_id>
Update scans.json status to STOPPED.
Workflow: List recent scans
User asks "show my recent scans" / "list scans":
Read .security-agent/scans.json. Show in a compact table:
| scan_id | type | title | status | started |
|---|---|---|---|---|
| scan-abc | FULL | pre-cr-main | COMPLETED | 2h ago |
| scan-def | FULL | pre-cr-feature-x | FAILED | 1d ago |
Rules
- Always run pre-scan checks (config exists + agent space verified) before any scan
- Scan APIs return immediately — poll status every 5 minutes
- Use the most recent scan in
scans.jsonif the user doesn't name one - Title must not contain spaces — use hyphens. Default to git branch name.
- Don't dump raw JSON — format with severity icons + file locations
- On
ResourceNotFoundExceptionfromstart-code-review-job, recreate the CodeReview and retry once
Troubleshooting
- "Not configured" /
config.jsonmissing → runsetup-security-agentskill first AccessDeniedons3 cp→ bucket not registered on agent space, or trust policy wrong. Re-run setup.ResourceNotFoundExceptionon agent space → it was deleted. Re-run setup.- Scan stuck in PREFLIGHT for >10 min → backend issue, not client. Show
batch-get-code-review-jobsoutput and tell user to escalate. - Code too large (zip > 2 GB) → run on a subdirectory instead.
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。