-
Notifications
You must be signed in to change notification settings - Fork 0
风险分析层 #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
The head ref may contain hidden characters: "\u6DFB\u52A0\u57FA\u4E8E\u89C4\u5219\u7684\u5DE5\u7A0B\u98CE\u9669\u5206\u6790\u5C42"
Merged
风险分析层 #4
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
|
|
||
| import { parseUnifiedDiff } from "../parse-unified-diff.js"; | ||
| import { analyzeSemantics } from "../semantic/analyze-semantics.js"; | ||
| import { analyzeRisk } from "./analyze-risk.js"; | ||
|
|
||
| function assess(filename: string, patch: string, language = "typescript") { | ||
| const parsed = parseUnifiedDiff(filename, patch); | ||
| const semantic = analyzeSemantics(parsed, { language }); | ||
|
|
||
| return analyzeRisk({ filename, language, semantic, parsed }); | ||
| } | ||
|
|
||
| describe("analyzeRisk", () => { | ||
| it("detects authLogicChanged for auth path and login symbol", () => { | ||
| const patch = `@@ -0,0 +1,3 @@ | ||
| +export function login() { | ||
| + return verifyToken(); | ||
| +} | ||
| `; | ||
| const result = assess("src/auth/service.ts", patch); | ||
|
|
||
| const finding = result.findings.find((f) => f.id === "authLogicChanged"); | ||
| expect(finding).toBeDefined(); | ||
| expect(finding?.confidence).toBeGreaterThanOrEqual(0.7); | ||
| expect(result.riskHints.length).toBeGreaterThan(0); | ||
| }); | ||
|
|
||
| it("detects databaseOperationModified for prisma query changes", () => { | ||
| const patch = `@@ -1,1 +1,1 @@ | ||
| -await prisma.user.findMany() | ||
| +await prisma.user.findFirst() | ||
| `; | ||
| const result = assess("src/db/user-repo.ts", patch); | ||
|
|
||
| expect(result.findings.some((f) => f.id === "databaseOperationModified")).toBe( | ||
| true, | ||
| ); | ||
| }); | ||
|
|
||
| it("detects cacheLayerTouched for redis import", () => { | ||
| const patch = `@@ -0,0 +1,1 @@ | ||
| +import Redis from 'ioredis'; | ||
| `; | ||
| const result = assess("src/cache/client.ts", patch); | ||
|
|
||
| expect(result.findings.some((f) => f.id === "cacheLayerTouched")).toBe(true); | ||
| }); | ||
|
|
||
| it("detects asyncIntroduced for sync to async change", () => { | ||
| const patch = `@@ -1,2 +1,2 @@ | ||
| -function fetchData() { | ||
| +async function fetchData() { | ||
| `; | ||
| const result = assess("src/api.ts", patch); | ||
|
|
||
| expect(result.findings.some((f) => f.id === "asyncIntroduced")).toBe(true); | ||
| expect(result.riskHints.some((hint) => hint.includes("Async"))).toBe(true); | ||
| }); | ||
|
|
||
| it("detects errorHandlingRemoved when try/catch is deleted", () => { | ||
| const patch = `@@ -1,4 +1,1 @@ | ||
| -try { | ||
| - doWork(); | ||
| -} catch (error) { | ||
| -} | ||
| +doWork(); | ||
| `; | ||
| const result = assess("src/worker.ts", patch); | ||
|
|
||
| expect(result.findings.some((f) => f.id === "errorHandlingRemoved")).toBe(true); | ||
| }); | ||
|
|
||
| it("detects concurrencyRisk when lock keyword and async change coexist", () => { | ||
| const patch = `@@ -1,3 +1,3 @@ | ||
| -function acquireLock() { | ||
| +async function acquireLock() { | ||
| mutex.lock(); | ||
| `; | ||
| const result = assess("src/concurrent/lock.ts", patch); | ||
|
|
||
| expect(result.findings.some((f) => f.id === "concurrencyRisk")).toBe(true); | ||
| }); | ||
|
|
||
| it("returns empty risk for null patch", () => { | ||
| const parsed = parseUnifiedDiff("empty.ts", null); | ||
| const semantic = analyzeSemantics(parsed); | ||
|
|
||
| const result = analyzeRisk({ | ||
| filename: "empty.ts", | ||
| language: "typescript", | ||
| semantic, | ||
| parsed, | ||
| }); | ||
|
|
||
| expect(result.riskHints).toHaveLength(0); | ||
| expect(result.findings).toHaveLength(0); | ||
| }); | ||
|
|
||
| it("filters hints by minConfidence", () => { | ||
| const patch = `@@ -0,0 +1,1 @@ | ||
| +// minor comment in migrations folder | ||
| `; | ||
| const parsed = parseUnifiedDiff("src/db/migrations/readme.md", patch); | ||
| const semantic = analyzeSemantics(parsed, { language: "typescript" }); | ||
|
|
||
| const lowThreshold = analyzeRisk( | ||
| { filename: parsed.filename, language: "typescript", semantic, parsed }, | ||
| { minConfidence: 0.6 }, | ||
| ); | ||
| const highThreshold = analyzeRisk( | ||
| { filename: parsed.filename, language: "typescript", semantic, parsed }, | ||
| { minConfidence: 0.9 }, | ||
| ); | ||
|
|
||
| expect(lowThreshold.riskHints.length).toBeGreaterThanOrEqual( | ||
| highThreshold.riskHints.length, | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import { parseUnifiedDiff } from "../parse-unified-diff.js"; | ||
| import type { ParsedFileDiff } from "../types.js"; | ||
| import { analyzeSemantics } from "../semantic/analyze-semantics.js"; | ||
| import type { AnalyzeSemanticsOptions } from "../semantic/analyze-semantics.js"; | ||
| import { detectLanguage } from "../semantic/detect-language.js"; | ||
| import { | ||
| DEFAULT_MIN_CONFIDENCE, | ||
| runRiskDetectors, | ||
| } from "./engine/run-detectors.js"; | ||
| import type { RiskDetector } from "./interfaces/risk-detector.js"; | ||
| import { | ||
| EMPTY_RISK_ANALYSIS, | ||
| type RiskAnalysisInput, | ||
| type RiskAnalysisResult, | ||
| } from "./types.js"; | ||
|
|
||
| export interface AnalyzeRiskOptions { | ||
| minConfidence?: number; | ||
| detectors?: RiskDetector[]; | ||
| } | ||
|
|
||
| export function analyzeRisk( | ||
| input: RiskAnalysisInput, | ||
| options: AnalyzeRiskOptions = {}, | ||
| ): RiskAnalysisResult { | ||
| if (input.parsed.isEmpty) { | ||
| return { ...EMPTY_RISK_ANALYSIS }; | ||
| } | ||
|
|
||
| return runRiskDetectors(input, { | ||
| minConfidence: options.minConfidence ?? DEFAULT_MIN_CONFIDENCE, | ||
| detectors: options.detectors, | ||
| }); | ||
| } | ||
|
|
||
| export interface ParseAnalyzeAndAssessRiskOptions extends AnalyzeSemanticsOptions { | ||
| minConfidence?: number; | ||
| detectors?: RiskDetector[]; | ||
| } | ||
|
|
||
| export interface ParsedFileDiffWithSemanticAndRisk extends ParsedFileDiff { | ||
| semantic: ReturnType<typeof analyzeSemantics>; | ||
| risk: RiskAnalysisResult; | ||
| } | ||
|
|
||
| /** Parses patch, runs semantic + risk analysis in one step. */ | ||
| export function parseAnalyzeAndAssessRisk( | ||
| filename: string, | ||
| patch: string | null, | ||
| options: ParseAnalyzeAndAssessRiskOptions = {}, | ||
| ): ParsedFileDiffWithSemanticAndRisk { | ||
| const language = options.language ?? detectLanguage(filename); | ||
| const parsed = parseUnifiedDiff(filename, patch); | ||
| const semantic = analyzeSemantics(parsed, { ...options, language }); | ||
|
|
||
| const risk = analyzeRisk( | ||
| { filename, language, semantic, parsed }, | ||
| { | ||
| minConfidence: options.minConfidence, | ||
| detectors: options.detectors, | ||
| }, | ||
| ); | ||
|
|
||
| return { ...parsed, semantic, risk }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import type { RiskDetector } from "../interfaces/risk-detector.js"; | ||
| import type { RiskAnalysisInput, RiskFinding } from "../types.js"; | ||
| import { truncateEvidence } from "../utils/confidence.js"; | ||
| import { collectChangedLines } from "../utils/line-scan.js"; | ||
|
|
||
| export class AsyncDetector implements RiskDetector { | ||
| readonly id = "asyncIntroduced" as const; | ||
|
|
||
| detect(input: RiskAnalysisInput): RiskFinding | null { | ||
| const evidence: string[] = []; | ||
|
|
||
| if (input.semantic.asyncChanges) { | ||
| evidence.push("semantic.asyncChanges=true"); | ||
| } | ||
|
|
||
| const asyncAdds = collectChangedLines(input.parsed).filter( | ||
| (line) => | ||
| line.side === "add" && | ||
| (/\basync\s+function\b/.test(line.content) || | ||
| /\basync\s+def\b/.test(line.content) || | ||
| /\basync\s+\w+\s*\(/.test(line.content)), | ||
| ); | ||
|
|
||
| if (asyncAdds.length > 0) { | ||
| evidence.push(`async additions: ${asyncAdds.length}`); | ||
| } | ||
|
|
||
| if (evidence.length === 0) { | ||
| return null; | ||
| } | ||
|
|
||
| return { | ||
| id: this.id, | ||
| message: `Async behavior introduced in ${input.filename}`, | ||
| confidence: 0.9, | ||
| evidence: evidence.map(truncateEvidence), | ||
| }; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
在检测新增的异步行为时,当前的正则表达式无法匹配到非常常见的 异步箭头函数(例如
async () => {}或async x => {}),因为\basync\s+\w+\s*\(要求async后面必须紧跟一个单词字符和括号。建议优化正则表达式,以完整支持 JavaScript/TypeScript 中的异步箭头函数、类异步方法以及 Python 中的
async def。