Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion internal/codeguard/checks/design/local_abstraction.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ func leakFindings(env support.Context, file string, source string) []core.Findin
domainPath := isDomainPath(file)
apiPath := isAPIPath(file)
handlerPath := isHandlerPath(file)
testOrStubPath := isDesignTestOrStubPath(file)
persistenceBoundaryPath := domainPath || apiPath || handlerPath || isContractBoundaryPath(file)
for idx, line := range lines {
trimmed := strings.TrimSpace(line)
Expand All @@ -126,7 +127,7 @@ func leakFindings(env support.Context, file string, source string) []core.Findin
findings = append(findings, designFinding(env, ruleInfrastructureLeak, file, lineNo,
"infrastructure/framework type leaks into a domain or public boundary", core.ConfidenceHigh))
}
if persistenceBoundaryPath && !isPackageAPIImplementationPath(file) && (apiPath || handlerPath || isPublicDeclaration(codeLine)) &&
if persistenceBoundaryPath && !isPackageAPIImplementationPath(file) && !testOrStubPath && (apiPath || handlerPath || isPublicDeclaration(codeLine)) &&
persistenceLeakPattern.MatchString(codeLine) &&
!allowedGeneratedPersistenceEnumLine(codeLine) && !allowedTypeScriptRecordUtilityLine(codeLine) &&
!allowedUIPropsDerivedTypeLine(file, codeLine) && !allowedFrameworkDTOBoundaryLine(file, codeLine) {
Expand Down Expand Up @@ -491,6 +492,21 @@ func isPackageAPIImplementationPath(file string) bool {
return strings.Contains(normalized, "/packages/api/src/") || strings.HasPrefix(normalized, "packages/api/src/")
}

func isDesignTestOrStubPath(file string) bool {
normalized := strings.ToLower(filepathSlash(file))
if strings.Contains(normalized, "/test/") || strings.Contains(normalized, "/tests/") ||
strings.Contains(normalized, "/testdata/") || strings.Contains(normalized, "/fixtures/") ||
strings.Contains(normalized, "/__fixtures__/") || strings.Contains(normalized, "/mocks/") ||
strings.Contains(normalized, "/stubs/") {
return true
}
return strings.HasSuffix(normalized, "_test.go") || strings.HasSuffix(normalized, "_test.py") ||
strings.HasSuffix(normalized, ".test.ts") || strings.HasSuffix(normalized, ".spec.ts") ||
strings.HasSuffix(normalized, ".test.tsx") || strings.HasSuffix(normalized, ".spec.tsx") ||
strings.HasSuffix(normalized, ".test.js") || strings.HasSuffix(normalized, ".spec.js") ||
strings.HasSuffix(normalized, ".test.jsx") || strings.HasSuffix(normalized, ".spec.jsx")
}

func isContractBoundaryPath(file string) bool {
normalized := strings.ToLower(filepathSlash(file))
if isFrontendUIPath(file) {
Expand Down
58 changes: 55 additions & 3 deletions internal/codeguard/checks/quality/quality_defensive.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,10 @@ func unvalidatedBoundaryInputLine(fn precisionFunction, loweredBody string) (int
if !boundaryFunctionName(fn.Name) && !hasBoundaryParam(fn.Params) {
return 0, false
}
if containsAny(loweredBody, []string{"validate", "schema", "sanitize", "bind", "decodevalid", "zod.", "yup.", "pydantic", "jsonschema"}) {
if validatedBoundaryInputPattern(fn, loweredBody) {
return 0, false
}
if formDataHasContentLengthPreflight(loweredBody) {
return 0, false
}
if containsAny(loweredBody, []string{"request", "req.", "event", "payload", "body", "json", "params", "query"}) {
Expand All @@ -139,6 +142,22 @@ func unvalidatedBoundaryInputLine(fn precisionFunction, loweredBody string) (int
return 0, false
}

func formDataHasContentLengthPreflight(loweredBody string) bool {
return strings.Contains(loweredBody, "formdata") &&
containsAny(loweredBody, []string{"content-length", "contentlength"}) &&
containsAny(loweredBody, []string{"> max", "> limit", "max_upload", "upload too large"})
}

func validatedBoundaryInputPattern(fn precisionFunction, loweredBody string) bool {
if containsAny(loweredBody, []string{"validate", "schema", "sanitize", "bind", "decodevalid", "safeparse", "zod.", "yup.", "pydantic", "jsonschema"}) {
return true
}
if regexp.MustCompile(`(?i)\b(parse|assert|guard|ensure|decode)[A-Z_][A-Za-z0-9_]*(?:Input|Payload|Body|Params|Query|Record|Request|Event|Config)?\s*\(`).MatchString(functionRawBody(fn)) {
return true
}
return false
}

func hasBoundaryParam(params []support.ParsedParam) bool {
for _, param := range params {
name := strings.ToLower(param.Name)
Expand Down Expand Up @@ -186,6 +205,9 @@ func integerOverflowLine(file string, fn precisionFunction, loweredBody string)
if isUIRenderArithmeticContext(file, fn, loweredBody) {
return 0, false
}
if guardedSequenceCollisionRetry(loweredBody) {
return 0, false
}
if containsAny(loweredBody, []string{"maxint", "math.max", "checked", "saturating", "overflow", "limits<", "safeint"}) {
return 0, false
}
Expand All @@ -198,6 +220,16 @@ func integerOverflowLine(file string, fn precisionFunction, loweredBody string)
return 0, false
}

func guardedSequenceCollisionRetry(loweredBody string) bool {
if !containsAny(loweredBody, []string{"p2002", "unique", "collision", "prisma"}) {
return false
}
if !containsAny(loweredBody, []string{"retry", "attempt", "for "}) {
return false
}
return containsAny(loweredBody, []string{"count + 1", "count+1", "externalid", "external_id", "nextid", "next_id"})
}

func isUIRenderArithmeticContext(file string, fn precisionFunction, loweredBody string) bool {
if isUIHelperOrMappingContext(file, fn) {
return true
Expand Down Expand Up @@ -278,6 +310,9 @@ func uncheckedExternalResponseLine(fn precisionFunction, loweredBody string) (in
if !externalCallPattern.MatchString(functionRawBody(fn)) {
return 0, false
}
if urlProtocolAllowlistPattern(loweredBody) {
return 0, false
}
if containsAny(loweredBody, []string{"status", ".ok", "err != nil", "if err", "error", "catch", "raise_for_status", "response_code"}) {
return 0, false
}
Expand All @@ -287,11 +322,18 @@ func uncheckedExternalResponseLine(fn precisionFunction, loweredBody string) (in
return 0, false
}

func urlProtocolAllowlistPattern(loweredBody string) bool {
if !containsAny(loweredBody, []string{"new url(", ".protocol"}) {
return false
}
return containsAny(loweredBody, []string{"https:", "http:", "allowedprotocol", "allowed_protocol", "protocols.includes", "includes(url.protocol)", "protocol !==", "protocol !="})
}

func missingSchemaValidationLine(fn precisionFunction, loweredBody string) (int, bool) {
if !jsonDecodePattern.MatchString(functionRawBody(fn)) {
return 0, false
}
if containsAny(loweredBody, []string{"validate", "schema", "jsonschema", "zod.", "yup.", "pydantic", "isvalid", "required"}) {
if validatedBoundaryInputPattern(fn, loweredBody) || containsAny(loweredBody, []string{"jsonschema", "isvalid", "required"}) {
return 0, false
}
return firstPatternLine(fn, jsonDecodePattern), true
Expand All @@ -301,12 +343,22 @@ func missingResourceLimitLine(fn precisionFunction, loweredBody string) (int, bo
if !resourceReadPattern.MatchString(functionRawBody(fn)) {
return 0, false
}
if containsAny(loweredBody, []string{"limitreader", "maxbytes", "max_bytes", "content-length", "limit(", "take(", "buffer_size", "quota"}) {
if containsAny(loweredBody, []string{"limitreader", "maxbytes", "max_bytes", "content-length", "contentlength", "limit(", "take(", "buffer_size", "quota"}) {
return 0, false
}
if boundedReadByteLengthCheck(loweredBody) {
return 0, false
}
return firstPatternLine(fn, resourceReadPattern), true
}

func boundedReadByteLengthCheck(loweredBody string) bool {
if !containsAny(loweredBody, []string{"arraybuffer", ".text", "readall", ".read"}) {
return false
}
return containsAny(loweredBody, []string{"bytelength", "byte_length", ".length > max", ".length > limit", "buffer.length", "bytes.length"})
}

func invalidStateTransitionLine(fn precisionFunction, loweredBody string) (int, bool) {
if !stateAssignmentPattern.MatchString(functionRawBody(fn)) {
return 0, false
Expand Down
29 changes: 22 additions & 7 deletions internal/codeguard/checks/quality/quality_precision.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ var (
"misc": {}, "stuff": {}, "value": {}, "values": {},
}
queryFunctionPrefixPattern = regexp.MustCompile(`^(get|find|list|load|read|lookup|fetch|is|has|can|should|compute|calculate|build|format|parse)`)
mutatingCallPattern = regexp.MustCompile(`(?i)(^|[.>:\-_])(add|append|assign|create|delete|emit|insert|mutate|persist|publish|remove|save|send|set|store|update|upsert|write)([A-Z_:\-.]|$)`)
mutatingCallPattern = regexp.MustCompile(`(?i)(^|[.>:\-_])(add|append|assign|clear|create|delete|emit|insert|mutate|persist|pop|publish|push|push_back|remove|reverse|save|send|set|sort|splice|store|update|upsert|write)([A-Z_:\-.]|$)`)
lowLevelOperationPattern = regexp.MustCompile(`(?i)(\bsql\.|\.query\(|\.exec\(|\bhttp\.|\bfetch\(|\baxios\.|\brequests\.|\bjson\.|\bJSON\.|\bos\.Getenv\b|\bprocess\.env\b|\bfs\.|#include\b)`)
primitiveTypePattern = regexp.MustCompile(`(?i)\b(string|str|int|int64|float|float64|double|decimal|number|boolean|bool|char|long|short)\b`)
domainPrimitiveNamePattern = regexp.MustCompile(`(?i)(id|status|state|type|kind|currency|amount|price|email|phone|country|role|permission|tenant|account|customer|order)`)
Expand Down Expand Up @@ -372,7 +372,7 @@ func precisionFunctionFindings(env support.Context, file string, fn precisionFun
findings = append(findings, precisionWarnFinding(env, namingGenericIdentifierRuleID, file, fn.StartLine,
fmt.Sprintf("function name %q is too generic to communicate intent", fn.Name), core.ConfidenceHigh))
}
if isAmbiguousIdentifier(fn.Name) && !isUIConventionalAmbiguousName(file, fn, fn.Name, "", fn.StartLine) {
if isAmbiguousIdentifier(fn.Name) && !isUIConventionalAmbiguousName(file, fn, fn.Name, "", fn.StartLine) && !isLocallyClearAmbiguousName(fn, fn.Name) {
findings = append(findings, precisionWarnFinding(env, qualityAmbiguousNameRuleID, file, fn.StartLine,
fmt.Sprintf("function name %q is ambiguous without domain context", fn.Name), core.ConfidenceHigh))
}
Expand All @@ -381,7 +381,7 @@ func precisionFunctionFindings(env support.Context, file string, fn precisionFun
findings = append(findings, precisionWarnFinding(env, namingGenericIdentifierRuleID, file, fn.StartLine,
fmt.Sprintf("parameter %q is too generic to communicate intent", param.Name), core.ConfidenceHigh))
}
if isAmbiguousIdentifier(param.Name) && !isUIConventionalAmbiguousName(file, fn, param.Name, param.Type, fn.StartLine) {
if isAmbiguousIdentifier(param.Name) && !isUIConventionalAmbiguousName(file, fn, param.Name, param.Type, fn.StartLine) && !isLocallyClearAmbiguousName(fn, param.Name) {
findings = append(findings, precisionWarnFinding(env, qualityAmbiguousNameRuleID, file, fn.StartLine,
fmt.Sprintf("parameter %q is ambiguous without domain context", param.Name), core.ConfidenceHigh))
}
Expand All @@ -395,12 +395,12 @@ func precisionFunctionFindings(env support.Context, file string, fn precisionFun
findings = append(findings, precisionWarnFinding(env, namingGenericIdentifierRuleID, file, assignment.Line,
fmt.Sprintf("identifier %q is too generic to explain its role", assignment.Name), core.ConfidenceHigh))
}
if isAmbiguousIdentifier(assignment.Name) && !isUIConventionalAmbiguousName(file, fn, assignment.Name, "", assignment.Line) {
if isAmbiguousIdentifier(assignment.Name) && !isUIConventionalAmbiguousName(file, fn, assignment.Name, "", assignment.Line) && !isLocallyClearAmbiguousName(fn, assignment.Name) {
findings = append(findings, precisionWarnFinding(env, qualityAmbiguousNameRuleID, file, assignment.Line,
fmt.Sprintf("identifier %q is ambiguous without domain context", assignment.Name), core.ConfidenceHigh))
}
}
if mixedAbstractionLevel(fn) {
if mixedAbstractionLevel(fn) && !isAdapterOrOrchestrationFunction(file, fn) {
findings = append(findings, precisionWarnFinding(env, functionMixedAbstractionLevelRuleID, file, fn.StartLine,
fmt.Sprintf("function %s mixes orchestration calls with low-level infrastructure operations", fn.Name), core.ConfidenceMedium))
findings = append(findings, precisionWarnFinding(env, qualityMixedAbstractionLevelsRuleID, file, fn.StartLine,
Expand Down Expand Up @@ -443,6 +443,15 @@ func isAmbiguousIdentifier(name string) bool {
return ok
}

func isLocallyClearAmbiguousName(fn precisionFunction, name string) bool {
normalized := strings.ToLower(strings.Trim(name, "_$"))
if normalized != "value" && normalized != "values" {
return false
}
loweredName := strings.ToLower(fn.Name)
return containsAny(loweredName, []string{"parse", "normalize", "format", "render", "map", "transform", "compare", "equal", "record", "field", "option"})
}

func isBooleanParameter(param support.ParsedParam) bool {
return strings.EqualFold(strings.TrimSpace(param.Type), "bool") ||
strings.EqualFold(strings.TrimSpace(param.Type), "boolean") ||
Expand Down Expand Up @@ -474,9 +483,12 @@ func hiddenSideEffect(file string, fn precisionFunction) bool {
if !queryFunctionPrefixPattern.MatchString(strings.ToLower(fn.Name)) {
return false
}
if isAccumulatorBuilderFunctionName(fn.Name) && !hasLikelyExternalMutationCall(fn) {
return false
}
localTargets := localMutationTargets(fn)
for _, call := range directCalls(fn) {
if mutatingCallPattern.MatchString(call.Callee) && !isLocalMutationCall(call.Callee, localTargets) {
if mutatingCallPattern.MatchString(call.Callee) && !isLocalMutationCall(call.Callee, localTargets) && !isBuilderAccumulatorMutationCall(fn, call) {
return true
}
}
Expand Down Expand Up @@ -516,13 +528,16 @@ func commandQueryMix(file string, fn precisionFunction) bool {
if !fn.Returns {
return false
}
if isAccumulatorBuilderFunctionName(fn.Name) && !hasLikelyExternalMutationCall(fn) {
return false
}
name := strings.ToLower(fn.Name)
if !queryFunctionPrefixPattern.MatchString(name) && !strings.Contains(fn.Body, "return ") {
return false
}
localTargets := localMutationTargets(fn)
for _, call := range directCalls(fn) {
if mutatingCallPattern.MatchString(call.Callee) && !isLocalMutationCall(call.Callee, localTargets) {
if mutatingCallPattern.MatchString(call.Callee) && !isLocalMutationCall(call.Callee, localTargets) && !isBuilderAccumulatorMutationCall(fn, call) {
return true
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ func duplicatedKnowledgeLineIsDisplayOnly(line string) bool {
if strings.Contains(lowered, "classname") || strings.Contains(lowered, "clasname") || strings.Contains(lowered, "class:") {
return true
}
if strings.Contains(lowered, "class") && strings.Contains(line, "-") {
return true
}
for _, marker := range []string{"css", "style", "styles", "variant", "variants", "tailwind", "stylesheet"} {
if strings.Contains(lowered, marker) {
return true
}
}
if strings.Contains(line, "<") && strings.Contains(line, ">") {
return true
}
Expand All @@ -91,6 +99,12 @@ func domainKnowledgeLiteralInLine(value string, line string) bool {
if numeric, ok := duplicatedKnowledgeNumber(trimmed); ok {
return duplicatedKnowledgeNumericLiteral(numeric, line)
}
if duplicatedKnowledgeSentinelLiteral(trimmed) {
return false
}
if duplicatedKnowledgeTableOrEnumLiteral(trimmed, line) {
return false
}
if duplicatedKnowledgeEnumStatusLiteral(trimmed, line) {
return false
}
Expand All @@ -116,9 +130,6 @@ func duplicatedKnowledgeNumericLiteral(number int, line string) bool {
}

func duplicatedKnowledgeEnumStatusLiteral(value string, line string) bool {
if line == "" {
return false
}
trimmed := strings.TrimSpace(value)
if trimmed == "" {
return false
Expand All @@ -127,6 +138,12 @@ func duplicatedKnowledgeEnumStatusLiteral(value string, line string) bool {
if !enumLike {
return false
}
if looksLikeAllCapsEnumLiteral(trimmed) {
return true
}
if line == "" {
return false
}
loweredLine := strings.ToLower(line)
for _, marker := range []string{"enum", "status", "type:", "kind:", "value:", "option", "label", "as const", "satisfies"} {
if strings.Contains(loweredLine, marker) {
Expand All @@ -136,6 +153,48 @@ func duplicatedKnowledgeEnumStatusLiteral(value string, line string) bool {
return false
}

func duplicatedKnowledgeSentinelLiteral(value string) bool {
trimmed := strings.TrimSpace(value)
return strings.HasPrefix(trimmed, "__") && strings.HasSuffix(trimmed, "__") && len(trimmed) <= 40
}

func duplicatedKnowledgeTableOrEnumLiteral(value string, line string) bool {
if !strings.Contains(value, "_") {
return false
}
if len(value) > 48 {
return false
}
parts := strings.Split(value, "_")
if len(parts) > 4 {
return false
}
for _, part := range parts {
if part == "" {
return false
}
}
loweredLine := strings.ToLower(line)
return containsAny(loweredLine, []string{"table", "tablename", "table_name", "enum", "status", "type", "kind", "key:", "value:", "option"})
}

func looksLikeAllCapsEnumLiteral(value string) bool {
hasLetter := false
for _, r := range value {
switch {
case r >= 'A' && r <= 'Z':
hasLetter = true
case r >= '0' && r <= '9':
continue
case r == '_' || r == '-' || r == ':':
continue
default:
return false
}
}
return hasLetter && strings.ToUpper(value) == value
}

func duplicatedKnowledgeNumber(value string) (int, bool) {
number, err := strconv.Atoi(value)
if err != nil {
Expand Down
Loading
Loading