Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(apex): health findings for SOQL injection, missing sharing, hardcoded record Ids and SeeAllData tests (#4442)

Raghav Chamadiya33693310eb6e
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 07088ca11..486aebd44 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -104,8 +104,8 @@ Each marker is a stateless class implementing the `Biomarker` Protocol
### The full roster
-`biomarkers/registry.py` registers **54 detectors**; counting the three governance
-findings written by the additive pass (`governance.py`) there are **57 marker ids**. They
+`biomarkers/registry.py` registers **58 detectors**; counting the three governance
+findings written by the additive pass (`governance.py`) there are **61 marker ids**. They
divide by what each is permitted to affect:
| Group | Count | Scores into |
@@ -114,7 +114,7 @@ divide by what each is permitted to affect:
| Performance | 22 | `performance` only |
| SQL | 3 | `maintainability` only |
| Governance | 3 | nothing: the finding surfaces, the score is untouched |
-| Advisory | 5 | nothing: measured by construction, out of impact-ranked lists unless requested |
+| Advisory | 9 | nothing: measured by construction, out of impact-ranked lists unless requested |
The authority is `scoring._BIOMARKER_DIMENSIONS`. An unlisted biomarker defaults into
`defect`, so every `sql_*` and performance name is listed explicitly: an omission would
@@ -162,6 +162,10 @@ the defect weight (§6.1), "maint" the maintainability and "perf" the performanc
| `sql_select_star` | SQL | `SELECT *` | Low | maint 0.7 |
| `sql_update_delete_without_where` | SQL | `UPDATE` or `DELETE` with no `WHERE` | Medium | maint 0.7 |
| `sql_cartesian_join` | Performance | A cartesian join in SQL | Medium | perf 0.6 |
+| `apex_soql_injection` | Apex | A String from outside the method spliced into a quoted literal of a dynamic query, unescaped | High; non-test Apex | Advisory |
+| `apex_missing_sharing` | Apex | A top-level class with queries or updates and no sharing keyword | Medium; not subclasses, inner or test classes | Advisory |
+| `apex_hardcoded_id` | Apex | A record Id as a string literal | Medium; 18 chars with a valid checksum or 15 on a standard prefix; non-test Apex | Advisory |
+| `apex_see_all_data` | Apex | `@IsTest(SeeAllData=true)` | Low | Advisory |
| `io_in_loop` | Performance | I/O per loop iteration (N+1), across functions | Medium | perf 1.0 |
| `string_concat_in_loop` | Performance | `+=` of a provable string in a loop | Low | perf 0.7 |
| `blocking_sync_in_async` | Performance | A sync blocking call in `async def` | Medium; Python, Rust, C#, Kotlin, Scala | perf 0.7 |
@@ -320,6 +324,8 @@ language because it does not transfer:
dropping it left defect AUC unchanged on the 66-repo corpus.
- `untested_complexity`: complexity and coverage already deduct elsewhere
([user guide](../layers/TEST_INTELLIGENCE.md#untested-complexity)).
+- The four `apex_*` markers: every finding on 13 Salesforce repos hand-read, none
+ wrong; no defect corpus covers Apex yet.
### 5.5 Worked example: the dispatch rule
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index 2ce7bff83..ffa68ce99 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -144,7 +144,7 @@ survives re-indexing, and a re-detected `resolved` finding reopens.
### Detector families
-The 54 detectors fall into families whose caps keep any one from dominating a file.
+The 58 detectors fall into families whose caps keep any one from dominating a file.
Every id with its threshold and weight:
[the full roster](../architecture/code-health.md#the-full-roster).
@@ -158,11 +158,12 @@ Every id with its threshold and weight:
| Test coverage | 4 | 2.0 + 2.0 | Untested hotspots, coverage gaps, uncovered lines (needs a report), untested complex functions (advisory) |
| Test quality | 4 | 0.5 | Oversized or duplicated assertion blocks; two advisory markers |
| SQL | 4 | none | Complex SQL, `SELECT *`, `UPDATE`/`DELETE` with no `WHERE`, cartesian joins |
+| Apex | 4 | none | SOQL injection, a class with queries and no sharing keyword, hardcoded record Ids, `SeeAllData=true` tests; all advisory |
| Performance | 21 | none | See [PERFORMANCE.md](PERFORMANCE.md) |
- Caps are code-health caps; SQL deducts only in maintainability (2.0) and performance
findings, cartesian joins included, only in performance risk (2.0).
-- Twenty-four detectors move code health. Five are advisory: listed with zero impact,
+- Twenty-four detectors move code health. Nine are advisory: listed with zero impact,
out of impact-ranked lists unless you ask for the advisory dimension. Three governance
findings from the [decisions layer](DECISIONS.md) never deduct.
- `dry_violation` and `duplicated_assertion_block` stay off every default surface (overview, priorities, MCP, REST lists) until
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 6fe20b1c9..8504a935a 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -88,7 +88,8 @@ Apex (`.cls`, `.trigger`, `.apex`) is parsed for symbols, heritage and calls,
resolved case-insensitively within each sfdx project's namespace; its dead-code
findings are review-only. Apex test coverage from the Salesforce CLI is read as a
coverage report ([formats](TEST_INTELLIGENCE.md#supported-formats)). Health covers Apex
-complexity, class cohesion, and SOQL, DML and callouts inside loops.
+complexity, class cohesion, and SOQL, DML and callouts inside loops; SOQL injection, missing
+sharing keywords, hardcoded record Ids and `SeeAllData=true` tests are findings that never move the score.
Salesforce flows (`.flow-meta.xml`) are one symbol each, linked to the Apex
invocable actions, subflows, screen components and triggering objects they name.
Salesforce object and field metadata become symbols that Apex SOQL, DML and
diff --git a/packages/core/src/repowise/core/analysis/health/apex_markers.py b/packages/core/src/repowise/core/analysis/health/apex_markers.py
new file mode 100644
index 000000000..e52bc810d
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/apex_markers.py
@@ -0,0 +1,702 @@
+"""Apex security and test-hygiene markers, read off the Apex tree.
+
+Four advisory markers, all precision-first (each stays silent when the tree does
+not prove its claim):
+
+- ``apex_soql_injection``: a dynamic query (``Database.query`` and friends,
+ ``Search.query``) whose string splices a value from outside the method (a
+ String parameter, a public String field or property, or a local built from one) inside
+ a quoted SOQL literal, with no escape call and no bind. Values outside quotes
+ (field lists, object names) are not flagged: escaping cannot protect them and
+ they are almost always describe results.
+- ``apex_missing_sharing``: a top-level class that runs SOQL, SOSL or DML in its
+ own body and declares no sharing keyword. A subclass inherits its parent's
+ setting and an inner class's queries are its own, so both are left out.
+- ``apex_hardcoded_id``: a string literal shaped like a record Id (an 18-char
+ Id with a valid checksum, or a 15-char Id with a standard key prefix), not a
+ zero-filled or ``xx`` sample Id, outside fixture-named classes.
+- ``apex_see_all_data``: ``@IsTest(SeeAllData=true)``.
+
+Test classes and methods are skipped by the first three, and a
+``@SuppressWarnings('PMD.<Rule>')`` naming the matching PMD rule (or ``'PMD'``) on
+the class or method silences each. Ceiling: any String parameter counts as from
+outside, so a private helper only ever called with constants still fires.
+Hits ride ``FileComplexity.perf_hits`` like the SQL smells.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable, Iterator
+from typing import TYPE_CHECKING
+
+from .complexity.models import PerfHit
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+SOQL_INJECTION = "apex_soql_injection"
+MISSING_SHARING = "apex_missing_sharing"
+HARDCODED_ID = "apex_hardcoded_id"
+SEE_ALL_DATA = "apex_see_all_data"
+
+_PMD_RULE = {
+ SOQL_INJECTION: "pmd.apexsoqlinjection",
+ MISSING_SHARING: "pmd.apexsharingviolations",
+ HARDCODED_ID: "pmd.avoidhardcodingid",
+ SEE_ALL_DATA: "pmd.apexunittestshouldnotuseseealldatatrue",
+}
+
+_DYNAMIC_QUERY = {
+ "database": frozenset(
+ {
+ "query", "countquery", "getquerylocator",
+ "querywithbinds", "countquerywithbinds", "getquerylocatorwithbinds",
+ }
+ ),
+ "search": frozenset({"query"}),
+}
+# Calls whose records sharing can hide: reads and changes to existing rows. An
+# insert creates a row no sharing rule hides, so it does not count.
+_SHARED_OPS = {
+ "database": _DYNAMIC_QUERY["database"] | {"update", "upsert", "delete", "undelete", "merge"},
+ "search": frozenset({"query", "find"}),
+}
+_SHARING = frozenset({"with_sharing", "without_sharing", "inherited_sharing"})
+# Objects whose rows carry no sharing, so a query on them reads the same either way.
+_UNSHARED_OBJECTS = frozenset(
+ {
+ "recordtype", "profile", "organization", "apexclass", "apextrigger", "asyncapexjob",
+ "crontrigger", "cronjobdetail", "permissionset", "userrole", "businesshours",
+ "staticresource", "entitydefinition", "fielddefinition", "userlicense",
+ "flowdefinitionview", "flowversionview", "opportunitystage", "casestatus",
+ "leadstatus", "taskstatus", "taskpriority", "contractstatus", "currencytype",
+ "datedconversionrate", "period", "fiscalyearsettings", "group", "groupmember",
+ "folder", "network", "site", "holiday", "permissionsetassignment",
+ }
+)
+_METHODS = frozenset({"method_declaration", "constructor_declaration"})
+_TYPES = frozenset({"class_declaration", "interface_declaration", "enum_declaration"})
+_STRING_COLLECTIONS = frozenset({"list<string>", "set<string>", "string[]"})
+# String methods whose result still carries the receiver's characters (``replace``
+# and ``remove`` are left out: they are how code strips quotes).
+_PASS_THROUGH = frozenset(
+ {
+ "trim", "tolowercase", "touppercase", "normalizespace", "deletewhitespace",
+ "substring", "left", "right", "mid", "capitalize", "abbreviate", "get",
+ }
+)
+
+# Standard key prefixes a 15-char literal must start with (an 18-char Id proves
+# itself by its checksum instead).
+_KEY_PREFIXES = frozenset(
+ {
+ "001", "003", "005", "006", "00Q", "500", "701", "00G", "012", "00e", "0PS",
+ "00D", "00T", "00U", "015", "068", "069", "00O", "01Z", "00X", "00E", "01t",
+ "01s", "01u", "00k", "00v", "02i", "800", "801", "0Q0", "00N", "01I", "00l",
+ }
+)
+# Test-support classes not marked @IsTest (fixtures, mocks) carry sample Ids by design.
+# Ceiling: named by convention only; a class reached only from tests is not detected.
+_FIXTURE_NAME = re.compile(r"fixture|mock|stub|fake|testdata|testfactory|testutil|datafactory", re.I)
+_ID_SHAPE = re.compile(r"[a-zA-Z0-9]{15}(?:[a-zA-Z0-9]{3})?")
+_CHECKSUM_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"
+# Built from ``_DYNAMIC_QUERY`` so the byte gate and the sink list cannot drift apart.
+_HAS_DYNAMIC_QUERY = re.compile(
+ "|".join(
+ rf"\b{receiver}\s*\.\s*(?:{'|'.join(sorted(methods))})\s*\("
+ for receiver, methods in _DYNAMIC_QUERY.items()
+ ).encode(),
+ re.I,
+)
+_HAS_ID_LITERAL = re.compile(rb"'[a-zA-Z0-9]{15}(?:[a-zA-Z0-9]{3})?'")
+_HAS_SEE_ALL_DATA = re.compile(rb"(?i)seealldata")
+
+
+def _text(node: Node | None) -> str:
+ return (node.text or b"").decode("utf-8", "replace") if node is not None else ""
+
+
+def _lower(node: Node | None) -> str:
+ return _text(node).lower()
+
+
+def _walk(node: Node, skip: frozenset[str] = frozenset()) -> Iterator[Node]:
+ """Every descendant of *node*, not entering a child whose type is in *skip*."""
+ stack = list(reversed(node.children))
+ while stack:
+ cur = stack.pop()
+ yield cur
+ if cur.type not in skip:
+ stack.extend(reversed(cur.children))
+
+
+def _ancestors(node: Node) -> Iterator[Node]:
+ cur = node.parent
+ while cur is not None:
+ yield cur
+ cur = cur.parent
+
+
+def _modifiers(decl: Node) -> Node | None:
+ return next((c for c in decl.children if c.type == "modifiers"), None)
+
+
+def _annotations(decl: Node) -> list[Node]:
+ mods = _modifiers(decl)
+ return [] if mods is None else [c for c in mods.children if c.type == "annotation"]
+
+
+def _modifier_kinds(decl: Node) -> set[str]:
+ mods = _modifiers(decl)
+ if mods is None:
+ return set()
+ return {g.type.lower() for c in mods.children if c.type == "modifier" for g in c.children}
+
+
+def _is_test_decl(decl: Node) -> bool:
+ return "testmethod" in _modifier_kinds(decl) or any(
+ _lower(a.child_by_field_name("name")) == "istest" for a in _annotations(decl)
+ )
+
+
+def _in_test(node: Node) -> bool:
+ return any(a.type in _METHODS | _TYPES and _is_test_decl(a) for a in _ancestors(node))
+
+
+def _suppressed(node: Node, kind: str) -> bool:
+ rule = _PMD_RULE[kind]
+ for decl in (a for a in (node, *_ancestors(node)) if a.type in _METHODS | _TYPES):
+ for ann in _annotations(decl):
+ if _lower(ann.child_by_field_name("name")) != "suppresswarnings":
+ continue
+ args = ann.child_by_field_name("arguments")
+ values = [n for n in _walk(args) if n.type == "string_literal"] if args is not None else []
+ names = {n.strip() for v in values for n in _literal(v).lower().split(",")}
+ if "pmd" in names or rule in names:
+ return True
+ return False
+
+
+def _decl_name(node: Node) -> str | None:
+ for a in _ancestors(node):
+ if a.type in _METHODS | _TYPES:
+ return _text(a.child_by_field_name("name")) or None
+ return None
+
+
+def _decl_start(node: Node) -> int:
+ for a in _ancestors(node):
+ if a.type in _METHODS:
+ return a.start_point[0] + 1
+ return 0
+
+
+def _hit(kind: str, node: Node, detail: str, at: Node | None = None) -> PerfHit:
+ return PerfHit(
+ kind=kind,
+ line=(at or node).start_point[0] + 1,
+ function=_decl_name(node),
+ detail=detail,
+ func_start=_decl_start(node),
+ )
+
+
+def _literal(node: Node) -> str:
+ """A string literal's value, Apex escapes decoded (``\\'`` is ``'``)."""
+ raw = _text(node)[1:-1]
+ return re.sub(r"\\(.)", lambda m: {"n": "\n", "t": "\t"}.get(m.group(1), m.group(1)), raw)
+
+
+def _soql_quotes(value: str) -> int:
+ """Quotes that open or close a SOQL string (a ``\\'`` inside one is escaped)."""
+ return len(re.findall(r"(?<!\\)'", value))
+
+
+# -- apex_see_all_data ----------------------------------------------------------
+
+
+def _sees_all_data(ann: Node) -> bool:
+ """``ann`` is ``@IsTest(SeeAllData=true)``, any case."""
+ if ann.type != "annotation" or _lower(ann.child_by_field_name("name")) != "istest":
+ return False
+ args = ann.child_by_field_name("arguments")
+ pairs = {
+ _lower(kv.child_by_field_name("key")): _lower(kv.child_by_field_name("value"))
+ for kv in (args.named_children if args is not None else ())
+ if kv.type == "annotation_key_value"
+ }
+ return pairs.get("seealldata") == "true"
+
+
+def _see_all_data(annotations: list[Node]) -> list[PerfHit]:
+ hits = []
+ for ann in annotations:
+ if not _sees_all_data(ann) or _suppressed(ann, SEE_ALL_DATA):
+ continue
+ decl = ann.parent.parent if ann.parent is not None else None
+ what = "class" if decl is not None and decl.type in _TYPES else "method"
+ hits.append(_hit(SEE_ALL_DATA, ann.parent or ann, what, at=ann))
+ return hits
+
+
+# -- apex_hardcoded_id ----------------------------------------------------------
+
+
+def _checksum(value: str) -> str:
+ out = ""
+ for chunk in range(3):
+ bits = sum(1 << i for i, c in enumerate(value[chunk * 5 : chunk * 5 + 5]) if c.isupper())
+ out += _CHECKSUM_CHARS[bits]
+ return out
+
+
+def is_record_id(value: str) -> bool:
+ """*value* reads as a Salesforce record Id: 18 chars with a valid checksum, or
+ 15 chars on a standard key prefix, mixing digits and letters either way."""
+ body = value[3:15]
+ if not _ID_SHAPE.fullmatch(value) or sum(c.isdigit() for c in value[:15]) < 3:
+ return False
+ # No letters is a zero-filled stand-in; ``xx`` marks Salesforce's sample Ids (``001xx000003DGb2``).
+ if not any(c.isalpha() for c in body) or "xx" in body:
+ return False
+ if len(value) == 18:
+ return _checksum(value[:15]) == value[15:]
+ # A 15-char Id has no checksum: also ask for the zero run its pod and reserved digits leave.
+ return value[:3] in _KEY_PREFIXES and "000" in body
+
+
+def _hardcoded_ids(root: Node, literals: list[Node]) -> list[PerfHit]:
+ hits: list[PerfHit] = []
+ if any(c.type in _TYPES and _FIXTURE_NAME.search(_text(c.child_by_field_name("name"))) for c in root.named_children):
+ return hits
+ for node in literals:
+ value = _literal(node)
+ if is_record_id(value) and not _in_test(node) and not _suppressed(node, HARDCODED_ID):
+ hits.append(_hit(HARDCODED_ID, node, value))
+ return hits
+
+
+# -- apex_missing_sharing -------------------------------------------------------
+
+
+def _static_call(node: Node, table: dict[str, frozenset[str]]) -> bool:
+ if node.type != "method_invocation":
+ return False
+ receiver = _lower(node.child_by_field_name("object")).replace(" ", "")
+ receiver = receiver.removeprefix("system.")
+ return _lower(node.child_by_field_name("name")) in table.get(receiver, frozenset())
+
+
+def _unshared(obj: str) -> bool:
+ """*obj* (lowercased) keeps no record sharing: custom metadata, a custom
+ setting (by its usual ``...Settings__c`` name) or a setup object."""
+ obj = obj.rsplit(".", 1)[-1]
+ return obj.endswith("__mdt") or "setting" in obj or obj in _UNSHARED_OBJECTS
+
+
+def _declared_type(ident: Node) -> str:
+ """The lowercased element type a name is declared with in its method or class."""
+ name = _lower(ident)
+ for scope in (a for a in _ancestors(ident) if a.type in _METHODS or a.type == "class_declaration"):
+ typ = _local_type(scope, name) if scope.type in _METHODS else _Scope(scope).fields.get(name, ("",))[0]
+ if typ:
+ return re.sub(r"^(?:list|set)<(.*)>$|\[\]$", r"\1", typ)
+ return ""
+
+
+def _inline_from(query: Node) -> str:
+ body = query.named_children[0] if query.named_children else None
+ source = body.child_by_field_name("from_clause") if body is not None else None
+ return _lower(source.named_children[0]) if source is not None and source.named_children else ""
+
+
+def _literal_from(value: Node) -> str | None:
+ """The FROM object of a query string built from literals, else ``None``."""
+ text = "".join(_literal(p) if p.type == "string_literal" else " ? " for p in _operands(value))
+ # Child subqueries name relationships, not the object read.
+ found = re.search(r"\bfrom\s+(\w+)", re.sub(r"\([^()]*\)", " ", text), re.I)
+ return found.group(1).lower() if found else None
+
+
+def _first_args(call: Node) -> list[Node]:
+ args = call.child_by_field_name("arguments")
+ return list(args.named_children[:1]) if args is not None else []
+
+
+def _query_objects(node: Node) -> list[str]:
+ """The objects a query may read: the FROM of inline SOQL, or of a dynamic
+ query built from literals (directly or through a local). ``""`` is unknown."""
+ if node.type == "query_expression":
+ return [_inline_from(node)]
+ values = _first_args(node)
+ if values and values[0].type == "identifier":
+ method = next((a for a in _ancestors(values[0]) if a.type in _METHODS), None)
+ values = _assigned(method, _lower(values[0])) if method is not None else []
+ # A ``+=`` appending a filter names no object; no FROM anywhere is unknown.
+ return [obj for obj in map(_literal_from, values) if obj] or [""]
+
+
+def _shared_target(target: Node | None) -> bool:
+ """A DML target whose records sharing applies to (unknown counts)."""
+ if target is None:
+ return True
+ return not _unshared(_declared_type(target) if target.type == "identifier" else _lower(target))
+
+
+def _shared_op(node: Node) -> bool:
+ """*node* reads or changes records that record sharing applies to."""
+ if node.type == "dml_expression":
+ kind = next((c for c in node.children if c.type == "dml_type"), None)
+ target = node.child_by_field_name("target")
+ return _lower(kind) != "insert" and target is not None and _shared_target(target)
+ if node.type == "query_expression" or _static_call(node, _DYNAMIC_QUERY):
+ return not all(obj and _unshared(obj) for obj in _query_objects(node))
+ return _static_call(node, _SHARED_OPS) and _shared_target(next(iter(_first_args(node)), None))
+
+
+def _first_db_op(cls: Node) -> Node | None:
+ body = cls.child_by_field_name("body")
+ if body is None:
+ return None
+ return next((n for n in _walk(body, skip=_TYPES) if _shared_op(n)), None)
+
+
+def _has_test_method(cls: Node) -> bool:
+ """A legacy test class: ``testMethod`` members and no ``@IsTest`` on the class."""
+ body = cls.child_by_field_name("body")
+ return any(m.type in _METHODS and _is_test_decl(m) for m in (body.named_children if body else ()))
+
+
+def _sharing_candidate(cls: Node) -> bool:
+ """A top-level class with no sharing keyword that could carry one: not a
+ subclass (it inherits its parent's), not a test class, not suppressed."""
+ if cls.type != "class_declaration" or _modifier_kinds(cls) & _SHARING:
+ return False
+ if cls.child_by_field_name("superclass") is not None:
+ return False
+ tests = _is_test_decl(cls) or _has_test_method(cls)
+ return not tests and not _suppressed(cls, MISSING_SHARING)
+
+
+def _missing_sharing(root: Node) -> list[PerfHit]:
+ hits = []
+ for cls in filter(_sharing_candidate, root.named_children):
+ op = _first_db_op(cls)
+ name = cls.child_by_field_name("name") or cls
+ if op is not None:
+ hits.append(
+ PerfHit(
+ kind=MISSING_SHARING,
+ line=name.start_point[0] + 1,
+ function=_text(name) or None,
+ detail=f"line {op.start_point[0] + 1}",
+ )
+ )
+ return hits
+
+
+# -- apex_soql_injection --------------------------------------------------------
+
+
+class _Scope:
+ """Declarations and assignments of one class, for tracing a query string."""
+
+ def __init__(self, cls: Node) -> None:
+ self.cls = cls
+ self.fields: dict[str, tuple[str, bool]] = {} # name -> (type, externally settable)
+ self.assigns: dict[str, list[tuple[Node, Node | None]]] = {} # name -> [(rhs, method)]
+ body = cls.child_by_field_name("body")
+ for member in body.named_children if body is not None else ():
+ if member.type != "field_declaration":
+ continue
+ kinds = _modifier_kinds(member)
+ settable = bool(kinds & {"public", "global"}) and "final" not in kinds
+ typ = "".join(_lower(member.child_by_field_name("type")).split())
+ for decl in member.children_by_field_name("declarator"):
+ self.fields[_lower(decl.child_by_field_name("name"))] = (typ, settable)
+
+ def assignments(self, name: str, method: Node | None) -> list[tuple[Node, Node | None]]:
+ """``(rhs, method)`` for every value *name* takes: in *method* when it is a
+ local or parameter there, else across the class when it is a field."""
+ if method is not None and _local_type(method, name) is not None:
+ return [(rhs, method) for rhs in _assigned(method, name)]
+ if name not in self.fields:
+ return []
+ if name not in self.assigns:
+ body = self.cls.child_by_field_name("body")
+ methods = [m for m in (body.named_children if body is not None else ()) if m.type in _METHODS]
+ self.assigns[name] = [
+ (rhs, m) for m in methods if _local_type(m, name) is None for rhs in _assigned(m, name)
+ ]
+ return self.assigns[name]
+
+
+def _declares(node: Node, name: str) -> bool:
+ if node.type == "formal_parameter":
+ return _lower(node.child_by_field_name("name")) == name
+ return node.type == "local_variable_declaration" and any(
+ _lower(d.child_by_field_name("name")) == name for d in node.children_by_field_name("declarator")
+ )
+
+
+def _local_type(method: Node, name: str) -> str | None:
+ """The lowercased type *method* declares *name* with (parameter or local)."""
+ decl = next((n for n in _walk(method, skip=_TYPES) if _declares(n, name)), None)
+ return "".join(_lower(decl.child_by_field_name("type")).split()) if decl is not None else None
+
+
+def _is_param(method: Node, name: str) -> bool:
+ params = method.child_by_field_name("parameters")
+ return any(
+ p.type == "formal_parameter" and _lower(p.child_by_field_name("name")) == name
+ for p in (params.named_children if params is not None else ())
+ )
+
+
+def _assigned(method: Node, name: str) -> list[Node]:
+ """Every expression *method* stores in *name* (initializer, ``=``, ``+=``)."""
+ out = []
+ for node in _walk(method, skip=_TYPES):
+ if node.type == "variable_declarator" and _lower(node.child_by_field_name("name")) == name:
+ value = node.child_by_field_name("value")
+ if value is not None:
+ out.append(value)
+ elif node.type == "assignment_expression" and _target(node.child_by_field_name("left")) == name:
+ out.append(node.child_by_field_name("right"))
+ return [n for n in out if n is not None]
+
+
+def _target(node: Node | None) -> str | None:
+ if node is None:
+ return None
+ if node.type == "identifier":
+ return _lower(node)
+ if node.type == "field_access" and _lower(node.child_by_field_name("object")) == "this":
+ return _lower(node.child_by_field_name("field"))
+ return None
+
+
+def _is_escape(node: Node) -> bool:
+ return node.type == "method_invocation" and "escape" in _lower(node.child_by_field_name("name"))
+
+
+def _operands(expr: Node) -> list[Node]:
+ """*expr* as the pieces a ``+`` chain concatenates, parentheses dropped."""
+ out, stack = [], [expr]
+ while stack: # iterative: generated code chains thousands of ``+``
+ cur = stack.pop()
+ if cur.type == "parenthesized_expression" and cur.named_children:
+ stack.append(cur.named_children[0])
+ elif cur.type == "binary_expression" and _text(cur.child_by_field_name("operator")) == "+":
+ stack += [c for c in (cur.child_by_field_name("right"), cur.child_by_field_name("left")) if c]
+ else:
+ out.append(cur)
+ return out
+
+
+class _Tracer:
+ def __init__(self, scope: _Scope) -> None:
+ self.scope = scope
+ self.seen: set[tuple[int, int, str]] = set()
+
+ # A value from outside the method --------------------------------------
+
+ def _type_of(self, name: str, method: Node | None) -> tuple[str | None, bool]:
+ """``(type, is a source)`` of *name* seen from *method*."""
+ if method is not None:
+ local = _local_type(method, name)
+ if local is not None:
+ return local, _is_param(method, name)
+ typ, settable = self.scope.fields.get(name, (None, False))
+ return typ, settable
+
+ def _sanitized(self, name: str, method: Node | None) -> bool:
+ return any(
+ _is_escape(rhs) for rhs, _m in self.scope.assignments(name, method)
+ )
+
+ def tainted_name(self, node: Node, method: Node | None, depth: int = 0) -> str | None:
+ """The outside String *node* carries unescaped, or ``None``."""
+ if depth > 4:
+ return None
+ if node.type == "parenthesized_expression" and node.named_children:
+ return self.tainted_name(node.named_children[0], method, depth)
+ if node.type == "ternary_expression":
+ return _first(self.tainted_name(b, method, depth + 1) for b in _branches(node))
+ if node.type == "array_access":
+ return self._collection(node.child_by_field_name("array"), method)
+ if node.type == "method_invocation":
+ return self._call(node, method, depth)
+ return self._tainted_name_of(node, method, depth)
+
+ def _tainted_name_of(self, node: Node, method: Node | None, depth: int) -> str | None:
+ """A plain name: a String source itself, or a String local or field built from one."""
+ name = _target(node)
+ typ, source = self._type_of(name, method) if name else (None, False)
+ if name is None or typ != "string" or self._sanitized(name, method):
+ return None
+ if source:
+ return _text(node)
+ if not self._first_visit(method, name):
+ return None
+ return _first(
+ self.tainted_name(piece, where, depth + 1)
+ for rhs, where in self.scope.assignments(name, method)
+ for piece in _operands(rhs)
+ )
+
+ def _first_visit(self, method: Node | None, name: str, space: int = 0) -> bool:
+ key = (space, method.id if method is not None else 0, name)
+ if key in self.seen:
+ return False
+ self.seen.add(key)
+ return True
+
+ def _collection(self, node: Node | None, method: Node | None) -> str | None:
+ name = _target(node)
+ if name is None:
+ return None
+ typ, source = self._type_of(name, method)
+ return _text(node) if source and typ in _STRING_COLLECTIONS else None
+
+ def _call(self, call: Node, method: Node | None, depth: int) -> str | None:
+ if _is_escape(call):
+ return None
+ receiver = call.child_by_field_name("object")
+ name = _lower(call.child_by_field_name("name"))
+ args = call.child_by_field_name("arguments")
+ first = args.named_children[0] if args is not None and args.named_children else None
+ if _lower(receiver) == "string" and name == "join" and first is not None:
+ return self._collection(first, method)
+ if receiver is None or name not in _PASS_THROUGH:
+ return None
+ if name == "get":
+ return self._collection(receiver, method)
+ return self.tainted_name(receiver, method, depth + 1)
+
+ # Where the query string splices one in ---------------------------------
+
+ def quoted_splice(self, expr: Node, method: Node | None, depth: int = 0) -> str | None:
+ """The outside value *expr* splices inside a quoted SOQL literal, tracing
+ the String locals and fields it is built from."""
+ if depth > 4:
+ return None
+ quoted = False
+ for piece in _operands(expr):
+ if piece.type == "string_literal":
+ quoted ^= _soql_quotes(_literal(piece)) % 2 == 1
+ continue
+ if quoted:
+ found = self.tainted_name(piece, method)
+ if found:
+ return found
+ found = self._built_from(piece, method, depth)
+ if found:
+ return found
+ return None
+
+ def _built_from(self, piece: Node, method: Node | None, depth: int) -> str | None:
+ """A splice inside the String local, field, ternary or format *piece* builds on."""
+ if piece.type == "ternary_expression":
+ return _first(self.quoted_splice(b, method, depth + 1) for b in _branches(piece))
+ if piece.type == "method_invocation":
+ return self._format(piece, method)
+ name = _target(piece)
+ if name is None or self._type_of(name, method)[0] != "string":
+ return None
+ if not self._first_visit(method, name, space=1):
+ return None
+ return _first(
+ self.quoted_splice(rhs, where, depth + 1)
+ for rhs, where in self.scope.assignments(name, method)
+ )
+
+ def _format(self, call: Node, method: Node | None) -> str | None:
+ """``String.format`` whose quoted placeholder takes an outside value."""
+ template, values = _format_args(call)
+ return _first(
+ self.tainted_name(values[index], method)
+ for index, quoted in _format_slots(template)
+ if quoted and index < len(values)
+ )
+
+
+def _first(found: Iterable[str | None]) -> str | None:
+ return next((f for f in found if f), None)
+
+
+def _branches(ternary: Node) -> list[Node]:
+ return [c for c in (ternary.child_by_field_name(f) for f in ("consequence", "alternative")) if c]
+
+
+def _format_args(call: Node) -> tuple[str, list[Node]]:
+ """``String.format(template, new List<Object>{...})``'s template and values."""
+ args = call.child_by_field_name("arguments")
+ named = args.named_children if args is not None else []
+ is_format = _lower(call.child_by_field_name("object")) == "string" and (
+ _lower(call.child_by_field_name("name")) == "format"
+ )
+ if not is_format or len(named) < 2 or named[0].type != "string_literal":
+ return "", []
+ init = next((c for c in named[1].children if c.type == "array_initializer"), None)
+ return _literal(named[0]), list(init.named_children) if init is not None else []
+
+
+def _format_slots(template: str) -> list[tuple[int, bool]]:
+ """``(argument index, inside a SOQL quote)`` for each placeholder of a
+ ``String.format`` template. Apex formats like Java's MessageFormat: ``''`` is
+ one quote, and a lone ``'`` quotes the text after it, placeholders included."""
+ slots, rendered, literal, i = [], 0, False, 0
+ while i < len(template):
+ if template.startswith("''", i):
+ rendered += 1
+ i += 2
+ elif template[i] == "'":
+ literal = not literal
+ i += 1
+ elif not literal and (m := re.match(r"\{(\d+)\}", template[i:])):
+ slots.append((int(m.group(1)), rendered % 2 == 1))
+ i += m.end()
+ else:
+ i += 1
+ return slots
+
+
+def _checked_query(call: Node) -> bool:
+ """A dynamic query call outside test code that no suppression covers."""
+ if not _static_call(call, _DYNAMIC_QUERY) or not _first_args(call):
+ return False
+ return not _in_test(call) and not _suppressed(call, SOQL_INJECTION)
+
+
+def _soql_injections(calls: list[Node]) -> list[PerfHit]:
+ hits = []
+ scopes: dict[int, _Scope] = {}
+ for call in filter(_checked_query, calls):
+ cls = next((a for a in _ancestors(call) if a.type == "class_declaration"), None)
+ method = next((a for a in _ancestors(call) if a.type in _METHODS), None)
+ if cls is None:
+ continue
+ found = _Tracer(scopes.setdefault(cls.id, _Scope(cls))).quoted_splice(_first_args(call)[0], method)
+ if found:
+ hits.append(_hit(SOQL_INJECTION, call, found))
+ return hits
+
+
+def apex_marker_hits(root: Node) -> list[PerfHit]:
+ """Every Apex marker hit in the file whose tree is *root*."""
+ # A byte scan picks the node types a file can hit on; most files walk for none.
+ source = root.text or b""
+ gates = {"method_invocation": _HAS_DYNAMIC_QUERY, "string_literal": _HAS_ID_LITERAL, "annotation": _HAS_SEE_ALL_DATA}
+ wanted = {kind for kind, gate in gates.items() if gate.search(source)}
+ nodes: dict[str, list[Node]] = {kind: [] for kind in gates}
+ for node in _walk(root) if wanted else ():
+ if node.type in wanted:
+ nodes[node.type].append(node)
+ return [
+ *_soql_injections(nodes["method_invocation"]),
+ *_missing_sharing(root),
+ *_hardcoded_ids(root, nodes["string_literal"]),
+ *_see_all_data(nodes["annotation"]),
+ ]
diff --git a/packages/core/src/repowise/core/analysis/health/biomarker_labels.py b/packages/core/src/repowise/core/analysis/health/biomarker_labels.py
index 11c3a8f36..7ecd37ba6 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarker_labels.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarker_labels.py
@@ -67,6 +67,10 @@ BIOMARKER_LABELS: dict[str, str] = {
"sql_select_star": "SELECT * in a view",
"sql_update_delete_without_where": "UPDATE/DELETE without WHERE",
"sql_cartesian_join": "Cartesian join",
+ "apex_soql_injection": "SOQL injection",
+ "apex_missing_sharing": "Apex class without sharing",
+ "apex_hardcoded_id": "Hardcoded record Id",
+ "apex_see_all_data": "Test sees all org data",
}
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
index c35243c9f..fe5be90b5 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
@@ -11,8 +11,8 @@ class Biomarker(Protocol):
## Registered detectors
-`registry.py` registers 54 detectors: the 29 code-health markers below, 22
-performance markers and 3 SQL maintainability markers. Every id with its threshold
+`registry.py` registers 58 detectors: the 29 code-health markers below, 22
+performance markers, 3 SQL maintainability markers and 4 advisory Apex markers. Every id with its threshold
and weight is in
[the full roster](../../../../../../../../docs/architecture/code-health.md#the-full-roster).
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/apex_hardcoded_id.py b/packages/core/src/repowise/core/analysis/health/biomarkers/apex_hardcoded_id.py
new file mode 100644
index 000000000..edc814706
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/apex_hardcoded_id.py
@@ -0,0 +1,35 @@
+"""``apex_hardcoded_id``: a record Id written as a string literal in non-test
+Apex (``health/apex_markers.py``).
+
+Advisory: no defect corpus labels it, so it is listed and never deducts.
+"""
+
+from __future__ import annotations
+
+from ..apex_markers import HARDCODED_ID
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+
+class ApexHardcodedIdDetector:
+ name = HARDCODED_ID
+ category = "apex"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ if ctx.is_test_material:
+ return []
+ return [
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.MEDIUM,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={"value": hit.detail},
+ reason=(
+ f"Hardcoded record Id '{hit.detail}': Ids differ between orgs and sandboxes"
+ ),
+ )
+ for hit in ctx.perf_hits
+ if hit.kind == self.name
+ ]
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/apex_missing_sharing.py b/packages/core/src/repowise/core/analysis/health/biomarkers/apex_missing_sharing.py
new file mode 100644
index 000000000..0c10ec66c
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/apex_missing_sharing.py
@@ -0,0 +1,36 @@
+"""``apex_missing_sharing``: a top-level Apex class that runs SOQL or DML and
+declares no sharing keyword (``health/apex_markers.py``).
+
+Advisory: no defect corpus labels it, so it is listed and never deducts.
+"""
+
+from __future__ import annotations
+
+from ..apex_markers import MISSING_SHARING
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+
+class ApexMissingSharingDetector:
+ name = MISSING_SHARING
+ category = "apex"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ if ctx.is_test_material:
+ return []
+ return [
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.MEDIUM,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={"value": hit.detail},
+ reason=(
+ f"Class {hit.function} runs SOQL or DML ({hit.detail}) and declares no sharing "
+ "keyword, so whether record sharing applies depends on its caller"
+ ),
+ )
+ for hit in ctx.perf_hits
+ if hit.kind == self.name
+ ]
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/apex_see_all_data.py b/packages/core/src/repowise/core/analysis/health/biomarkers/apex_see_all_data.py
new file mode 100644
index 000000000..23b88971b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/apex_see_all_data.py
@@ -0,0 +1,34 @@
+"""``apex_see_all_data``: ``@IsTest(SeeAllData=true)`` on an Apex test class or
+method (``health/apex_markers.py``).
+
+Advisory: no defect corpus labels it, so it is listed and never deducts.
+"""
+
+from __future__ import annotations
+
+from ..apex_markers import SEE_ALL_DATA
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+
+class ApexSeeAllDataDetector:
+ name = SEE_ALL_DATA
+ category = "apex"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ return [
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.LOW,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={"value": hit.detail},
+ reason=(
+ f"@IsTest(SeeAllData=true) on {hit.detail} {hit.function}: the test reads the "
+ "org's live data, so its result depends on the org it runs in"
+ ),
+ )
+ for hit in ctx.perf_hits
+ if hit.kind == self.name
+ ]
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/apex_soql_injection.py b/packages/core/src/repowise/core/analysis/health/biomarkers/apex_soql_injection.py
new file mode 100644
index 000000000..4db87ff63
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/apex_soql_injection.py
@@ -0,0 +1,37 @@
+"""``apex_soql_injection``: a dynamic query splicing an outside String into a
+quoted SOQL literal with no escaping or bind (``health/apex_markers.py``).
+
+Advisory: no defect corpus labels it, so it is listed and never deducts.
+"""
+
+from __future__ import annotations
+
+from ..apex_markers import SOQL_INJECTION
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+
+class ApexSoqlInjectionDetector:
+ name = SOQL_INJECTION
+ category = "apex"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ if ctx.is_test_material:
+ return []
+ return [
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.HIGH,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={"value": hit.detail},
+ reason=(
+ f"Dynamic query splices `{hit.detail}`, a String from outside the method, into a "
+ "quoted SOQL literal with no escaping: bind it (`:value`) or pass it through "
+ "String.escapeSingleQuotes"
+ ),
+ )
+ for hit in ctx.perf_hits
+ if hit.kind == self.name
+ ]
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index 851dc3ae5..c60f795a7 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -11,6 +11,10 @@ from __future__ import annotations
from collections.abc import Sequence
+from .apex_hardcoded_id import ApexHardcodedIdDetector
+from .apex_missing_sharing import ApexMissingSharingDetector
+from .apex_see_all_data import ApexSeeAllDataDetector
+from .apex_soql_injection import ApexSoqlInjectionDetector
from .array_spread_in_reduce import ArraySpreadInReduceDetector
from .assertion_free_test import AssertionFreeTestDetector
from .base import Biomarker, BiomarkerResult, FileContext
@@ -131,6 +135,11 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
SqlSelectStarDetector, # type: ignore[list-item]
SqlUpdateDeleteWithoutWhereDetector, # type: ignore[list-item]
SqlCartesianJoinDetector, # type: ignore[list-item]
+ # Apex markers (advisory: listed, never scored).
+ ApexSoqlInjectionDetector, # type: ignore[list-item]
+ ApexMissingSharingDetector, # type: ignore[list-item]
+ ApexHardcodedIdDetector, # type: ignore[list-item]
+ ApexSeeAllDataDetector, # type: ignore[list-item]
]
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index c754111ce..950b232f1 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -252,6 +252,10 @@ def walk_file(
perf_hits, io_boundary_names, perf_fn_facts = _collect_perf_hits(
tree.root_node, language, lmap, scan.io_names
)
+ if language == "apex":
+ from ..apex_markers import apex_marker_hits
+
+ perf_hits = [*perf_hits, *apex_marker_hits(tree.root_node)]
return FileComplexity(
functions=functions,
classes=classes,
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index ef1cbb5d8..ac39d0966 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -224,6 +224,11 @@ _BIOMARKER_CATEGORY: dict[str, str] = {
"ungoverned_hotspot": "organizational",
"stale_governance": "organizational",
"contradictory_decision": "organizational",
+ # Advisory Apex markers; one family so grouped surfaces file them together.
+ "apex_soql_injection": "apex",
+ "apex_missing_sharing": "apex",
+ "apex_hardcoded_id": "apex",
+ "apex_see_all_data": "apex",
}
@@ -330,6 +335,11 @@ _BIOMARKER_DIMENSIONS: dict[str, set[str]] = {
# coverage through coverage_gap and coverage_gradient. Uncalibrated; it ranks
# which complex functions most need tests rather than moving the score.
"untested_complexity": {ADVISORY_DIMENSION},
+ # Uncalibrated Apex markers: findings only until a defect corpus covers them.
+ "apex_soql_injection": {ADVISORY_DIMENSION},
+ "apex_missing_sharing": {ADVISORY_DIMENSION},
+ "apex_hardcoded_id": {ADVISORY_DIMENSION},
+ "apex_see_all_data": {ADVISORY_DIMENSION},
}
# Maintainability per-biomarker weight multipliers. Expert-set by definition -
@@ -557,6 +567,10 @@ _ADVISORY_HOME: frozenset[str] = frozenset(
"hidden_coupling",
"brain_method",
"untested_complexity",
+ "apex_soql_injection",
+ "apex_missing_sharing",
+ "apex_hardcoded_id",
+ "apex_see_all_data",
}
)
diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.py
index 50597b526..68f279181 100644
--- a/packages/core/src/repowise/core/analysis/health/suggestions.py
+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py
@@ -316,6 +316,23 @@ _TEMPLATES: dict[str, str] = {
"Confirm the statement should touch every row. Add the WHERE clause it "
"needs, or a comment stating that the full-table change is intended."
),
+ # Apex.
+ "apex_soql_injection": (
+ "Bind the value. Write it as a bind variable (`:value`) in the query "
+ "string, or pass it through String.escapeSingleQuotes before splicing it in."
+ ),
+ "apex_missing_sharing": (
+ "Declare the sharing mode. Add `with sharing` (or `inherited sharing`), or "
+ "`without sharing` with a comment saying why the class must see every record."
+ ),
+ "apex_hardcoded_id": (
+ "Look the record up instead. Query it by a stable field (DeveloperName, a "
+ "unique name) or read the Id from custom metadata or a custom setting."
+ ),
+ "apex_see_all_data": (
+ "Create the test's data. Insert the records the test needs (a test data "
+ "factory or @TestSetup) and drop SeeAllData=true."
+ ),
}
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index 057f523d5..1aa8bcbb0 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -21,7 +21,8 @@ export type BiomarkerCategory =
| "error_handling"
| "performance"
| "organizational"
- | "sql";
+ | "sql"
+ | "apex";
export interface BiomarkerInfo {
label: string;
@@ -40,6 +41,7 @@ export const CATEGORY_LABEL: Record<BiomarkerCategory, string> = {
performance: "Performance",
organizational: "Organizational",
sql: "SQL",
+ apex: "Apex",
};
export const CATEGORY_CAP: Record<BiomarkerCategory, number> = {
@@ -59,6 +61,8 @@ export const CATEGORY_CAP: Record<BiomarkerCategory, number> = {
// SQL smells deduct on the maintainability pillar only, bounded by the `sql`
// cap in `_MAINTAINABILITY_CATEGORY_CAPS` (scoring.py).
sql: 2.0,
+ // Apex markers are advisory: listed, never deducted.
+ apex: 0,
};
export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
@@ -404,6 +408,30 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
description:
"A comma-join (FROM a, b) with no join predicate anywhere in the statement produces the full cross product: O(n·m) rows. An explicit CROSS JOIN states intent and is not flagged; a comma-join with a WHERE clause is old-style join syntax and is not flagged either.",
},
+ apex_soql_injection: {
+ label: BIOMARKER_LABELS.apex_soql_injection,
+ category: "apex",
+ description:
+ "A dynamic Apex query (Database.query, Search.query) that splices a String from outside the method, a parameter or public property, into a quoted SOQL literal without String.escapeSingleQuotes or a bind variable. Advisory: it never deducts.",
+ },
+ apex_missing_sharing: {
+ label: BIOMARKER_LABELS.apex_missing_sharing,
+ category: "apex",
+ description:
+ "A top-level Apex class that runs SOQL or DML and declares none of with, without or inherited sharing, so whether record sharing applies depends on its caller. Subclasses and inner classes are not flagged. Advisory: it never deducts.",
+ },
+ apex_hardcoded_id: {
+ label: BIOMARKER_LABELS.apex_hardcoded_id,
+ category: "apex",
+ description:
+ "A string literal that is a Salesforce record Id (an 18-character Id with a valid checksum, or a 15-character Id with a standard key prefix) outside test code. Ids differ between orgs and sandboxes. Advisory: it never deducts.",
+ },
+ apex_see_all_data: {
+ label: BIOMARKER_LABELS.apex_see_all_data,
+ category: "apex",
+ description:
+ "A test class or method annotated @IsTest(SeeAllData=true): it reads the org's live data, so it can pass in one org and fail in another. Advisory: it never deducts.",
+ },
};
export function biomarkerInfo(name: string): BiomarkerInfo {
@@ -444,6 +472,10 @@ export const ADVISORY_HOME_BIOMARKERS: ReadonlySet<string> = new Set([
"hidden_coupling",
"brain_method",
"untested_complexity",
+ "apex_soql_injection",
+ "apex_missing_sharing",
+ "apex_hardcoded_id",
+ "apex_see_all_data",
]);
/**
diff --git a/packages/ui/src/health/generated/biomarker-labels.ts b/packages/ui/src/health/generated/biomarker-labels.ts
index 488598c4d..a16315ca4 100644
--- a/packages/ui/src/health/generated/biomarker-labels.ts
+++ b/packages/ui/src/health/generated/biomarker-labels.ts
@@ -61,6 +61,10 @@ export const BIOMARKER_LABELS = {
sql_select_star: "SELECT * in a view",
sql_update_delete_without_where: "UPDATE/DELETE without WHERE",
sql_cartesian_join: "Cartesian join",
+ apex_soql_injection: "SOQL injection",
+ apex_missing_sharing: "Apex class without sharing",
+ apex_hardcoded_id: "Hardcoded record Id",
+ apex_see_all_data: "Test sees all org data",
} as const;
/** Renamed ids (old -> current), so rows stored under an old id get the current label. */
diff --git a/packages/ui/src/health/plain-language.ts b/packages/ui/src/health/plain-language.ts
index 6bb81826f..ea864712d 100644
--- a/packages/ui/src/health/plain-language.ts
+++ b/packages/ui/src/health/plain-language.ts
@@ -59,6 +59,10 @@ const BY_CATEGORY: Record<BiomarkerCategory, PlainIssue> = {
title: "Risky SQL",
why: "The query is hard to reason about or can touch more rows than meant.",
},
+ apex: {
+ title: "Apex security or test risk",
+ why: "It can expose records, break in another org, or depend on org data.",
+ },
};
const BY_BIOMARKER: Record<string, PlainIssue> = {
diff --git a/tests/fixtures/lang_samples/apex/HealthMarkersTest.cls b/tests/fixtures/lang_samples/apex/HealthMarkersTest.cls
new file mode 100644
index 000000000..e85e9fd03
--- /dev/null
+++ b/tests/fixtures/lang_samples/apex/HealthMarkersTest.cls
@@ -0,0 +1,19 @@
+// Fixtures for apex_see_all_data: the class and one method read live org data.
+@IsTest(SeeAllData=true)
+private class HealthMarkersTest {
+ @isTest(seeAllData = true)
+ static void readsOrgData() {
+ Id fixtureId = '0011t00000ABCDeAAP';
+ System.assertNotEquals(null, fixtureId);
+ }
+
+ @IsTest(SeeAllData=false)
+ static void ownData() {
+ insert new Account(Name = 'x');
+ }
+
+ @IsTest(SeeAllData=true)
+ @SuppressWarnings('PMD.ApexUnitTestShouldNotUseSeeAllDataTrue')
+ static void suppressed() {
+ }
+}
diff --git a/tests/fixtures/lang_samples/apex/health_markers.cls b/tests/fixtures/lang_samples/apex/health_markers.cls
new file mode 100644
index 000000000..50a0351ce
--- /dev/null
+++ b/tests/fixtures/lang_samples/apex/health_markers.cls
@@ -0,0 +1,78 @@
+// Fixtures for the Apex health markers: the class declares no sharing keyword
+// and runs SOQL (apex_missing_sharing); each method below either fires one
+// marker or shows a shape that must stay quiet.
+public class HealthMarkers {
+ private static final String BASE = 'SELECT Id FROM Account';
+ private static final Id OWNER = '0051t000002bF3QAAU';
+ public String searchText { get; set; }
+ private String internalName;
+
+ // -- fire ------------------------------------------------------------------
+
+ public List<Account> byName(String name) {
+ return Database.query(BASE + ' WHERE Name = \'' + name + '\'');
+ }
+
+ public List<Account> byBuiltClause(String city) {
+ String soql = BASE;
+ String clause = ' WHERE BillingCity LIKE \'%' + city.trim() + '%\'';
+ soql += clause;
+ return Database.query(soql);
+ }
+
+ public List<List<SObject>> bySearchProperty() {
+ return Search.query('FIND \'' + searchText + '\' IN ALL FIELDS RETURNING Account');
+ }
+
+ public List<Account> byNames(List<String> names) {
+ return Database.query(BASE + ' WHERE Name IN (\'' + String.join(names, '\',\'') + '\')');
+ }
+
+ public Id defaultRecordType() {
+ return '012000000000AbcAAE';
+ }
+
+ // -- stay quiet ------------------------------------------------------------
+
+ public List<Account> escaped(String name) {
+ return Database.query(BASE + ' WHERE Name = \'' + String.escapeSingleQuotes(name) + '\'');
+ }
+
+ public List<Account> escapedFirst(String name) {
+ name = String.escapeSingleQuotes(name);
+ return Database.query(BASE + ' WHERE Name = \'' + name + '\'');
+ }
+
+ public List<Account> bound(String name) {
+ return Database.query(BASE + ' WHERE Name = :name');
+ }
+
+ public List<Account> typedId(Id recordId) {
+ return Database.query(BASE + ' WHERE Id = \'' + recordId + '\'');
+ }
+
+ public List<SObject> fieldList(List<String> fields, String objectName) {
+ // Identifiers outside quotes: escaping cannot protect them, not flagged.
+ return Database.query('SELECT ' + String.join(fields, ',') + ' FROM ' + objectName);
+ }
+
+ public List<Account> privateField() {
+ return Database.query(BASE + ' WHERE Name = \'' + internalName + '\'');
+ }
+
+ public List<Account> inline() {
+ return [SELECT Id FROM Account WHERE OwnerId = :OWNER];
+ }
+
+ public void notIds() {
+ String word = 'AccountServices';
+ String digits = '001000000000000';
+ String sample = '001000000000000AAA';
+ }
+
+ public with sharing class Inner {
+ public void touch(List<Account> rows) {
+ update rows;
+ }
+ }
+}
diff --git a/tests/unit/health/golden/health_engine.json b/tests/unit/health/golden/health_engine.json
index 3848188f5..0070a2b3d 100644
--- a/tests/unit/health/golden/health_engine.json
+++ b/tests/unit/health/golden/health_engine.json
@@ -901,6 +901,25 @@
"is_test": false,
"code_origin": "production"
},
+ {
+ "file_path": "apex/HealthMarkersTest.cls",
+ "score": 10.0,
+ "max_ccn": 1,
+ "max_nesting": 0,
+ "nloc": 16,
+ "has_test_file": true,
+ "module": "apex",
+ "duplication_pct": null,
+ "line_coverage_pct": null,
+ "branch_coverage_pct": null,
+ "defect_score": 10.0,
+ "maintainability_score": 10.0,
+ "performance_score": 10.0,
+ "structure_deduction": 0.0,
+ "history_deduction": 0.0,
+ "is_test": true,
+ "code_origin": "test"
+ },
{
"file_path": "apex/assertions.cls",
"score": 10.0,
@@ -939,6 +958,25 @@
"is_test": false,
"code_origin": "production"
},
+ {
+ "file_path": "apex/health_markers.cls",
+ "score": 10.0,
+ "max_ccn": 1,
+ "max_nesting": 0,
+ "nloc": 56,
+ "has_test_file": false,
+ "module": "apex",
+ "duplication_pct": null,
+ "line_coverage_pct": null,
+ "branch_coverage_pct": null,
+ "defect_score": 10.0,
+ "maintainability_score": 10.0,
+ "performance_score": 10.0,
+ "structure_deduction": 0.0,
+ "history_deduction": 0.0,
+ "is_test": false,
+ "code_origin": "production"
+ },
{
"file_path": "apex/nested.cls",
"score": 8.55,
@@ -2252,6 +2290,150 @@
}
],
"findings": [
+ {
+ "biomarker_type": "apex_see_all_data",
+ "severity": "low",
+ "file_path": "apex/HealthMarkersTest.cls",
+ "function_name": "HealthMarkersTest",
+ "line_start": 2,
+ "line_end": 2,
+ "details": {
+ "value": "class",
+ "symbol_line": 2
+ },
+ "health_impact": 0.0,
+ "reason": "@IsTest(SeeAllData=true) on class HealthMarkersTest: the test reads the org's live data, so its result depends on the org it runs in",
+ "dimension": "advisory",
+ "id": "finding_36631da27da27fc56829"
+ },
+ {
+ "biomarker_type": "apex_see_all_data",
+ "severity": "low",
+ "file_path": "apex/HealthMarkersTest.cls",
+ "function_name": "readsOrgData",
+ "line_start": 4,
+ "line_end": 4,
+ "details": {
+ "value": "method",
+ "symbol_line": 4
+ },
+ "health_impact": 0.0,
+ "reason": "@IsTest(SeeAllData=true) on method readsOrgData: the test reads the org's live data, so its result depends on the org it runs in",
+ "dimension": "advisory",
+ "id": "finding_5ad2784c4b1e3692c080"
+ },
+ {
+ "biomarker_type": "apex_soql_injection",
+ "severity": "high",
+ "file_path": "apex/health_markers.cls",
+ "function_name": "byName",
+ "line_start": 13,
+ "line_end": 13,
+ "details": {
+ "value": "name",
+ "symbol_line": 12
+ },
+ "health_impact": 0.0,
+ "reason": "Dynamic query splices `name`, a String from outside the method, into a quoted SOQL literal with no escaping: bind it (`:value`) or pass it through String.escapeSingleQuotes",
+ "dimension": "advisory",
+ "id": "finding_f1341e96d7d388579f63"
+ },
+ {
+ "biomarker_type": "apex_soql_injection",
+ "severity": "high",
+ "file_path": "apex/health_markers.cls",
+ "function_name": "byBuiltClause",
+ "line_start": 20,
+ "line_end": 20,
+ "details": {
+ "value": "city",
+ "symbol_line": 16
+ },
+ "health_impact": 0.0,
+ "reason": "Dynamic query splices `city`, a String from outside the method, into a quoted SOQL literal with no escaping: bind it (`:value`) or pass it through String.escapeSingleQuotes",
+ "dimension": "advisory",
+ "id": "finding_4ae2e2ef6626a04cd197"
+ },
+ {
+ "biomarker_type": "apex_soql_injection",
+ "severity": "high",
+ "file_path": "apex/health_markers.cls",
+ "function_name": "bySearchProperty",
+ "line_start": 24,
+ "line_end": 24,
+ "details": {
+ "value": "searchText",
+ "symbol_line": 23
+ },
+ "health_impact": 0.0,
+ "reason": "Dynamic query splices `searchText`, a String from outside the method, into a quoted SOQL literal with no escaping: bind it (`:value`) or pass it through String.escapeSingleQuotes",
+ "dimension": "advisory",
+ "id": "finding_f43545b2aa74a6b7613f"
+ },
+ {
+ "biomarker_type": "apex_soql_injection",
+ "severity": "high",
+ "file_path": "apex/health_markers.cls",
+ "function_name": "byNames",
+ "line_start": 28,
+ "line_end": 28,
+ "details": {
+ "value": "names",
+ "symbol_line": 27
+ },
+ "health_impact": 0.0,
+ "reason": "Dynamic query splices `names`, a String from outside the method, into a quoted SOQL literal with no escaping: bind it (`:value`) or pass it through String.escapeSingleQuotes",
+ "dimension": "advisory",
+ "id": "finding_8f755e834430112253f6"
+ },
+ {
+ "biomarker_type": "apex_missing_sharing",
+ "severity": "medium",
+ "file_path": "apex/health_markers.cls",
+ "function_name": "HealthMarkers",
+ "line_start": 4,
+ "line_end": 4,
+ "details": {
+ "value": "line 13",
+ "symbol_line": 4
+ },
+ "health_impact": 0.0,
+ "reason": "Class HealthMarkers runs SOQL or DML (line 13) and declares no sharing keyword, so whether record sharing applies depends on its caller",
+ "dimension": "advisory",
+ "id": "finding_fa887492d1d88d4d4cb3"
+ },
+ {
+ "biomarker_type": "apex_hardcoded_id",
+ "severity": "medium",
+ "file_path": "apex/health_markers.cls",
+ "function_name": "HealthMarkers",
+ "line_start": 6,
+ "line_end": 6,
+ "details": {
+ "value": "0051t000002bF3QAAU",
+ "symbol_line": 4
+ },
+ "health_impact": 0.0,
+ "reason": "Hardcoded record Id '0051t000002bF3QAAU': Ids differ between orgs and sandboxes",
+ "dimension": "advisory",
+ "id": "finding_231d102a50d21a2b4ba8"
+ },
+ {
+ "biomarker_type": "apex_hardcoded_id",
+ "severity": "medium",
+ "file_path": "apex/health_markers.cls",
+ "function_name": "defaultRecordType",
+ "line_start": 32,
+ "line_end": 32,
+ "details": {
+ "value": "012000000000AbcAAE",
+ "symbol_line": 31
+ },
+ "health_impact": 0.0,
+ "reason": "Hardcoded record Id '012000000000AbcAAE': Ids differ between orgs and sandboxes",
+ "dimension": "advisory",
+ "id": "finding_7df931acae6b893d752d"
+ },
{
"biomarker_type": "nested_complexity",
"severity": "high",
@@ -5303,24 +5485,24 @@
],
"kpis": {
"hotspot_health": null,
- "average_health": 9.6,
+ "average_health": 9.62,
"worst_performer_path": "scala/nested.scala",
"worst_performer_score": 7.77,
- "worst_test_path": "apex/assertions.cls",
+ "worst_test_path": "apex/HealthMarkersTest.cls",
"worst_test_score": 10.0,
- "file_count": 69,
- "maintainability_average": 9.64,
+ "file_count": 71,
+ "maintainability_average": 9.65,
"maintainability_hotspot": null,
- "performance_average": 9.47,
+ "performance_average": 9.48,
"performance_hotspot": null,
- "structure_average": 0.4,
+ "structure_average": 0.39,
"structure_hotspot": null,
"history_average": 0.0,
"history_hotspot": null,
- "production_average": 9.6,
- "production_file_count": 68,
+ "production_average": 9.61,
+ "production_file_count": 69,
"unanalysed_file_count": 4,
- "analysed_share": 0.9452
+ "analysed_share": 0.9467
},
"repo_function_mod_p80": null,
"suggestions": [
diff --git a/tests/unit/health/test_apex_markers.py b/tests/unit/health/test_apex_markers.py
new file mode 100644
index 000000000..ea9db3e02
--- /dev/null
+++ b/tests/unit/health/test_apex_markers.py
@@ -0,0 +1,193 @@
+"""Apex health markers: SOQL injection, missing sharing, hardcoded Ids, SeeAllData.
+
+Precision first: every firing shape has a paired quiet one, and the markers are
+advisory, so no finding moves a score.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.health.apex_markers import (
+ _DYNAMIC_QUERY,
+ _HAS_DYNAMIC_QUERY,
+ is_record_id,
+)
+from repowise.core.analysis.health.biomarkers.base import FileContext
+from repowise.core.analysis.health.biomarkers.registry import detect_all
+from repowise.core.analysis.health.complexity import walk_file
+from repowise.core.analysis.health.scoring import biomarker_dimension, dimensions_for, score_file
+
+_FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lang_samples" / "apex"
+_KINDS = ("apex_soql_injection", "apex_missing_sharing", "apex_hardcoded_id", "apex_see_all_data")
+
+
+def _hits(src: str, name: str = "t.cls") -> list[tuple[str, str | None, str]]:
+ fc = walk_file(name, "apex", src.encode())
+ return sorted((h.kind, h.function, h.detail) for h in fc.perf_hits if h.kind in _KINDS)
+
+
+def _fixture_hits(name: str) -> list[tuple[str, str | None, str]]:
+ return _hits((_FIXTURES / name).read_text(encoding="utf-8"), name)
+
+
+def _ctx(src: str, *, is_test: bool) -> FileContext:
+ fc = walk_file("t.cls", "apex", src.encode())
+ return FileContext(
+ file_path="classes/t.cls", language="apex", nloc=10, has_test_file=False,
+ module=None, is_test=is_test, perf_hits=fc.perf_hits,
+ )
+
+
+def test_fixture_hits():
+ assert _fixture_hits("health_markers.cls") == sorted(
+ [
+ ("apex_soql_injection", "byName", "name"),
+ ("apex_soql_injection", "byBuiltClause", "city"),
+ ("apex_soql_injection", "bySearchProperty", "searchText"),
+ ("apex_soql_injection", "byNames", "names"),
+ ("apex_missing_sharing", "HealthMarkers", "line 13"),
+ ("apex_hardcoded_id", "HealthMarkers", "0051t000002bF3QAAU"),
+ ("apex_hardcoded_id", "defaultRecordType", "012000000000AbcAAE"),
+ ]
+ )
+
+
+def test_see_all_data_fixture():
+ assert _fixture_hits("HealthMarkersTest.cls") == [
+ ("apex_see_all_data", "HealthMarkersTest", "class"),
+ ("apex_see_all_data", "readsOrgData", "method"),
+ ]
+
+
+# -- apex_soql_injection --------------------------------------------------------
+
+_INJECTION_QUIET = {
+ "constant": "static final String N = 'x'; List<Account> m() { return Database.query('SELECT Id FROM Account WHERE Name = \\'' + N + '\\''); }",
+ "local from literal": "List<Account> m() { String n = 'x'; return Database.query('SELECT Id FROM Account WHERE Name = \\'' + n + '\\''); }",
+ "escape wrapper": "List<Account> m(String n) { return Database.query('SELECT Id FROM Account WHERE Name = \\'' + Util.escapeSoql(n) + '\\''); }",
+ "number": "List<Account> m(Integer n) { return Database.query('SELECT Id FROM Account WHERE Name = \\'' + n + '\\''); }",
+ "outside quotes": "List<Account> m(String where) { return Database.query('SELECT Id FROM Account WHERE ' + where); }",
+ "suppressed": "@SuppressWarnings('PMD.ApexSOQLInjection') List<Account> m(String n) { return Database.query('SELECT Id FROM Account WHERE Name = \\'' + n + '\\''); }",
+ "inline soql": "List<Account> m(String n) { return [SELECT Id FROM Account WHERE Name = :n]; }",
+ "quotes stripped": "List<Account> m(String n) { return Database.query('SELECT Id FROM Account WHERE Name = \\'' + n.replaceAll('[^a-z]', '') + '\\''); }",
+ "suppressed in a list": "@SuppressWarnings('PMD.ApexDoc', 'PMD.ApexSOQLInjection') List<Account> m(String n) { return Database.query('SELECT Id FROM Account WHERE Name = \\'' + n + '\\''); }",
+ "format, quoted placeholder": "List<Account> m(String n) { return Database.query(String.format('SELECT Id FROM Account WHERE Name = \\'{0}\\'', new List<Object>{ n })); }",
+}
+
+
[email protected]("body", _INJECTION_QUIET.values(), ids=_INJECTION_QUIET.keys())
+def test_injection_quiet(body):
+ hits = _hits(f"public with sharing class A {{ {body} }}")
+ assert [h for h in hits if h[0] == "apex_soql_injection"] == []
+
+
+def test_injection_through_a_field_built_in_the_constructor():
+ src = """public with sharing class B implements Database.Batchable<SObject> {
+ String query;
+ public B(String status) { query = 'SELECT Id FROM Account WHERE Status__c = \\'' + status + '\\''; }
+ public Database.QueryLocator start(Database.BatchableContext bc) { return Database.getQueryLocator(query); }
+ }"""
+ assert _hits(src) == [("apex_soql_injection", "start", "status")]
+
+
+def test_injection_through_string_format():
+ src = """public with sharing class A {
+ List<Account> m(String n) {
+ return Database.query(String.format('SELECT Id FROM Account WHERE Name = \\'\\'{0}\\'\\'', new List<Object>{ n }));
+ }
+ }"""
+ assert _hits(src) == [("apex_soql_injection", "m", "n")]
+
+
+# -- apex_missing_sharing -------------------------------------------------------
+
+_SHARING_QUIET = {
+ "declared": "public inherited sharing class A { void m() { update rows; } }",
+ "subclass": "public class A extends Base { void m() { update rows; } }",
+ "test class": "@IsTest private class A { static void m() { update rows; } }",
+ "inner only": "public class A { public with sharing class B { void m() { update rows; } } }",
+ "insert only": "public class A { void m() { insert new Account(); } }",
+ "custom metadata": "public class A { List<X__mdt> m() { return [SELECT Id FROM X__mdt]; } }",
+ "setup object": "public class A { void m() { List<RecordType> r = Database.query('SELECT Id, (SELECT Value FROM Localization) FROM RecordType'); } }",
+ "custom setting": "public class A { My_Settings__c s; void m() { upsert s; } }",
+ "suppressed": "@SuppressWarnings('PMD') public class A { void m() { update rows; } }",
+ "interface": "public interface A { void m(); }",
+ "trigger": "trigger T on Account (before update) { update Trigger.new; }",
+}
+
+
[email protected]("src", _SHARING_QUIET.values(), ids=_SHARING_QUIET.keys())
+def test_missing_sharing_quiet(src):
+ assert [h for h in _hits(src) if h[0] == "apex_missing_sharing"] == []
+
+
+def test_missing_sharing_fires_on_dynamic_query_of_unknown_object():
+ src = "public class A { List<SObject> m(String q) { return Database.query(q); } }"
+ assert _hits(src) == [("apex_missing_sharing", "A", "line 1")]
+
+
+# -- apex_hardcoded_id ----------------------------------------------------------
+
+
+ ("value", "expected"),
+ [
+ ("0051t000002bF3QAAU", True), # 18 chars, valid checksum
+ ("0051t000002bF3QAAA", False), # checksum wrong
+ ("0015f00000QzJ1T", True), # 15 chars, Account key prefix
+ ("001x000xxx35tPN", False), # the site template's placeholder
+ ("zzz1t000002bF3Q", False), # 15 chars, unknown prefix
+ ("001000000000000AAA", False), # all zeros: a placeholder
+ ("AccountServices", False),
+ ("ExampleFeature1", False),
+ ],
+)
+def test_is_record_id(value, expected):
+ assert is_record_id(value) is expected
+
+
+def test_hardcoded_id_quiet_in_fixture_class():
+ src = "public class AccountFixtures { Id m() { return '0051t000002bF3QAAU'; } }"
+ assert _hits(src) == []
+
+
+# -- detectors and scoring --------------------------------------------------------
+
+
+def test_test_files_keep_only_see_all_data():
+ src = (_FIXTURES / "health_markers.cls").read_text(encoding="utf-8")
+ assert {r.biomarker_type for r in detect_all(_ctx(src, is_test=True))} & set(_KINDS) == set()
+ test_src = (_FIXTURES / "HealthMarkersTest.cls").read_text(encoding="utf-8")
+ kinds = [r.biomarker_type for r in detect_all(_ctx(test_src, is_test=True))]
+ assert kinds.count("apex_see_all_data") == 2
+
+
+def test_findings_are_advisory_and_never_deduct():
+ src = (_FIXTURES / "health_markers.cls").read_text(encoding="utf-8")
+ results = [r for r in detect_all(_ctx(src, is_test=False)) if r.biomarker_type in _KINDS]
+ assert {r.biomarker_type for r in results} == set(_KINDS) - {"apex_see_all_data"}
+ for kind in _KINDS:
+ assert dimensions_for(kind) == {"advisory"}
+ assert biomarker_dimension(kind) == "advisory"
+ scores, deductions = score_file(results)
+ assert set(deductions) == {0.0}
+ assert scores["defect"] == scores["maintainability"] == scores["performance"] == 10.0
+
+
[email protected]("call", ["queryWithBinds", "countQueryWithBinds", "getQueryLocatorWithBinds"])
+def test_injection_in_a_with_binds_only_file(call):
+ src = f"""public with sharing class A {{
+ Object m(String n) {{
+ return Database.{call}('SELECT Id FROM Account WHERE Name = \\'' + n + '\\'', new Map<String, Object>(), AccessLevel.USER_MODE);
+ }}
+ }}"""
+ assert _hits(src) == [("apex_soql_injection", "m", "n")]
+
+
+def test_byte_gate_covers_every_dynamic_query_sink():
+ for receiver, methods in _DYNAMIC_QUERY.items():
+ for method in methods:
+ assert _HAS_DYNAMIC_QUERY.search(f"{receiver.title()}.{method} (q)".encode()), method
diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.py
index b7c8eedc4..43af2972f 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -1900,7 +1900,9 @@ _APEX_CASES = [
@pytest.mark.parametrize("src,expected,note", _APEX_CASES, ids=[c[2] for c in _APEX_CASES])
def test_apex_cases(src, expected, note):
- assert _hits("apex", src) == sorted(expected), note
+ # The cases' bare classes declare no sharing; that marker has its own tests.
+ hits = [h for h in _hits("apex", src) if h[0] != "apex_missing_sharing"]
+ assert hits == sorted(expected), note
def test_apex_parameter_switched_sink_is_no_bare_sink():
diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.py
index 412a57957..543952db3 100644
--- a/tests/unit/health/test_scoring_snapshot.py
+++ b/tests/unit/health/test_scoring_snapshot.py
@@ -120,6 +120,10 @@ _EXPECTED_BIOMARKER_CATEGORY = {
"ungoverned_hotspot": "organizational",
"stale_governance": "organizational",
"contradictory_decision": "organizational",
+ "apex_soql_injection": "apex",
+ "apex_missing_sharing": "apex",
+ "apex_hardcoded_id": "apex",
+ "apex_see_all_data": "apex",
}
diff --git a/tests/unit/ingestion/parser/golden/apex.json b/tests/unit/ingestion/parser/golden/apex.json
index d5cdcf86b..d930caaff 100644
--- a/tests/unit/ingestion/parser/golden/apex.json
+++ b/tests/unit/ingestion/parser/golden/apex.json
@@ -1688,6 +1688,968 @@
"references": [],
"schema_refs": []
},
+ "apex/health_markers.cls": {
+ "file_info": {
+ "path": "lang_samples/apex/health_markers.cls",
+ "language": "apex",
+ "size_bytes": 2708,
+ "is_test": false,
+ "is_config": false,
+ "is_api_contract": false,
+ "is_entry_point": false,
+ "is_manifest_entry": false,
+ "is_reachability_root": false
+ },
+ "symbols": [
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers",
+ "name": "HealthMarkers",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers",
+ "kind": "class",
+ "signature": "class HealthMarkers",
+ "start_line": 4,
+ "end_line": 78,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": null,
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::searchText",
+ "name": "searchText",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.searchText",
+ "kind": "variable",
+ "signature": "searchText",
+ "start_line": 7,
+ "end_line": 7,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::byName",
+ "name": "byName",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.byName",
+ "kind": "method",
+ "signature": "byName(String name) -> List<Account>",
+ "start_line": 12,
+ "end_line": 14,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::byBuiltClause",
+ "name": "byBuiltClause",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.byBuiltClause",
+ "kind": "method",
+ "signature": "byBuiltClause(String city) -> List<Account>",
+ "start_line": 16,
+ "end_line": 21,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::bySearchProperty",
+ "name": "bySearchProperty",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.bySearchProperty",
+ "kind": "method",
+ "signature": "bySearchProperty() -> List<List<SObject>>",
+ "start_line": 23,
+ "end_line": 25,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::byNames",
+ "name": "byNames",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.byNames",
+ "kind": "method",
+ "signature": "byNames(List<String> names) -> List<Account>",
+ "start_line": 27,
+ "end_line": 29,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::defaultRecordType",
+ "name": "defaultRecordType",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.defaultRecordType",
+ "kind": "method",
+ "signature": "defaultRecordType() -> Id",
+ "start_line": 31,
+ "end_line": 33,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::escaped",
+ "name": "escaped",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.escaped",
+ "kind": "method",
+ "signature": "escaped(String name) -> List<Account>",
+ "start_line": 37,
+ "end_line": 39,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::escapedFirst",
+ "name": "escapedFirst",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.escapedFirst",
+ "kind": "method",
+ "signature": "escapedFirst(String name) -> List<Account>",
+ "start_line": 41,
+ "end_line": 44,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::bound",
+ "name": "bound",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.bound",
+ "kind": "method",
+ "signature": "bound(String name) -> List<Account>",
+ "start_line": 46,
+ "end_line": 48,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::typedId",
+ "name": "typedId",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.typedId",
+ "kind": "method",
+ "signature": "typedId(Id recordId) -> List<Account>",
+ "start_line": 50,
+ "end_line": 52,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::fieldList",
+ "name": "fieldList",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.fieldList",
+ "kind": "method",
+ "signature": "fieldList(List<String> fields, String objectName) -> List<SObject>",
+ "start_line": 54,
+ "end_line": 57,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::privateField",
+ "name": "privateField",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.privateField",
+ "kind": "method",
+ "signature": "privateField() -> List<Account>",
+ "start_line": 59,
+ "end_line": 61,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::inline",
+ "name": "inline",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.inline",
+ "kind": "method",
+ "signature": "inline() -> List<Account>",
+ "start_line": 63,
+ "end_line": 65,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::notIds",
+ "name": "notIds",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.notIds",
+ "kind": "method",
+ "signature": "notIds() -> void",
+ "start_line": 67,
+ "end_line": 71,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::HealthMarkers::Inner",
+ "name": "Inner",
+ "qualified_name": "lang_samples.apex.health_markers.HealthMarkers.Inner",
+ "kind": "class",
+ "signature": "class Inner",
+ "start_line": 73,
+ "end_line": 77,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkers",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/health_markers.cls::Inner::touch",
+ "name": "touch",
+ "qualified_name": "lang_samples.apex.health_markers.Inner.touch",
+ "kind": "method",
+ "signature": "touch(List<Account> rows) -> void",
+ "start_line": 74,
+ "end_line": 76,
+ "docstring": null,
+ "decorators": [],
+ "visibility": "public",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "Inner",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "public"
+ ],
+ "alias_of": null
+ }
+ ],
+ "imports": [],
+ "exports": [
+ "HealthMarkers"
+ ],
+ "export_aliases": {},
+ "calls": [
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::byName",
+ "line": 13,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "trim",
+ "receiver_name": "city",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::byBuiltClause",
+ "line": 18,
+ "argument_count": 0,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::byBuiltClause",
+ "line": 20,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": [
+ "soql"
+ ]
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Search",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::bySearchProperty",
+ "line": 24,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::byNames",
+ "line": 28,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "join",
+ "receiver_name": "String",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::byNames",
+ "line": 28,
+ "argument_count": 2,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": [
+ null,
+ "String"
+ ],
+ "argument_names": [
+ "names",
+ null
+ ]
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::escaped",
+ "line": 38,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "escapeSingleQuotes",
+ "receiver_name": "String",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::escaped",
+ "line": 38,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": [
+ "name"
+ ]
+ },
+ {
+ "target_name": "escapeSingleQuotes",
+ "receiver_name": "String",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::escapedFirst",
+ "line": 42,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": [
+ "name"
+ ]
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::escapedFirst",
+ "line": 43,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::bound",
+ "line": 47,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::typedId",
+ "line": 51,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::fieldList",
+ "line": 56,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ },
+ {
+ "target_name": "join",
+ "receiver_name": "String",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::fieldList",
+ "line": 56,
+ "argument_count": 2,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": [
+ null,
+ "String"
+ ],
+ "argument_names": [
+ "fields",
+ null
+ ]
+ },
+ {
+ "target_name": "query",
+ "receiver_name": "Database",
+ "caller_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::privateField",
+ "line": 60,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ }
+ ],
+ "heritage": [],
+ "docstring": null,
+ "parse_errors": [],
+ "content_hash": "437b2b8db7896dce8a88bc2921875fa183f555b2bf8992c4793c1f4da834601b",
+ "type_refs": [
+ {
+ "type_name": "Account",
+ "line": 12,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 16,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 27,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 37,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 41,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 46,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 50,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 59,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 63,
+ "origin": "method_param"
+ },
+ {
+ "type_name": "Account",
+ "line": 74,
+ "origin": "param_type"
+ }
+ ],
+ "local_refs": [],
+ "registrars": [],
+ "references": [],
+ "schema_refs": [
+ {
+ "source_symbol_id": "lang_samples/apex/health_markers.cls::Inner::touch",
+ "object_name": "Account",
+ "line": 75,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::inline",
+ "object_name": "Account",
+ "line": 64,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::inline",
+ "object_name": "Account",
+ "line": 64,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/health_markers.cls::HealthMarkers::inline",
+ "object_name": "Account",
+ "line": 64,
+ "path": [
+ "OwnerId"
+ ]
+ }
+ ]
+ },
+ "apex/HealthMarkersTest.cls": {
+ "file_info": {
+ "path": "lang_samples/apex/HealthMarkersTest.cls",
+ "language": "apex",
+ "size_bytes": 545,
+ "is_test": false,
+ "is_config": false,
+ "is_api_contract": false,
+ "is_entry_point": false,
+ "is_manifest_entry": false,
+ "is_reachability_root": false
+ },
+ "symbols": [
+ {
+ "id": "lang_samples/apex/HealthMarkersTest.cls::HealthMarkersTest",
+ "name": "HealthMarkersTest",
+ "qualified_name": "lang_samples.apex.HealthMarkersTest.HealthMarkersTest",
+ "kind": "class",
+ "signature": "class HealthMarkersTest",
+ "start_line": 2,
+ "end_line": 19,
+ "docstring": null,
+ "decorators": [
+ "@IsTest(SeeAllData=true)\nprivate"
+ ],
+ "visibility": "private",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": null,
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "private"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/HealthMarkersTest.cls::HealthMarkersTest::readsOrgData",
+ "name": "readsOrgData",
+ "qualified_name": "lang_samples.apex.HealthMarkersTest.HealthMarkersTest.readsOrgData",
+ "kind": "method",
+ "signature": "readsOrgData() -> void",
+ "start_line": 4,
+ "end_line": 8,
+ "docstring": null,
+ "decorators": [
+ "@isTest(seeAllData = true)\n static"
+ ],
+ "visibility": "private",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkersTest",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "static"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/HealthMarkersTest.cls::HealthMarkersTest::ownData",
+ "name": "ownData",
+ "qualified_name": "lang_samples.apex.HealthMarkersTest.HealthMarkersTest.ownData",
+ "kind": "method",
+ "signature": "ownData() -> void",
+ "start_line": 10,
+ "end_line": 13,
+ "docstring": null,
+ "decorators": [
+ "@IsTest(SeeAllData=false)\n static"
+ ],
+ "visibility": "private",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkersTest",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "static"
+ ],
+ "alias_of": null
+ },
+ {
+ "id": "lang_samples/apex/HealthMarkersTest.cls::HealthMarkersTest::suppressed",
+ "name": "suppressed",
+ "qualified_name": "lang_samples.apex.HealthMarkersTest.HealthMarkersTest.suppressed",
+ "kind": "method",
+ "signature": "suppressed() -> void",
+ "start_line": 15,
+ "end_line": 18,
+ "docstring": null,
+ "decorators": [
+ "@IsTest(SeeAllData=true)\n @SuppressWarnings('PMD.ApexUnitTestShouldNotUseSeeAllDataTrue')\n static"
+ ],
+ "visibility": "private",
+ "is_async": false,
+ "complexity_estimate": 1,
+ "language": "apex",
+ "parent_name": "HealthMarkersTest",
+ "is_exported_symbol": false,
+ "is_declaration": false,
+ "type_parameter_count": null,
+ "extension_receiver": null,
+ "written_receiver": null,
+ "modifiers": [
+ "static"
+ ],
+ "alias_of": null
+ }
+ ],
+ "imports": [],
+ "exports": [],
+ "export_aliases": {},
+ "calls": [
+ {
+ "target_name": "assertNotEquals",
+ "receiver_name": "System",
+ "caller_symbol_id": "lang_samples/apex/HealthMarkersTest.cls::HealthMarkersTest::readsOrgData",
+ "line": 7,
+ "argument_count": 2,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": [
+ null,
+ "fixtureId"
+ ]
+ },
+ {
+ "target_name": "Account",
+ "receiver_name": null,
+ "caller_symbol_id": "lang_samples/apex/HealthMarkersTest.cls::HealthMarkersTest::ownData",
+ "line": 12,
+ "argument_count": 1,
+ "receiver_call": null,
+ "scope_name": null,
+ "edge_type": "calls",
+ "supplied_props": null,
+ "bare_name_fallback": false,
+ "spawned": false,
+ "argument_types": null,
+ "argument_names": null
+ }
+ ],
+ "heritage": [],
+ "docstring": null,
+ "parse_errors": [],
+ "content_hash": "ee0b625d872285a30bc7a789d76e01feadef22aaacfda9214f6b1a36f94e9c5f",
+ "type_refs": [
+ {
+ "type_name": "Account",
+ "line": 12,
+ "origin": "composite_literal"
+ }
+ ],
+ "local_refs": [],
+ "registrars": [],
+ "references": [],
+ "schema_refs": [
+ {
+ "source_symbol_id": "lang_samples/apex/HealthMarkersTest.cls::HealthMarkersTest::ownData",
+ "object_name": "Account",
+ "line": 12,
+ "path": []
+ }
+ ]
+ },
"apex/nested.cls": {
"file_info": {
"path": "lang_samples/apex/nested.cls",