ai-agent-security 0.22.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (618) hide show
  1. agentsec/__init__.py +44 -0
  2. agentsec/__main__.py +13 -0
  3. agentsec/advisor.py +334 -0
  4. agentsec/ai/__init__.py +13 -0
  5. agentsec/ai/lethal_trifecta.py +302 -0
  6. agentsec/ai/semgrep-rules/python-llm.yaml +96 -0
  7. agentsec/ai_bom.py +440 -0
  8. agentsec/arm.py +126 -0
  9. agentsec/astutil.py +290 -0
  10. agentsec/audit.py +643 -0
  11. agentsec/bicep.py +323 -0
  12. agentsec/canary.py +1244 -0
  13. agentsec/cfn.py +357 -0
  14. agentsec/checklist/__init__.py +203 -0
  15. agentsec/checklist/checklist.json +11124 -0
  16. agentsec/checkmeta.py +84 -0
  17. agentsec/ci/__init__.py +9 -0
  18. agentsec/ci/components/container-cve/component.json +14 -0
  19. agentsec/ci/components/container-cve/files/.github/workflows/container-cve.yml.tmpl +83 -0
  20. agentsec/ci/components/container-cve/files/.trivy-images.txt +9 -0
  21. agentsec/ci/components/dast/component.json +14 -0
  22. agentsec/ci/components/dast/files/.github/workflows/dast.yml.tmpl +90 -0
  23. agentsec/ci/components/db-lint/component.json +14 -0
  24. agentsec/ci/components/db-lint/files/.github/workflows/db-lint.yml.tmpl +65 -0
  25. agentsec/ci/components/dockerfile-lint/component.json +11 -0
  26. agentsec/ci/components/dockerfile-lint/files/.github/workflows/dockerfile-lint.yml.tmpl +34 -0
  27. agentsec/ci/components/dockerfile-lint/files/.hadolint.yaml +28 -0
  28. agentsec/ci/components/frontend-sec/component.json +14 -0
  29. agentsec/ci/components/frontend-sec/files/.github/workflows/frontend-security.yml.tmpl +40 -0
  30. agentsec/ci/components/garak/component.json +14 -0
  31. agentsec/ci/components/garak/files/.github/workflows/llm-redteam-garak.yml.tmpl +79 -0
  32. agentsec/ci/components/garak/files/scripts/redteam-shim.py +221 -0
  33. agentsec/ci/components/promptfoo/component.json +15 -0
  34. agentsec/ci/components/promptfoo/files/.github/workflows/llm-redteam-promptfoo.yml.tmpl +64 -0
  35. agentsec/ci/components/promptfoo/files/promptfooconfig.yaml +205 -0
  36. agentsec/ci/components/promptfoo/files/scripts/redteam-shim.py +221 -0
  37. agentsec/ci/components/python-sec/component.json +14 -0
  38. agentsec/ci/components/python-sec/files/.github/workflows/python-security.yml.tmpl +45 -0
  39. agentsec/ci/components/react-doctor/component.json +16 -0
  40. agentsec/ci/components/react-doctor/files/.github/workflows/frontend-health.yml.tmpl +84 -0
  41. agentsec/ci/components/react-doctor/files/@@FRONTEND_DIR@@/react-doctor.config.json +13 -0
  42. agentsec/ci/components/scorecard/component.json +13 -0
  43. agentsec/ci/components/scorecard/files/.github/workflows/scorecard.yml.tmpl +78 -0
  44. agentsec/ci/components/secret-scan/component.json +14 -0
  45. agentsec/ci/components/secret-scan/files/.github/workflows/secret-scan.yml.tmpl +70 -0
  46. agentsec/ci/components/secret-scan/files/.gitleaks.toml +34 -0
  47. agentsec/ci/components/secret-scan/files/.gitleaksignore +6 -0
  48. agentsec/ci/components/self-audit/component.json +16 -0
  49. agentsec/ci/components/self-audit/files/.github/workflows/agentsec-audit.yml.tmpl +44 -0
  50. agentsec/ci/components/type-check/component.json +14 -0
  51. agentsec/ci/components/type-check/files/.github/workflows/type-check.yml.tmpl +44 -0
  52. agentsec/ci/doctor.py +479 -0
  53. agentsec/ci/library.py +548 -0
  54. agentsec/ci/render.py +31 -0
  55. agentsec/clean_canary.py +171 -0
  56. agentsec/clean_canary_fixtures.py +533 -0
  57. agentsec/cli.py +3140 -0
  58. agentsec/compounding_risk.py +246 -0
  59. agentsec/config.py +186 -0
  60. agentsec/console.py +32 -0
  61. agentsec/corpus.py +1437 -0
  62. agentsec/coverage.py +365 -0
  63. agentsec/crosscheck.py +152 -0
  64. agentsec/deps_apply.py +962 -0
  65. agentsec/deps_monitor.py +912 -0
  66. agentsec/detect.py +1221 -0
  67. agentsec/drift.py +309 -0
  68. agentsec/epss.py +148 -0
  69. agentsec/exceptions.py +539 -0
  70. agentsec/findings.py +945 -0
  71. agentsec/fix.py +293 -0
  72. agentsec/gap_report.py +101 -0
  73. agentsec/guard_sandbox.py +248 -0
  74. agentsec/guard_worker.py +559 -0
  75. agentsec/guards/__init__.py +7 -0
  76. agentsec/guards/acp_vulnerabilities.py +385 -0
  77. agentsec/guards/actions_script_injection.py +261 -0
  78. agentsec/guards/actions_sha_pin.py +105 -0
  79. agentsec/guards/agent_headless_trust_surface.py +295 -0
  80. agentsec/guards/agent_iam_control_plane_exposure.py +213 -0
  81. agentsec/guards/agent_iam_killchain_combination.py +294 -0
  82. agentsec/guards/agent_iam_tool_resource_unscoped.py +307 -0
  83. agentsec/guards/agent_loop_circuit_breaker.py +828 -0
  84. agentsec/guards/agent_memory_retention.py +162 -0
  85. agentsec/guards/agent_memory_security.py +403 -0
  86. agentsec/guards/agent_memory_user_scope.py +328 -0
  87. agentsec/guards/agent_resume_unverified_trigger.py +279 -0
  88. agentsec/guards/agent_tool_audit_log.py +181 -0
  89. agentsec/guards/agent_tool_overpermission.py +352 -0
  90. agentsec/guards/agent_tool_url_fetch_ssrf.py +414 -0
  91. agentsec/guards/agentic_skills_ast.py +249 -0
  92. agentsec/guards/ai_docker.py +458 -0
  93. agentsec/guards/ai_instruction_poisoning.py +435 -0
  94. agentsec/guards/alb_listener_http_protocol.py +164 -0
  95. agentsec/guards/ansi_escape_llm_output.py +235 -0
  96. agentsec/guards/ansible_debug_echoes_auth_variable.py +134 -0
  97. agentsec/guards/ansible_host_key_checking_disabled.py +114 -0
  98. agentsec/guards/ansible_ignore_errors_on_security_task.py +124 -0
  99. agentsec/guards/ansible_no_log_disabled_on_secret_task.py +138 -0
  100. agentsec/guards/ansible_setuid_binary_creation.py +101 -0
  101. agentsec/guards/ansible_sudo_nopasswd.py +103 -0
  102. agentsec/guards/ansible_unsafe_lookups_enabled.py +104 -0
  103. agentsec/guards/api_docs_exposed.py +124 -0
  104. agentsec/guards/approval_parser_shell_desync.py +241 -0
  105. agentsec/guards/argv_toctou.py +270 -0
  106. agentsec/guards/arm_aks_rbac_disabled.py +133 -0
  107. agentsec/guards/arm_apim_backend_unauthenticated.py +169 -0
  108. agentsec/guards/arm_appservice_https_only_disabled.py +143 -0
  109. agentsec/guards/arm_redis_ssl_disabled.py +116 -0
  110. agentsec/guards/arm_sql_tde_disabled.py +143 -0
  111. agentsec/guards/async_blocking_io.py +196 -0
  112. agentsec/guards/auth_dependency_not_applied.py +682 -0
  113. agentsec/guards/auth_disabled_by_default.py +149 -0
  114. agentsec/guards/auth_rate_limit_absent.py +208 -0
  115. agentsec/guards/auth_users_exposed_view.py +91 -0
  116. agentsec/guards/auto_updates_absent.py +231 -0
  117. agentsec/guards/autostart_persistence_mechanism.py +155 -0
  118. agentsec/guards/aws_observability_hygiene.py +336 -0
  119. agentsec/guards/aws_weak_tls_policy.py +362 -0
  120. agentsec/guards/azure_keyvault_key_no_expiration.py +131 -0
  121. agentsec/guards/azure_keyvault_purge_protection_disabled.py +130 -0
  122. agentsec/guards/azure_mssql_publicly_accessible.py +135 -0
  123. agentsec/guards/azure_storage_account_https_only.py +137 -0
  124. agentsec/guards/azure_storage_account_public_blob_access.py +135 -0
  125. agentsec/guards/background_tasks.py +72 -0
  126. agentsec/guards/base.py +7216 -0
  127. agentsec/guards/bicep_admin_username_literal.py +103 -0
  128. agentsec/guards/bicep_commandtoexecute_plaintext_settings.py +190 -0
  129. agentsec/guards/bicep_output_secret_not_secure.py +115 -0
  130. agentsec/guards/bicep_param_file_insecure_secret_value.py +112 -0
  131. agentsec/guards/bicep_secret_param_not_secure.py +106 -0
  132. agentsec/guards/bicep_secure_param_in_nested_deployment.py +229 -0
  133. agentsec/guards/bicep_secure_parameter_default.py +151 -0
  134. agentsec/guards/bola.py +156 -0
  135. agentsec/guards/browser_credential_store_access.py +217 -0
  136. agentsec/guards/build_secret.py +518 -0
  137. agentsec/guards/bulk_env_var_harvesting.py +162 -0
  138. agentsec/guards/cfn_authentication_password.py +181 -0
  139. agentsec/guards/cfn_batch_privileged_container.py +117 -0
  140. agentsec/guards/cfn_cognito_mfa_off.py +114 -0
  141. agentsec/guards/cfn_cognito_unauth_identities.py +117 -0
  142. agentsec/guards/cfn_ec2_subnet_public_ip.py +114 -0
  143. agentsec/guards/cfn_ecr_scan_on_push.py +108 -0
  144. agentsec/guards/cfn_iam_escalation_action_no_condition.py +218 -0
  145. agentsec/guards/cfn_iam_notaction_with_allow.py +156 -0
  146. agentsec/guards/cfn_iam_user_direct_policy.py +146 -0
  147. agentsec/guards/cfn_kms_key_rotation_not_enabled.py +118 -0
  148. agentsec/guards/cfn_nacl_ineffective_deny.py +145 -0
  149. agentsec/guards/cfn_rds_hardcoded_password_no_echo.py +277 -0
  150. agentsec/guards/cfn_rds_publicly_accessible.py +116 -0
  151. agentsec/guards/cfn_s3_public_access_canned_acl.py +125 -0
  152. agentsec/guards/cfn_s3_versioning_missing.py +134 -0
  153. agentsec/guards/cfn_vpc_flow_log_missing.py +123 -0
  154. agentsec/guards/cfn_waf_default_allow.py +131 -0
  155. agentsec/guards/cfn_wildcard_principal.py +148 -0
  156. agentsec/guards/checkout_price_from_server.py +91 -0
  157. agentsec/guards/ci_image_build_no_sbom_provenance.py +170 -0
  158. agentsec/guards/ci_secret_env_unscoped.py +378 -0
  159. agentsec/guards/claude_code_compromise.py +567 -0
  160. agentsec/guards/claude_hook_rce.py +210 -0
  161. agentsec/guards/claude_routines_security.py +167 -0
  162. agentsec/guards/cleartext_secret_storage.py +200 -0
  163. agentsec/guards/client_side_auth_decision.py +370 -0
  164. agentsec/guards/client_side_secret_literal.py +659 -0
  165. agentsec/guards/cloud_metadata_endpoint_literal.py +138 -0
  166. agentsec/guards/cloudtrail_logging_disabled.py +193 -0
  167. agentsec/guards/cloudwatch_log_group_not_kms_encrypted.py +112 -0
  168. agentsec/guards/code_injection_eval_exec.py +271 -0
  169. agentsec/guards/command_injection.py +321 -0
  170. agentsec/guards/compose_connection_string_credential.py +182 -0
  171. agentsec/guards/compose_credential_env_literal.py +231 -0
  172. agentsec/guards/compose_db_port_exposed.py +289 -0
  173. agentsec/guards/compose_dns_bypass.py +277 -0
  174. agentsec/guards/compose_image_digest_missing.py +132 -0
  175. agentsec/guards/compose_logging_disabled.py +120 -0
  176. agentsec/guards/compose_no_network_segmentation.py +173 -0
  177. agentsec/guards/compose_no_new_privileges.py +158 -0
  178. agentsec/guards/compose_resource_limits_absent.py +135 -0
  179. agentsec/guards/compose_sensitive_host_mount.py +188 -0
  180. agentsec/guards/compose_shared_mount_propagation.py +144 -0
  181. agentsec/guards/compose_tmpfs_insecure_options.py +150 -0
  182. agentsec/guards/compose_user_directive_missing.py +251 -0
  183. agentsec/guards/compose_writable_host_root_mount.py +203 -0
  184. agentsec/guards/compose_writable_root_filesystem.py +138 -0
  185. agentsec/guards/content_type_magic_bytes.py +119 -0
  186. agentsec/guards/cors_wildcard.py +166 -0
  187. agentsec/guards/credential_file_path_reference.py +217 -0
  188. agentsec/guards/crewai_rce_chain.py +290 -0
  189. agentsec/guards/cron_systemd_persistence_write.py +248 -0
  190. agentsec/guards/csv_injection.py +212 -0
  191. agentsec/guards/ctypes_load_downloaded_library.py +263 -0
  192. agentsec/guards/curl_pipe_to_shell.py +250 -0
  193. agentsec/guards/dataset_injection.py +374 -0
  194. agentsec/guards/datastore_auth_absent.py +308 -0
  195. agentsec/guards/db_role_privilege_excessive.py +363 -0
  196. agentsec/guards/debug_default_off.py +98 -0
  197. agentsec/guards/debug_route_exposed.py +232 -0
  198. agentsec/guards/default_service_credential.py +484 -0
  199. agentsec/guards/definer_dynamic_sql.py +246 -0
  200. agentsec/guards/definer_function_grants.py +381 -0
  201. agentsec/guards/dependency_version_floor.py +889 -0
  202. agentsec/guards/destructive_filesystem_command.py +145 -0
  203. agentsec/guards/dns_egress_allowlist.py +115 -0
  204. agentsec/guards/dns_exfiltration_pattern.py +184 -0
  205. agentsec/guards/docker_add_misuse.py +149 -0
  206. agentsec/guards/docker_apt_update_not_alone.py +140 -0
  207. agentsec/guards/docker_expose_ssh.py +123 -0
  208. agentsec/guards/docker_latest_base_tag.py +180 -0
  209. agentsec/guards/docker_nonroot_user.py +150 -0
  210. agentsec/guards/docker_privileged_flags.py +318 -0
  211. agentsec/guards/docker_run_sudo.py +127 -0
  212. agentsec/guards/docker_socket_access.py +133 -0
  213. agentsec/guards/dockerfile_credential_in_instruction.py +189 -0
  214. agentsec/guards/dockerfile_run_isolation_weakening.py +196 -0
  215. agentsec/guards/dockerfile_workdir_sensitive_path.py +105 -0
  216. agentsec/guards/dom_xss_sinks.py +974 -0
  217. agentsec/guards/download_execute_chain.py +310 -0
  218. agentsec/guards/dynamic_import_non_literal.py +155 -0
  219. agentsec/guards/dynamodb_table_not_encrypted.py +134 -0
  220. agentsec/guards/ebs_volume_not_encrypted.py +115 -0
  221. agentsec/guards/ecr_repository_hygiene.py +232 -0
  222. agentsec/guards/ecr_repository_not_kms_encrypted.py +123 -0
  223. agentsec/guards/ecs_efs_volume_transit_encryption_disabled.py +164 -0
  224. agentsec/guards/efs_file_system_not_encrypted.py +118 -0
  225. agentsec/guards/elasticache_transit_encryption_disabled.py +132 -0
  226. agentsec/guards/electron_security_misconfig.py +209 -0
  227. agentsec/guards/empty_password_in_config.py +240 -0
  228. agentsec/guards/env_file_not_gitignored.py +155 -0
  229. agentsec/guards/env_secret_console_log.py +188 -0
  230. agentsec/guards/env_secret_in_prompt.py +177 -0
  231. agentsec/guards/env_secret_logged.py +234 -0
  232. agentsec/guards/environ_dump_to_network.py +437 -0
  233. agentsec/guards/error_response_info_leak.py +779 -0
  234. agentsec/guards/fail2ban_absent.py +107 -0
  235. agentsec/guards/fail_safe_exception.py +203 -0
  236. agentsec/guards/file_system_race.py +159 -0
  237. agentsec/guards/forwarded_header_blind_trust.py +484 -0
  238. agentsec/guards/frontend_xss.py +166 -0
  239. agentsec/guards/fulfill_on_completed_not_created.py +91 -0
  240. agentsec/guards/gcp_kms_key_public.py +195 -0
  241. agentsec/guards/gcp_kms_rotation_period_not_set.py +126 -0
  242. agentsec/guards/gcp_sql_publicly_accessible.py +242 -0
  243. agentsec/guards/git_in_docker.py +188 -0
  244. agentsec/guards/go_build_supply_chain_footgun.py +183 -0
  245. agentsec/guards/go_pprof_exposed.py +200 -0
  246. agentsec/guards/go_sql_injection.py +288 -0
  247. agentsec/guards/go_ssh_host_key_trust.py +146 -0
  248. agentsec/guards/go_template_html_escaping.py +346 -0
  249. agentsec/guards/go_tls_verify_disabled.py +160 -0
  250. agentsec/guards/graphql_mutation_idor.py +223 -0
  251. agentsec/guards/guardrail_architecture.py +963 -0
  252. agentsec/guards/hardcoded_llm_provider_key.py +301 -0
  253. agentsec/guards/hardcoded_password_default_arg.py +125 -0
  254. agentsec/guards/hardcoded_private_key_in_source.py +291 -0
  255. agentsec/guards/header_injection.py +153 -0
  256. agentsec/guards/hidden_executable_dotfile.py +98 -0
  257. agentsec/guards/homoglyph_source_chars.py +366 -0
  258. agentsec/guards/hostname_regex_unsafe.py +198 -0
  259. agentsec/guards/iac_open_ingress.py +111 -0
  260. agentsec/guards/iam_escalation_action_no_condition.py +285 -0
  261. agentsec/guards/iam_managed_admin_policy_attached.py +189 -0
  262. agentsec/guards/iam_notaction_with_allow.py +166 -0
  263. agentsec/guards/iam_policy_attached_to_user_directly.py +144 -0
  264. agentsec/guards/iam_resource_scopable_wildcard.py +181 -0
  265. agentsec/guards/iam_role_public_assume.py +529 -0
  266. agentsec/guards/iam_service_wildcard.py +156 -0
  267. agentsec/guards/iam_wildcard.py +241 -0
  268. agentsec/guards/incomplete_url_scheme_check.py +143 -0
  269. agentsec/guards/incomplete_url_substring_sanitization.py +189 -0
  270. agentsec/guards/incorrect_suffix_check.py +135 -0
  271. agentsec/guards/input_delimiters.py +180 -0
  272. agentsec/guards/insecure_cookies.py +309 -0
  273. agentsec/guards/insecure_file_permissions.py +151 -0
  274. agentsec/guards/insecure_tempfile_mktemp.py +99 -0
  275. agentsec/guards/invisible_unicode.py +202 -0
  276. agentsec/guards/java_command_injection.py +187 -0
  277. agentsec/guards/java_hardcoded_password_key.py +214 -0
  278. agentsec/guards/java_ldap_injection.py +157 -0
  279. agentsec/guards/java_path_traversal.py +231 -0
  280. agentsec/guards/java_sql_injection.py +249 -0
  281. agentsec/guards/java_ssrf.py +177 -0
  282. agentsec/guards/java_tls_verify_disabled.py +228 -0
  283. agentsec/guards/java_unsafe_deserialization.py +196 -0
  284. agentsec/guards/java_weak_crypto.py +169 -0
  285. agentsec/guards/java_xxe_unsafe_parsing.py +191 -0
  286. agentsec/guards/js_buffer_noassert.py +114 -0
  287. agentsec/guards/js_client_side_open_redirect.py +279 -0
  288. agentsec/guards/js_code_injection.py +346 -0
  289. agentsec/guards/js_command_injection.py +774 -0
  290. agentsec/guards/js_cors_wildcard.py +324 -0
  291. agentsec/guards/js_helmet_header_disabled.py +127 -0
  292. agentsec/guards/js_host_header_email_link.py +139 -0
  293. agentsec/guards/js_http_to_file_access.py +135 -0
  294. agentsec/guards/js_insecure_download_sensitive_file.py +110 -0
  295. agentsec/guards/js_loop_bound_injection.py +129 -0
  296. agentsec/guards/js_path_traversal.py +328 -0
  297. agentsec/guards/js_private_file_exposure.py +258 -0
  298. agentsec/guards/js_prototype_pollution.py +153 -0
  299. agentsec/guards/js_regex_injection_dos.py +137 -0
  300. agentsec/guards/js_secure_cookies.py +237 -0
  301. agentsec/guards/js_security_headers_absent.py +198 -0
  302. agentsec/guards/js_server_side_open_redirect.py +223 -0
  303. agentsec/guards/js_sql_injection.py +201 -0
  304. agentsec/guards/js_ssrf.py +149 -0
  305. agentsec/guards/js_supply_chain.py +800 -0
  306. agentsec/guards/js_system_prompt_injection.py +229 -0
  307. agentsec/guards/js_weak_crypto.py +205 -0
  308. agentsec/guards/js_xxe_unsafe_parsing.py +179 -0
  309. agentsec/guards/jsx_href_scheme.py +445 -0
  310. agentsec/guards/jwt_alg.py +239 -0
  311. agentsec/guards/jwt_claims_validated.py +163 -0
  312. agentsec/guards/jwt_exp_too_long.py +251 -0
  313. agentsec/guards/jwt_key_source_allowlist.py +262 -0
  314. agentsec/guards/k8s_allow_privilege_escalation.py +190 -0
  315. agentsec/guards/k8s_automount_serviceaccount_token.py +85 -0
  316. agentsec/guards/k8s_default_namespace.py +131 -0
  317. agentsec/guards/k8s_docker_sock_mount.py +79 -0
  318. agentsec/guards/k8s_host_namespace_sharing.py +90 -0
  319. agentsec/guards/k8s_hostpath_writable_mount.py +215 -0
  320. agentsec/guards/k8s_privileged_capabilities.py +136 -0
  321. agentsec/guards/k8s_privileged_container.py +79 -0
  322. agentsec/guards/k8s_rbac_anonymous_binding.py +106 -0
  323. agentsec/guards/k8s_rbac_cluster_admin_binding.py +145 -0
  324. agentsec/guards/k8s_rbac_dangerous_verb.py +426 -0
  325. agentsec/guards/k8s_rbac_wildcard_rule.py +151 -0
  326. agentsec/guards/k8s_readonly_root_filesystem.py +82 -0
  327. agentsec/guards/k8s_resource_limits_absent.py +128 -0
  328. agentsec/guards/k8s_run_as_non_root.py +91 -0
  329. agentsec/guards/k8s_seccomp_apparmor_unconfined.py +112 -0
  330. agentsec/guards/k8s_unmasked_proc_mount.py +96 -0
  331. agentsec/guards/k8s_unsafe_sysctl.py +159 -0
  332. agentsec/guards/keylogging_pattern.py +165 -0
  333. agentsec/guards/kinesis_stream_not_encrypted.py +129 -0
  334. agentsec/guards/kms_key_disabled.py +108 -0
  335. agentsec/guards/kms_key_rotation_not_enabled.py +145 -0
  336. agentsec/guards/langchain_load_prompt.py +187 -0
  337. agentsec/guards/langchain_prompt_template_injection.py +202 -0
  338. agentsec/guards/langchain_serialization.py +149 -0
  339. agentsec/guards/langchain_unsafe_chain.py +193 -0
  340. agentsec/guards/ldap_injection.py +142 -0
  341. agentsec/guards/lethal_trifecta_guard.py +31 -0
  342. agentsec/guards/llm_input_size_cap.py +266 -0
  343. agentsec/guards/llm_json_output_unvalidated.py +445 -0
  344. agentsec/guards/llm_output_html_sink.py +288 -0
  345. agentsec/guards/llm_output_secrets_unscanned.py +322 -0
  346. agentsec/guards/llm_output_to_sink.py +301 -0
  347. agentsec/guards/llm_query_engine_execution.py +412 -0
  348. agentsec/guards/llm_rate_limit_absent.py +277 -0
  349. agentsec/guards/llm_response_logged.py +158 -0
  350. agentsec/guards/llm_tool_dynamic_dispatch.py +300 -0
  351. agentsec/guards/llm_tool_result_leak.py +546 -0
  352. agentsec/guards/log_injection.py +347 -0
  353. agentsec/guards/markdown_render_xss.py +276 -0
  354. agentsec/guards/mass_assignment.py +207 -0
  355. agentsec/guards/matview_exposed.py +266 -0
  356. agentsec/guards/mcp_apps_ui_isolation.py +185 -0
  357. agentsec/guards/mcp_config_security.py +1578 -0
  358. agentsec/guards/mcp_env_placeholder_exfil.py +441 -0
  359. agentsec/guards/mcp_hardcoded_credential.py +314 -0
  360. agentsec/guards/mcp_marketplace_fetch_stdio_spawn.py +296 -0
  361. agentsec/guards/mcp_noauth_default.py +405 -0
  362. agentsec/guards/mcp_oauth_flow_hardening.py +799 -0
  363. agentsec/guards/mcp_oauth_scope_creep.py +197 -0
  364. agentsec/guards/mcp_overprivileged_scope.py +157 -0
  365. agentsec/guards/mcp_raw_execution_tool_name.py +201 -0
  366. agentsec/guards/mcp_routing_desync.py +288 -0
  367. agentsec/guards/mcp_sampling_no_consent.py +289 -0
  368. agentsec/guards/mcp_sandbox_self_disable.py +262 -0
  369. agentsec/guards/mcp_server_card_integrity.py +240 -0
  370. agentsec/guards/mcp_session_id_security.py +207 -0
  371. agentsec/guards/mcp_ssrf_unvalidated_destination.py +366 -0
  372. agentsec/guards/mcp_stateless_migration.py +290 -0
  373. agentsec/guards/mcp_stdio_no_sanitizer.py +326 -0
  374. agentsec/guards/mcp_tasks_lifecycle.py +278 -0
  375. agentsec/guards/mcp_tool_description_injection.py +1811 -0
  376. agentsec/guards/mcp_tool_env_inheritance.py +165 -0
  377. agentsec/guards/mcp_tool_path_traversal.py +530 -0
  378. agentsec/guards/mcp_tool_unverified.py +485 -0
  379. agentsec/guards/mcp_toolgate_asymmetry.py +398 -0
  380. agentsec/guards/mcp_tools_list_unbounded.py +376 -0
  381. agentsec/guards/mcp_transport_dns_rebinding.py +256 -0
  382. agentsec/guards/mcp_transport_flip.py +175 -0
  383. agentsec/guards/mcp_transport_no_auth.py +371 -0
  384. agentsec/guards/mcp_transport_session_unauth.py +263 -0
  385. agentsec/guards/mcp_tunnel_config_security.py +553 -0
  386. agentsec/guards/mcp_twin_route_auth_asymmetry.py +324 -0
  387. agentsec/guards/mcp_unsafe_auth_url_launch.py +248 -0
  388. agentsec/guards/ml_artifact_committed.py +104 -0
  389. agentsec/guards/ml_gguf_template_injection.py +471 -0
  390. agentsec/guards/ml_keras_lambda_rce.py +589 -0
  391. agentsec/guards/ml_model_provenance.py +305 -0
  392. agentsec/guards/ml_onnx_external_data.py +534 -0
  393. agentsec/guards/ml_pickle_dangerous_global.py +510 -0
  394. agentsec/guards/msk_cluster_transit_encryption_disabled.py +210 -0
  395. agentsec/guards/multi_agent_prompt_origin.py +405 -0
  396. agentsec/guards/next_api_route_auth_missing.py +249 -0
  397. agentsec/guards/next_public_client_secret.py +145 -0
  398. agentsec/guards/next_server_action_no_auth.py +172 -0
  399. agentsec/guards/no_cache_on_sensitive.py +765 -0
  400. agentsec/guards/no_pan_stored.py +151 -0
  401. agentsec/guards/nosql_injection_js.py +217 -0
  402. agentsec/guards/nosql_metadata_injection.py +156 -0
  403. agentsec/guards/npm_ignore_scripts.py +308 -0
  404. agentsec/guards/npm_install_script_network.py +221 -0
  405. agentsec/guards/obfuscated_payload_execution.py +413 -0
  406. agentsec/guards/open_redirect.py +512 -0
  407. agentsec/guards/opensearch_domain_encryption_disabled.py +209 -0
  408. agentsec/guards/overly_large_regex_range.py +151 -0
  409. agentsec/guards/paramiko_host_key_trust.py +121 -0
  410. agentsec/guards/path_prefix_authz_bypass.py +168 -0
  411. agentsec/guards/path_traversal.py +609 -0
  412. agentsec/guards/payments_user_scope.py +163 -0
  413. agentsec/guards/pdf_embedded_javascript.py +163 -0
  414. agentsec/guards/pg_anon_grant.py +278 -0
  415. agentsec/guards/pg_default_privileges_public.py +153 -0
  416. agentsec/guards/pg_extension_in_public.py +174 -0
  417. agentsec/guards/pg_foreign_table_exposed.py +161 -0
  418. agentsec/guards/pg_function_immutable_reads_session.py +229 -0
  419. agentsec/guards/pg_function_leakproof.py +137 -0
  420. agentsec/guards/pg_function_search_path.py +216 -0
  421. agentsec/guards/pg_graphql_table_exposed.py +182 -0
  422. agentsec/guards/pg_rls_no_policy.py +307 -0
  423. agentsec/guards/pg_rls_not_forced.py +137 -0
  424. agentsec/guards/pg_role_bypassrls.py +126 -0
  425. agentsec/guards/pg_role_bypassrls_membership.py +181 -0
  426. agentsec/guards/pg_security_definer_view.py +287 -0
  427. agentsec/guards/pg_ssl_required.py +207 -0
  428. agentsec/guards/pgmq_queue_exposed_in_api.py +113 -0
  429. agentsec/guards/php_code_injection.py +401 -0
  430. agentsec/guards/php_command_injection.py +246 -0
  431. agentsec/guards/php_extract_superglobal_overwrite.py +124 -0
  432. agentsec/guards/php_file_inclusion.py +182 -0
  433. agentsec/guards/php_preg_replace_eval_modifier.py +122 -0
  434. agentsec/guards/php_reflected_xss.py +141 -0
  435. agentsec/guards/php_sql_injection.py +182 -0
  436. agentsec/guards/php_tls_verify_disabled.py +167 -0
  437. agentsec/guards/php_unsafe_deserialization.py +177 -0
  438. agentsec/guards/pii_llm_roundtrip.py +218 -0
  439. agentsec/guards/plugin_security.py +738 -0
  440. agentsec/guards/policy_exists_rls_disabled.py +216 -0
  441. agentsec/guards/policy_no_role_scope.py +457 -0
  442. agentsec/guards/policy_truncation.py +242 -0
  443. agentsec/guards/postmessage_origin.py +244 -0
  444. agentsec/guards/privileged_field_assignment.py +205 -0
  445. agentsec/guards/prompt_string_interp.py +556 -0
  446. agentsec/guards/proxy_tls_hardening.py +212 -0
  447. agentsec/guards/public_table_rls.py +340 -0
  448. agentsec/guards/pydantic_model_construct.py +245 -0
  449. agentsec/guards/python_supply_chain.py +569 -0
  450. agentsec/guards/rag_isolation.py +314 -0
  451. agentsec/guards/rag_no_instruction_filter.py +892 -0
  452. agentsec/guards/rag_scoped_retrieval.py +291 -0
  453. agentsec/guards/rag_trust_boundary.py +204 -0
  454. agentsec/guards/rate_limit_no_persistent_store.py +237 -0
  455. agentsec/guards/rate_limit_no_user_key.py +206 -0
  456. agentsec/guards/rds_backup_retention_too_short.py +205 -0
  457. agentsec/guards/rds_publicly_accessible.py +139 -0
  458. agentsec/guards/rds_storage_not_encrypted.py +214 -0
  459. agentsec/guards/react_native_insecure_token_storage.py +160 -0
  460. agentsec/guards/redis_glob_pattern_injection.py +181 -0
  461. agentsec/guards/redos.py +549 -0
  462. agentsec/guards/refresh_token_plaintext.py +169 -0
  463. agentsec/guards/regex_html_sanitizer.py +182 -0
  464. agentsec/guards/request_body_size_unbounded.py +219 -0
  465. agentsec/guards/request_model_extra_forbid.py +220 -0
  466. agentsec/guards/response_model_set.py +382 -0
  467. agentsec/guards/reverse_shell_pattern.py +189 -0
  468. agentsec/guards/rls_anon_write_access.py +134 -0
  469. agentsec/guards/rls_auth_email_lockout.py +120 -0
  470. agentsec/guards/rls_auth_role_unknown_literal.py +417 -0
  471. agentsec/guards/rls_auth_uid_unwrapped.py +249 -0
  472. agentsec/guards/rls_auth_users_unbound_exists.py +151 -0
  473. agentsec/guards/rls_current_setting_unqualified.py +135 -0
  474. agentsec/guards/rls_current_user_tenant_key.py +149 -0
  475. agentsec/guards/rls_fkey_to_auth_non_primary.py +136 -0
  476. agentsec/guards/rls_hardcoded_tenant_literal.py +147 -0
  477. agentsec/guards/rls_inverted_auth_check.py +208 -0
  478. agentsec/guards/rls_multiple_permissive_policies.py +157 -0
  479. agentsec/guards/rls_no_user_metadata_claim.py +112 -0
  480. agentsec/guards/rls_partition_inherits_bypass.py +172 -0
  481. agentsec/guards/rls_pattern_match_auth_context.py +143 -0
  482. agentsec/guards/rls_permissive_policy.py +363 -0
  483. agentsec/guards/rls_realtime_published_no_rls.py +160 -0
  484. agentsec/guards/rls_restrictive_only.py +161 -0
  485. agentsec/guards/rls_update_privileged_column.py +368 -0
  486. agentsec/guards/ruby_command_injection.py +261 -0
  487. agentsec/guards/ruby_dangerous_dispatch.py +346 -0
  488. agentsec/guards/ruby_mass_assignment.py +193 -0
  489. agentsec/guards/ruby_sql_injection.py +354 -0
  490. agentsec/guards/ruby_tls_verify_disabled.py +154 -0
  491. agentsec/guards/ruby_unsafe_deserialization.py +188 -0
  492. agentsec/guards/ruby_unsafe_reflection.py +199 -0
  493. agentsec/guards/ruby_weak_crypto.py +125 -0
  494. agentsec/guards/s3_bucket_canned_acl.py +208 -0
  495. agentsec/guards/s3_bucket_insecure_transport_allowed.py +287 -0
  496. agentsec/guards/s3_bucket_policy_wildcard_principal.py +234 -0
  497. agentsec/guards/s3_mfa_delete_disabled.py +283 -0
  498. agentsec/guards/s3_public_access_block_disabled.py +160 -0
  499. agentsec/guards/sagemaker_notebook_not_encrypted.py +126 -0
  500. agentsec/guards/sandbox_denylist_bypass.py +261 -0
  501. agentsec/guards/secret_in_url_query.py +295 -0
  502. agentsec/guards/secret_str_serialized.py +290 -0
  503. agentsec/guards/secrets_manager_default_kms.py +134 -0
  504. agentsec/guards/security_headers.py +133 -0
  505. agentsec/guards/sensitive_columns.py +280 -0
  506. agentsec/guards/sensitive_logging.py +276 -0
  507. agentsec/guards/service_role_key.py +162 -0
  508. agentsec/guards/session_fixation_no_regenerate.py +136 -0
  509. agentsec/guards/session_no_csrf.py +256 -0
  510. agentsec/guards/setup_network_call.py +203 -0
  511. agentsec/guards/sfn_observability.py +198 -0
  512. agentsec/guards/shared_resource_authz.py +245 -0
  513. agentsec/guards/skill_poisoning.py +340 -0
  514. agentsec/guards/skill_untrusted_exec_path.py +314 -0
  515. agentsec/guards/slopsquatting.py +312 -0
  516. agentsec/guards/sns_topic_not_encrypted.py +112 -0
  517. agentsec/guards/sql_race_check_then_insert.py +296 -0
  518. agentsec/guards/sqlalchemy_text_parameterized.py +153 -0
  519. agentsec/guards/sqs_queue_not_encrypted.py +123 -0
  520. agentsec/guards/ssh_allowlist_absent.py +99 -0
  521. agentsec/guards/sshd_hardening.py +142 -0
  522. agentsec/guards/ssrf_bracketed_ipv6_bypass.py +260 -0
  523. agentsec/guards/ssrf_dns_rebind_toctou.py +233 -0
  524. agentsec/guards/ssrf_general.py +531 -0
  525. agentsec/guards/ssrf_ipv6_bypass.py +113 -0
  526. agentsec/guards/ssrf_redirect_bypass.py +218 -0
  527. agentsec/guards/ssti.py +215 -0
  528. agentsec/guards/staticfiles_broad_mount.py +126 -0
  529. agentsec/guards/storage_no_rls.py +278 -0
  530. agentsec/guards/string_format_injection.py +169 -0
  531. agentsec/guards/stripe_webhook.py +696 -0
  532. agentsec/guards/supabase_anon_key_rls_reachable.py +185 -0
  533. agentsec/guards/supabase_filter_injection.py +185 -0
  534. agentsec/guards/supabase_storage_public.py +284 -0
  535. agentsec/guards/supabase_vault_exposure.py +883 -0
  536. agentsec/guards/supabase_vault_plaintext_leak.py +357 -0
  537. agentsec/guards/svg_embedded_script.py +113 -0
  538. agentsec/guards/system_prompt_exposure.py +375 -0
  539. agentsec/guards/system_prompt_leak.py +164 -0
  540. agentsec/guards/target_blank_noopener.py +210 -0
  541. agentsec/guards/terraform_hardcoded_secret_literal.py +362 -0
  542. agentsec/guards/tls_verify_disabled.py +315 -0
  543. agentsec/guards/token_in_localstorage.py +172 -0
  544. agentsec/guards/tool_callback_enforcement.py +1022 -0
  545. agentsec/guards/tool_chaining_exfil.py +208 -0
  546. agentsec/guards/trust_boundary.py +239 -0
  547. agentsec/guards/trusted_host_absent.py +143 -0
  548. agentsec/guards/truthy_ownership_check.py +341 -0
  549. agentsec/guards/unauthenticated_file_download.py +217 -0
  550. agentsec/guards/unawaited_async_truthy.py +209 -0
  551. agentsec/guards/unrestricted_file_upload.py +93 -0
  552. agentsec/guards/unsafe_deserialization.py +423 -0
  553. agentsec/guards/untrusted_package_install_source.py +181 -0
  554. agentsec/guards/upload_no_size_limit.py +219 -0
  555. agentsec/guards/upstream_response_unvalidated.py +368 -0
  556. agentsec/guards/version_floors.json +590 -0
  557. agentsec/guards/vite_client_secret.py +161 -0
  558. agentsec/guards/vite_sourcemap_prod.py +180 -0
  559. agentsec/guards/vscode_tasks_auto_exec.py +471 -0
  560. agentsec/guards/weak_crypto.py +216 -0
  561. agentsec/guards/weak_password_length_check.py +134 -0
  562. agentsec/guards/weak_secret_key_literal.py +151 -0
  563. agentsec/guards/webhook_idempotency.py +183 -0
  564. agentsec/guards/webhook_signature_not_verified.py +478 -0
  565. agentsec/guards/websocket_no_auth.py +252 -0
  566. agentsec/guards/websocket_origin.py +175 -0
  567. agentsec/guards/xpath_injection.py +118 -0
  568. agentsec/guards/xxe_safe.py +92 -0
  569. agentsec/guards/zip_bomb.py +175 -0
  570. agentsec/guards/zip_slip.py +273 -0
  571. agentsec/hostaudit/__init__.py +13 -0
  572. agentsec/hostaudit/audit.py +353 -0
  573. agentsec/hostaudit/probes.py +549 -0
  574. agentsec/ingest.py +396 -0
  575. agentsec/intake.py +241 -0
  576. agentsec/js_harden.py +163 -0
  577. agentsec/k8s.py +85 -0
  578. agentsec/kev.py +105 -0
  579. agentsec/live.py +534 -0
  580. agentsec/livescan.py +288 -0
  581. agentsec/net.py +231 -0
  582. agentsec/patterns.py +16 -0
  583. agentsec/pins.py +174 -0
  584. agentsec/prioritize.py +114 -0
  585. agentsec/python_harden.py +234 -0
  586. agentsec/reachability.py +183 -0
  587. agentsec/registry.py +1140 -0
  588. agentsec/report.py +298 -0
  589. agentsec/runners/__init__.py +8 -0
  590. agentsec/runners/bandit.py +88 -0
  591. agentsec/runners/base.py +363 -0
  592. agentsec/runners/eslint.py +217 -0
  593. agentsec/runners/gitleaks.py +69 -0
  594. agentsec/runners/go_osv_hygiene.py +414 -0
  595. agentsec/runners/hadolint.py +80 -0
  596. agentsec/runners/node_audit.py +160 -0
  597. agentsec/runners/pip_audit.py +107 -0
  598. agentsec/runners/react_doctor.py +198 -0
  599. agentsec/runners/scorecard.py +161 -0
  600. agentsec/runners/semgrep.py +127 -0
  601. agentsec/runners/trivy.py +230 -0
  602. agentsec/setup.py +705 -0
  603. agentsec/sql_state.py +214 -0
  604. agentsec/ssrf_fetch.py +175 -0
  605. agentsec/targets.py +116 -0
  606. agentsec/text_sanitize.py +188 -0
  607. agentsec/textio.py +22 -0
  608. agentsec/tool_version.py +200 -0
  609. agentsec/tooling.py +227 -0
  610. agentsec/triage.py +165 -0
  611. agentsec/triage_cli.py +465 -0
  612. agentsec/update_check.py +262 -0
  613. agentsec/walk.py +619 -0
  614. ai_agent_security-0.22.2.dist-info/METADATA +267 -0
  615. ai_agent_security-0.22.2.dist-info/RECORD +618 -0
  616. ai_agent_security-0.22.2.dist-info/WHEEL +4 -0
  617. ai_agent_security-0.22.2.dist-info/entry_points.txt +2 -0
  618. ai_agent_security-0.22.2.dist-info/licenses/LICENSE +202 -0
agentsec/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """agentsec — stack-aware security audit tool for FastAPI + React + Postgres + LLM/RAG apps."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+
7
+
8
+ def _checklist_version() -> str:
9
+ """The package version IS the checklist registry version (single source of truth —
10
+ see pyproject `[tool.hatch.version]`). Read straight from the shipped JSON so
11
+ `__version__` always reflects the on-disk checklist, even in an editable checkout."""
12
+ try:
13
+ data = json.loads(
14
+ (Path(__file__).parent / "checklist" / "checklist.json").read_text(encoding="utf-8")
15
+ )
16
+ return str(data["version"])
17
+ except (OSError, ValueError, KeyError):
18
+ return "0+unknown"
19
+
20
+
21
+ __version__ = _checklist_version()
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Canonical repo identity: the public repository users install from, pin in CI and file issues
25
+ # on. The ONE place to change if it ever moves; Python code imports these (including
26
+ # scripts/cut-release.py and scripts/regen-versions-json.py).
27
+ #
28
+ # Non-Python files can't import this, so they are separate switch points. When
29
+ # you flip the slug below, also update (`git grep -i "<old owner>/ai-agent-security"`):
30
+ # - README.md (the "Run it in CI" `uses:` snippet, the dev-install line,
31
+ # and every absolute doc link)
32
+ # - pyproject.toml (`[project.urls]`, shown on the PyPI project page)
33
+ # - docs/user-guide.md §16 (the action's `uses:` line and the pre-commit `repo:` line;
34
+ # action.yml itself names no slug: it reads
35
+ # `github.action_repository` for its feedback links)
36
+ # - BREAKING_CHANGES.md, docs/infographic/*.html, wiki/ (migration recipes, install hints, links)
37
+ # - .github/ISSUE_TEMPLATE/config.yml (`contact_links` — GitHub requires ABSOLUTE urls
38
+ # here, so the Discussions/SECURITY.md links cannot
39
+ # be made relative and are a real switch point)
40
+ # tests/test_ci_library.py pins the expected URL, and tests/test_packaging.py checks every public
41
+ # text file's repo pointers against this constant: your switch-point tripwires.
42
+ # ---------------------------------------------------------------------------
43
+ AGENTSEC_REPO_SLUG = "Zard-Lab/ai-agent-security"
44
+ AGENTSEC_REPO_URL = f"https://github.com/{AGENTSEC_REPO_SLUG}"
agentsec/__main__.py ADDED
@@ -0,0 +1,13 @@
1
+ """Enable `python -m agentsec` (delegates to the console-script entry point).
2
+
3
+ The packaged console script is `agentsec` (pyproject `[project.scripts]`), but
4
+ `python -m agentsec` is a natural thing to type — and CI workflows reach for it
5
+ when the script isn't on PATH. Without this module that form fails with
6
+ "No module named agentsec.__main__"; this makes the two invocations equivalent.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from agentsec.cli import main
11
+
12
+ if __name__ == "__main__":
13
+ raise SystemExit(main())
agentsec/advisor.py ADDED
@@ -0,0 +1,334 @@
1
+ """Exclude advisor — suggest (never apply) directories a repo may want to demote or exclude.
2
+
3
+ agentsec keeps its *global* non-product lists deliberately tiny (universal conventions only — see
4
+ `detect.NONPRODUCT_DIR_ALT`). Everything repo-specific (`evals/`, offline `scripts/`, generated
5
+ dumps, vendored trees) is opt-in per repo. This module is the **discovery layer** that bridges the
6
+ gap: it scores each directory by how likely it is non-product and proposes the strong candidates,
7
+ annotated with *why*, for the user to opt into `.agentsec/config.json` (via `config.write_repo_config`).
8
+
9
+ **Robustness via corroboration, not names.** A directory is suggested only when signals from **≥2
10
+ independent axes** agree, including **≥1 robust axis** (import-unreachability, structural shape, or
11
+ already-excluded). A name match alone never suggests — so a repo that genuinely *serves* an `evals/`
12
+ endpoint (import-reachable, real route files, not gitignored) is never proposed.
13
+
14
+ Each candidate is classified **demote** (still scanned, ranked low — tests/eval/script source where a
15
+ real bug must stay visible) or **exclude** (hard drop — vendored/generated/dead code). The advisor is
16
+ advisory only: it returns `Candidate`s; persisting them is a separate, consent-gated step (the CLI).
17
+
18
+ The hardwired Layer-1 trees (`tests/`, `fixtures/`, `migrations/`, ...) are never *proactive*
19
+ candidates (already rank-demoted by convention), but Layer 1 never DROPS an external scanner's
20
+ findings, so a noisy tests tree still counts toward report totals. The reactive half therefore
21
+ proposes archiving such a tree once a completed audit proves it holds an all-low/info cluster,
22
+ and the CLI discloses the trees on proactive runs (#716).
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import re
27
+ from dataclasses import dataclass, field
28
+ from pathlib import Path
29
+
30
+ from agentsec.config import _DEFAULT_NONPRODUCT_PATHS
31
+ from agentsec.detect import ARCHIVE_SEGMENTS, StackProfile
32
+ from agentsec.findings import Finding
33
+ from agentsec.guards.base import is_nonproduct_path
34
+ from agentsec.reachability import unreachable_dirs
35
+ from agentsec.walk import GitignoreMatcher, walk_files
36
+
37
+ # Directory-name hints (weak on their own — a name only nudges, never decides).
38
+ _NAME_HINTS = (
39
+ ARCHIVE_SEGMENTS
40
+ | _DEFAULT_NONPRODUCT_PATHS
41
+ | {
42
+ "test", "tests", "__tests__", "__mocks__", "mocks", "fixture", "fixtures",
43
+ "example", "examples", "sample", "samples", "e2e", "spec", "specs", "stories",
44
+ ".storybook", "sandbox", "playground", "demo", "demos", "notebook", "notebooks",
45
+ "bench", "benchmark", "benchmarks", "script", "tooling", "doc", "eval", "judge",
46
+ "cypress",
47
+ }
48
+ )
49
+ # Names that classify a candidate as a HARD-exclude (drop) rather than demote.
50
+ _EXCLUDE_NAMES = ARCHIVE_SEGMENTS | {"vendor", "vendored", "third_party", "dist", "build", "out", "target"}
51
+
52
+ # Files whose mere shape marks a directory as non-product (test/notebook/story tooling).
53
+ _NONPRODUCT_FILE_RE = re.compile(
54
+ r"(?:^test_.*\.py$|.*_test\.py$|^conftest\.py$|^__main__\.py$"
55
+ r"|.*\.(?:test|spec|stories)\.[a-z0-9]+$)",
56
+ re.IGNORECASE,
57
+ )
58
+ # Headers that mark a generated/vendored artifact (read from the file's first lines).
59
+ _GENERATED_HEADER_RE = re.compile(
60
+ r"DO NOT EDIT|@generated|autogenerated|auto-generated|generated by|pg_dump|supabase db dump",
61
+ re.IGNORECASE,
62
+ )
63
+ _GENERATED_SNIFF_LINES = 25
64
+
65
+
66
+ @dataclass
67
+ class Candidate:
68
+ """One suggested directory, with the evidence behind the suggestion."""
69
+
70
+ directory: str # repo-relative, forward-slash
71
+ kind: str # "demote" | "exclude"
72
+ confidence: str # "high" | "heuristic"
73
+ signals: list[str] = field(default_factory=list) # human-readable "why" lines
74
+ finding_count: int = 0 # findings currently under this dir (reactive)
75
+ severity_mix: dict[str, int] = field(default_factory=dict)
76
+
77
+
78
+ def _matcher(root: Path, name: str) -> GitignoreMatcher | None:
79
+ """A `.gitignore`/`.dockerignore` matcher for the repo root (both share the syntax)."""
80
+ p = root / name
81
+ if not p.is_file():
82
+ return None
83
+ try:
84
+ return GitignoreMatcher.from_text(p.read_text(encoding="utf-8", errors="ignore"))
85
+ except OSError:
86
+ return None
87
+
88
+
89
+ def _is_generated(members: list[Path]) -> bool:
90
+ for f in members:
91
+ try:
92
+ with f.open(encoding="utf-8", errors="ignore") as fh:
93
+ head = "".join(next(fh, "") for _ in range(_GENERATED_SNIFF_LINES))
94
+ except OSError:
95
+ continue
96
+ if _GENERATED_HEADER_RE.search(head):
97
+ return True
98
+ return False
99
+
100
+
101
+ def _dir_members(root: Path) -> dict[str, list[Path]]:
102
+ """Map every repo-relative directory (that holds files) to its immediate file members.
103
+
104
+ Walks **past `.gitignore`** (`respect_gitignore=False`) so gitignored dirs are still visible —
105
+ being gitignored is itself a non-product signal, and the advisor must be able to surface them.
106
+ Vendored/build dirs and nested worktrees (`walk.DEFAULT_EXCLUDE_DIRS`) are still skipped."""
107
+ by_dir: dict[str, list[Path]] = {}
108
+ for f in walk_files(root, respect_gitignore=False):
109
+ rel = f.relative_to(root).parent.as_posix()
110
+ if rel in (".", ""):
111
+ continue
112
+ by_dir.setdefault(rel, []).append(f)
113
+ return by_dir
114
+
115
+
116
+ def _score_dir(
117
+ reldir: str,
118
+ members: list[Path],
119
+ unreachable: set[str],
120
+ gitignore: GitignoreMatcher | None,
121
+ dockerignore: GitignoreMatcher | None,
122
+ ) -> Candidate | None:
123
+ """Apply the corroboration rule to one directory. Returns a Candidate or None (not suggested)."""
124
+ seg = reldir.rsplit("/", 1)[-1].lower()
125
+ signals: list[str] = []
126
+
127
+ # --- robust axes ---
128
+ robust = 0
129
+ if reldir in unreachable:
130
+ robust += 1
131
+ signals.append("not imported by any served entrypoint (import-unreachable)")
132
+ n_np = sum(1 for m in members if _NONPRODUCT_FILE_RE.match(m.name) or m.suffix == ".ipynb")
133
+ structural = bool(members) and n_np * 2 >= len(members) and n_np > 0
134
+ if structural:
135
+ robust += 1
136
+ signals.append(f"{n_np}/{len(members)} files are test/notebook/story shape")
137
+ excluded = bool(
138
+ (gitignore and gitignore.match(reldir, is_dir=True))
139
+ or (dockerignore and dockerignore.match(reldir, is_dir=True))
140
+ )
141
+ if excluded:
142
+ robust += 1
143
+ signals.append("already ignored by .gitignore/.dockerignore")
144
+
145
+ # --- weak axes ---
146
+ weak = 0
147
+ if seg in _NAME_HINTS or seg in _EXCLUDE_NAMES:
148
+ weak += 1
149
+ signals.append(f"directory name '{seg}' is a common non-product convention")
150
+ generated = _is_generated(members)
151
+ if generated:
152
+ weak += 1
153
+ signals.append("contains a generated/vendored file header (DO NOT EDIT / pg_dump / @generated)")
154
+
155
+ # Corroboration: suggest only with >=2 axes total AND >=1 robust axis. Name/header alone never suggests.
156
+ if robust == 0 or (robust + weak) < 2:
157
+ return None
158
+
159
+ kind = "exclude" if (generated or seg in _EXCLUDE_NAMES) else "demote"
160
+ confidence = "high" if (excluded or generated or seg in _EXCLUDE_NAMES or robust >= 2) else "heuristic"
161
+ return Candidate(directory=reldir, kind=kind, confidence=confidence, signals=signals)
162
+
163
+
164
+ def suggest_proactive(root: Path, profile: StackProfile) -> list[Candidate]:
165
+ """Walk-based suggestions (no scan needed). The proactive half of the advisor."""
166
+ from agentsec.config import load_repo_config
167
+
168
+ cfg = load_repo_config(root)
169
+ already = cfg.archive_segments | cfg.nonproduct_segments # don't re-suggest opted-in trees
170
+ unreachable = unreachable_dirs(root, profile)
171
+ gitignore = _matcher(root, ".gitignore")
172
+ dockerignore = _matcher(root, ".dockerignore")
173
+ out: list[Candidate] = []
174
+ for reldir, members in sorted(_dir_members(root).items()):
175
+ # Skip dirs already covered, so suggesting them is just noise: (a) anything under a tree the
176
+ # repo already opted into config (segment match, so a nested `old/x/tools` is skipped too), and
177
+ # (b) the hardwired Layer-1 conventions (tests/fixtures/migrations/…). The advisor's value is
178
+ # the dirs NOT already covered (evals/, scripts/, repo-specific trees). NOTE: (b) is only
179
+ # "covered" for guards; external-scanner findings under a Layer-1 tree are rank-demoted, never
180
+ # dropped, so `_builtin_tree_candidates` (reactive) proposes archiving such a tree when a scan
181
+ # proves it noisy, and the CLI discloses these trees on proactive runs (#716).
182
+ if (set(reldir.lower().split("/")) & already) or is_nonproduct_path(reldir + "/_"):
183
+ continue
184
+ cand = _score_dir(reldir, members, unreachable, gitignore, dockerignore)
185
+ if cand is not None:
186
+ out.append(cand)
187
+ return _dedupe_nested(out)
188
+
189
+
190
+ def builtin_demoted_roots(root: Path) -> list[str]:
191
+ """Top-most directories covered by the hardwired Layer-1 conventions (`tests/`, `fixtures/`,
192
+ `migrations/`, ...): exactly the trees `suggest_proactive` deliberately never suggests. Exposed
193
+ so the CLI can DISCLOSE them instead of silently omitting them: Layer 1 only rank-demotes
194
+ external-scanner findings (the DROP half is per-guard), so these trees still count toward the
195
+ report totals (#716)."""
196
+ roots: set[str] = set()
197
+ for reldir in _dir_members(root):
198
+ parts = reldir.split("/")
199
+ for i in range(1, len(parts) + 1):
200
+ prefix = "/".join(parts[:i])
201
+ if is_nonproduct_path(prefix + "/_"):
202
+ roots.add(prefix)
203
+ break
204
+ return sorted(roots)
205
+
206
+
207
+ def _dedupe_nested(cands: list[Candidate]) -> list[Candidate]:
208
+ """Drop a candidate whose parent dir is already a candidate of the same kind (suggest the top tree)."""
209
+ by_dir = {c.directory: c for c in cands}
210
+ out: list[Candidate] = []
211
+ for c in cands:
212
+ parts = c.directory.split("/")
213
+ covered = any(
214
+ "/".join(parts[:i]) in by_dir and by_dir["/".join(parts[:i])].kind == c.kind
215
+ for i in range(1, len(parts))
216
+ )
217
+ if not covered:
218
+ out.append(c)
219
+ return out
220
+
221
+
222
+ # --- reactive overlay: layer real scan output onto the proactive candidates -------------------
223
+
224
+
225
+ def _location_dir(location: str) -> str:
226
+ """The repo-relative directory of a finding location (`a/b/x.py:9` -> `a/b`)."""
227
+ path = (location or "").replace("\\", "/").split(":", 1)[0]
228
+ return path.rsplit("/", 1)[0] if "/" in path else ""
229
+
230
+
231
+ def _under(candidate_dir: str, location: str) -> bool:
232
+ d = _location_dir(location)
233
+ return d == candidate_dir or d.startswith(candidate_dir + "/")
234
+
235
+
236
+ # Checks whose findings are secret-detection hits: never advise archiving over one, whatever its
237
+ # severity (an archive is a hard DROP, and a committed secret in a tests tree is still a leak).
238
+ # Today this veto is redundant defense-in-depth: the gitleaks runner emits severity="high" for
239
+ # everything, so the medium+ gate above already blocks it. Kept deliberately, so the guarantee
240
+ # survives if that severity model ever changes (#724 review).
241
+ _SECRET_CHECK_IDS = frozenset({"gitleaks"})
242
+
243
+
244
+ def _builtin_tree_candidates(root: Path, findings: list[Finding]) -> list[Candidate]:
245
+ """Archive proposals for the hardwired Layer-1 trees, driven by scan evidence only (#716).
246
+
247
+ `suggest_proactive` skips these trees ("already covered"), which is true for guards but not for
248
+ external scanners: their findings are rank-demoted, never dropped, so a tests tree can dominate
249
+ the report totals while staying invisible to the advisor (851 of 866 noise-floor findings on the
250
+ reference RAG-app run). A demote proposal would be a no-op (the rank-demote already applies), so the only
251
+ meaningful proposal is `exclude` (`archive_paths`), gated conservatively: never for a clean tree,
252
+ never over a medium+ finding (stricter than the product-reachable veto: an archive drops
253
+ EVERYTHING under the tree), and never over a secret-detection hit."""
254
+ from agentsec.config import load_repo_config
255
+
256
+ cfg = load_repo_config(root)
257
+ # Skip only ARCHIVED trees (their findings are already dropped). A Layer-1 tree in
258
+ # `nonproduct_paths` is deliberately still proposed: that config entry is a no-op for it (the
259
+ # rank-demote already applies by convention, and the counts never consult the demote stamp),
260
+ # and it is the natural-but-ineffective hand-fix the #716 reporter applied. Skipping on it
261
+ # would recreate the exact silent dead end this function exists to close (#724 review).
262
+ already = cfg.archive_segments
263
+ total_low = sum(1 for f in findings if f.severity in ("low", "info"))
264
+ out: list[Candidate] = []
265
+ for reldir in builtin_demoted_roots(root):
266
+ if set(reldir.lower().split("/")) & already:
267
+ continue
268
+ under = [f for f in findings if _under(reldir, f.location)]
269
+ if not under:
270
+ continue # a clean built-in tree is never suggested (the original design intent, kept)
271
+ if any(f.severity not in ("low", "info") for f in under):
272
+ continue # a medium+ finding here: surface it, never suggest dropping the tree
273
+ if any(f.check_id in _SECRET_CHECK_IDS for f in under):
274
+ continue
275
+ mix: dict[str, int] = {}
276
+ for f in under:
277
+ mix[f.severity] = mix.get(f.severity, 0) + 1
278
+ share = round(100 * len(under) / total_low) if total_low else 0
279
+ out.append(Candidate(
280
+ directory=reldir,
281
+ kind="exclude",
282
+ # High confidence only when the tree is the report's dominant low-severity source.
283
+ confidence="high" if 2 * len(under) >= total_low else "heuristic",
284
+ signals=[
285
+ "already rank-demoted by the built-in conventions, but scanner findings here still "
286
+ "count toward report totals",
287
+ f"{len(under)} finding(s) here, all low/info ({share}% of the report's "
288
+ f"{total_low} low-severity finding(s))",
289
+ "archive_paths is a hard DROP: future findings under this tree (secrets included) "
290
+ "would no longer be reported",
291
+ ],
292
+ finding_count=len(under),
293
+ severity_mix=mix,
294
+ ))
295
+ return out
296
+
297
+
298
+ def suggest(root: Path, profile: StackProfile, findings: list[Finding] | None = None) -> list[Candidate]:
299
+ """The advisor entrypoint. Proactive walk-based candidates, plus — when `findings` from a completed
300
+ audit are supplied — a reactive overlay that fills each candidate's finding stats, **vetoes** any
301
+ candidate that holds a real high-severity *product* finding (Sonar conservatism: never suggest
302
+ sweeping a serious bug under the rug), and boosts confidence when the dir's findings are an
303
+ all-low-priority, few-guard cluster (a measured non-product signature, not a guessed name).
304
+ The hardwired Layer-1 trees, which the proactive half never suggests, are appended here as
305
+ archive candidates when the scan shows an all-low/info cluster under them (#716)."""
306
+ cands = suggest_proactive(root, profile)
307
+ if not findings:
308
+ return cands
309
+
310
+ # Lazy import: `prioritize` imports `findings`, which would otherwise risk an import cycle.
311
+ from agentsec.prioritize import reachability
312
+
313
+ out: list[Candidate] = []
314
+ for c in cands:
315
+ under = [f for f in findings if _under(c.directory, f.location)]
316
+ # Veto: a serious bug in still-product-reachable code here — surface it, don't suggest hiding it.
317
+ if any(f.severity in ("critical", "high") and reachability(f) == "product" for f in under):
318
+ continue
319
+ c.finding_count = len(under)
320
+ mix: dict[str, int] = {}
321
+ for f in under:
322
+ mix[f.severity] = mix.get(f.severity, 0) + 1
323
+ c.severity_mix = mix
324
+ if under:
325
+ low = sum(1 for f in under if f.severity in ("low", "info"))
326
+ guards = {f.check_id for f in under}
327
+ c.signals.append(
328
+ f"{len(under)} finding(s) here from {len(guards)} guard(s), {low} low-severity"
329
+ )
330
+ if c.confidence != "high" and low == len(under) and len(guards) <= 2:
331
+ c.confidence = "high" # measured: an all-low-severity, few-guard cluster
332
+ out.append(c)
333
+ out.extend(_builtin_tree_candidates(root, findings))
334
+ return out
@@ -0,0 +1,13 @@
1
+ """The AI/agentic reasoning layer — the gap OSS scanners don't fill.
2
+
3
+ - `semgrep-rules/` : a custom Semgrep pack for LLM/RAG/agent sinks (Pydantic-AI
4
+ and LangChain), consumed by the SemgrepRunner via `--config`.
5
+ - `lethal_trifecta.py` : an architecture analyzer for Simon Willison's "lethal
6
+ trifecta" (private data + untrusted content + external comms) that produces
7
+ findings + a reasoning scaffold for the Claude /security skill.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+
13
+ SEMGREP_RULES_DIR = Path(__file__).parent / "semgrep-rules"