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.

fix(workspace): trace Apex callouts through wrapper methods (#4532)

arnavsx3ff8531e3f4f5
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/apex_callouts.py b/packages/core/src/repowise/core/workspace/extractors/http/apex_callouts.py
index 0fbd878db..3ddc99cea 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/apex_callouts.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/apex_callouts.py
@@ -8,11 +8,13 @@ An Apex callout is a ``System.HttpRequest`` configured statement by statement::
new Http().send(req);
A row needs, inside one method, an ``HttpRequest`` declared there (or taken as
-a parameter), its ``setEndpoint`` and exactly one literal verb; anything else is
+a parameter), its ``setEndpoint`` and exactly one resolved verb; anything else is
refused rather than guessed. The endpoint must be an absolute URL or
``callout:Name/path``, whose credential name becomes the call's base token
(the ``${API_BASE}/users`` shape) for ``service_bases`` to map. A name folds
-only as a ``final`` field or a local the method assigns once, never a parameter.
+only as a ``final`` field or a local the method assigns once. An endpoint
+parameter can instead read literal arguments at unambiguous same-class calls
+to its wrapper, one level only; a verb parameter must resolve at that call too.
Ceiling: the Named Credential's own ``.xml`` endpoint is not read; reading it
would add a host and path prefix to each ``callout:`` row.
@@ -58,6 +60,9 @@ _CALLOUT_RE = re.compile(
)
_ABSOLUTE_RE = re.compile(r"https?://[^/$?]+(?:[/?]|$)", re.IGNORECASE)
+_METHOD_HEADER_RE = re.compile(r"\b(?P<name>[A-Za-z_]\w*)\s*\([^()]*\)\s*$")
+_LITERAL_RE = re.compile(r"'(?:[^'\\]|\\.)*'", re.DOTALL)
+
def _blocks(code: str) -> list[tuple[int, int, bool]]:
"""``(open, close, is_type_body)`` per brace block of comment- and string-blanked *code*."""
@@ -100,13 +105,23 @@ def _method_scope(
return None
-def _verb(content: str, code: str, recv: str, start: int, end: int) -> str | None:
+def _verb(
+ content: str,
+ code: str,
+ recv: str,
+ start: int,
+ end: int,
+ bindings: dict[str, str | None] | None = None,
+) -> str | None:
"""The one literal verb *recv*'s ``setMethod`` calls name in ``[start, end)``, else None."""
pattern = re.compile(rf"\b{re.escape(recv)}\s*\.\s*setMethod\s*\(", re.IGNORECASE)
verbs: set[str | None] = set()
for m in pattern.finditer(code, start, end):
args = call_arguments(content, m.end() - 1)
- verbs.add(method_from_argument(args[0]) if args and len(args) == 1 else None)
+ expr = args[0] if args and len(args) == 1 else None
+ if expr is not None and bindings is not None:
+ expr = bindings.get(expr.lower(), expr)
+ verbs.add(method_from_argument(expr) if expr is not None else None)
if len(verbs) != 1:
return None
return verbs.pop()
@@ -182,6 +197,109 @@ def _url(
return resolve_string(_cut_query(expr), APEX_SYNTAX, constants)
+def _type_scope(blocks: list[tuple[int, int, bool]], offset: int) -> tuple[int, int, bool] | None:
+ """The innermost class/interface/enum containing *offset*."""
+ return max(
+ (b for b in blocks if b[2] and b[0] < offset < b[1]),
+ default=None,
+ )
+
+
+def _wrapper_calls(
+ content: str,
+ code: str,
+ blocks: list[tuple[int, int, bool]],
+ scope: tuple[int, int],
+ recv: str,
+ expr: str,
+) -> list[tuple[str, str, int]]:
+ """``(verb, URL, caller offset)`` for literal calls to an endpoint wrapper."""
+ start, end = scope
+ body = code.find("{", start, end)
+ header = code[start:body] if body != -1 else ""
+ method = _METHOD_HEADER_RE.search(header)
+ owner = _type_scope(blocks, start)
+ if method is None or owner is None:
+ return []
+ # Angle brackets nest type arguments in declarations, like brackets nest
+ # expressions at a call site. Keep their commas out of parameter splitting.
+ params = call_arguments(
+ header.replace("<", "[").replace(">", "]"), header.index("(", method.start())
+ )
+ if not params or any(not p for p in params):
+ return []
+ names = [p.rsplit(None, 1)[-1].lower() for p in params]
+ if expr.lower() not in names or len(set(names)) != len(names):
+ return []
+ endpoint_pos = names.index(expr.lower())
+ name = method.group("name")
+ pattern = re.compile(rf"\b{re.escape(name)}\s*\(", re.IGNORECASE)
+ sites = [m for m in pattern.finditer(code) if _type_scope(blocks, m.start()) == owner]
+ # Headers live directly in the type body, as do field initializers. Only
+ # a declaration prefix (modifiers and a return type) counts as an overload.
+ declarations: set[int] = set()
+ for site in sites:
+ if _method_scope(blocks, code, site.start()) is not None:
+ continue
+ boundary = max(
+ code.rfind("{", 0, site.start()),
+ code.rfind("}", 0, site.start()),
+ code.rfind(";", 0, site.start()),
+ )
+ prefix = re.sub(r"@\w+(?:\s*\([^()]*\))?", "", code[boundary + 1 : site.start()]).strip()
+ if prefix and re.fullmatch(r"[\w.<>,\[\]\s]+", prefix):
+ declarations.add(site.start())
+ if declarations != {start + method.start("name")}:
+ return []
+ mutated = {
+ n
+ for n in names
+ if re.search(
+ rf"(?<![.\w]){re.escape(n)}\s*[-+*/%&|^]?=(?!=)", code[body:end], re.IGNORECASE
+ )
+ }
+ type_header = code[
+ max(
+ code.rfind("{", 0, owner[0]), code.rfind("}", 0, owner[0]), code.rfind(";", 0, owner[0])
+ )
+ + 1 : owner[0]
+ ]
+ type_name = re.search(r"\bclass\s+([A-Za-z_]\w*)", type_header, re.IGNORECASE)
+ out: list[tuple[str, str, int]] = []
+ for site in sites:
+ if site.start() in declarations:
+ continue
+ prefix = code[: site.start()].rstrip()
+ before = prefix
+ if prefix.endswith("."):
+ qualifier = re.search(r"(?<![.\w])([A-Za-z_]\w*)\s*\.\s*$", prefix)
+ if qualifier is None or prefix[: qualifier.start()].rstrip().endswith("."):
+ continue
+ before = prefix[: qualifier.start()]
+ receiver = qualifier.group(1)
+ if receiver.lower() != "this" and (
+ type_name is None
+ or receiver.lower() != type_name.group(1).lower()
+ or _declared_in(code, receiver, owner[0], owner[1])
+ ):
+ continue
+ if re.search(r"\bnew\s*$", before, re.IGNORECASE):
+ continue # constructing a same-named type does not invoke the wrapper
+ args = call_arguments(content, site.end() - 1)
+ if args is None or len(args) != len(names):
+ continue
+ bindings = {
+ n: arg if n not in mutated and _LITERAL_RE.fullmatch(arg) else None
+ for n, arg in zip(names, args, strict=True)
+ }
+ literal = bindings[names[endpoint_pos]]
+ url = resolve_string(literal, APEX_SYNTAX) if literal is not None else None
+ verb = _verb(content, code, recv, start, end, bindings)
+ if url is not None and verb is not None:
+ out.append((verb, url, site.start()))
+ return out
+
+
class ApexCalloutsDialect:
name = "apex-callouts"
extensions = APEX
@@ -208,23 +326,29 @@ class ApexCalloutsDialect:
continue # not a request this method holds
method = _verb(content, code, recv, start, end)
args = call_arguments(content, m.end() - 1)
- if method is None or not args or len(args) != 1:
+ if not args or len(args) != 1:
continue
if constants is None:
constants = _final_fields(content, code)
url = _url(content, code, args[0], scope, constants)
- endpoint = _endpoint(url) if url is not None else None
- if endpoint is None:
- continue
- c = build_consumer_contract(
- ctx,
- method=method,
- url=endpoint,
- client="apex-callout",
- line=line_at(content, m.start()),
- origin=ContractOrigin.CLIENT_CALL,
+ sites = (
+ [(method, url, m.start())]
+ if method is not None and url is not None
+ else _wrapper_calls(content, code, blocks, scope, recv, args[0])
)
- if c is not None:
- c.symbol_name = f"apex-callout:{method} {url}" # as written, not rewritten
- out.append(c)
+ for method, url, offset in sites:
+ endpoint = _endpoint(url)
+ if endpoint is None:
+ continue
+ c = build_consumer_contract(
+ ctx,
+ method=method,
+ url=endpoint,
+ client="apex-callout",
+ line=line_at(content, offset),
+ origin=ContractOrigin.CLIENT_CALL,
+ )
+ if c is not None:
+ c.symbol_name = f"apex-callout:{method} {url}" # as written, not rewritten
+ out.append(c)
return out
diff --git a/tests/unit/workspace/test_apex_http.py b/tests/unit/workspace/test_apex_http.py
index d28e2048a..c7d8e7491 100644
--- a/tests/unit/workspace/test_apex_http.py
+++ b/tests/unit/workspace/test_apex_http.py
@@ -2,14 +2,16 @@
A provider is a ``@RestResource`` class's verb-annotated method, served under
``/services/apexrest``. A consumer is an ``HttpRequest`` whose endpoint and one
-verb are both literal inside one method; anything the file does not settle is
-refused rather than guessed.
+verb resolve inside one method or at its wrapper's literal call sites; anything
+the file does not settle is refused rather than guessed.
"""
from __future__ import annotations
from pathlib import Path
+import pytest
+
from repowise.core.ingestion.framework_routes import apex_rest_routes
from repowise.core.workspace.extractors.base import ScanContext
from repowise.core.workspace.extractors.http import HttpExtractor
@@ -336,6 +338,208 @@ class TestApexCalloutConsumer:
assert ids(source) == set()
+WRAPPER = """public class Client {
+ private HttpResponse makeApiCall(String endpoint, String method) {
+ HttpRequest req = new HttpRequest();
+ req.setEndpoint(endpoint);
+ req.setMethod(method);
+ return new Http().send(req);
+ }
+ public void run(String endpoint, String method) {
+ CALLS
+ }
+ MEMBERS
+}
+"""
+
+
+def wrapper(calls: str, members: str = "") -> str:
+ return WRAPPER.replace("CALLS", calls).replace("MEMBERS", members)
+
+
+class TestApexCalloutWrapper:
+ def test_literal_arguments_record_the_callers_line(self) -> None:
+ source = wrapper("makeApiCall('callout:Billing/invoices', 'GET');")
+ [c] = contracts(source)
+ assert c.contract_id == "http::GET::/invoices"
+ assert c.line == 9
+ assert c.meta["base_token"] == "Billing"
+ assert c.meta["client"] == "apex-callout"
+ assert c.symbol_name == "apex-callout:GET callout:Billing/invoices"
+ assert c.origin == "client_call"
+ assert c.confidence == 0.75
+
+ def test_each_caller_supplies_its_own_endpoint_and_verb(self) -> None:
+ source = wrapper(
+ "makeApiCall('callout:Billing/invoices', 'GET');\n"
+ " makeApiCall('https://billing.example.com/payments', 'POST');\n"
+ " makeApiCall('callout:Billing/invoices', 'GET');"
+ )
+ rows = contracts(source)
+ assert [(c.contract_id, c.line) for c in rows] == [
+ ("http::GET::/invoices", 9),
+ ("http::POST::/payments", 10),
+ ("http::GET::/invoices", 11),
+ ]
+ assert rows[1].meta["host"] == "billing.example.com"
+
+ @pytest.mark.parametrize(
+ "args",
+ [
+ "endpoint, 'GET'",
+ "'callout:Billing/' + endpoint, 'GET'",
+ "'callout:Billing/' + 'invoices', 'GET'",
+ "getEndpoint(), 'GET'",
+ "URL, 'GET'",
+ "'callout:Billing/invoices', method",
+ "'callout:Billing/invoices', 'G' + 'ET'",
+ "'callout:Billing/invoices', 'INVALID'",
+ "'callout:Billing/invoices'",
+ "'callout:Billing/invoices', 'GET', true",
+ ],
+ )
+ def test_non_literal_or_invalid_arguments_add_nothing(self, args: str) -> None:
+ source = wrapper(
+ f"makeApiCall({args});",
+ "static final String URL = 'callout:Billing/invoices';",
+ )
+ assert ids(source) == set()
+
+ def test_a_literal_verb_inside_the_wrapper_still_works(self) -> None:
+ source = wrapper("makeApiCall('callout:Billing/invoices', method);")
+ source = source.replace("req.setMethod(method)", "req.setMethod('POST')")
+ assert ids(source) == {"http::POST::/invoices"}
+
+ def test_an_unresolved_caller_does_not_hide_a_literal_caller(self) -> None:
+ source = wrapper(
+ "makeApiCall(endpoint, method);\n"
+ " makeApiCall('callout:Billing/invoices', 'GET');"
+ )
+ [c] = contracts(source)
+ assert c.contract_id == "http::GET::/invoices"
+ assert c.line == 10
+
+ @pytest.mark.parametrize("prefix", ["new ", "NEW Client."])
+ def test_a_constructor_with_the_same_name_is_not_a_wrapper_call(self, prefix: str) -> None:
+ source = wrapper(
+ f"{prefix}makeApiCall('callout:Wrong/constructor', 'GET');",
+ "class makeApiCall { public makeApiCall(String endpoint, String method) {} }",
+ )
+ assert ids(source) == set()
+
+ @pytest.mark.parametrize("verb", ["", "req.setMethod('DELETE');", "req.setMethod(other);"])
+ def test_missing_or_conflicting_verbs_are_refused(self, verb: str) -> None:
+ source = wrapper("makeApiCall('callout:Billing/invoices', 'GET');")
+ if not verb:
+ source = source.replace("req.setMethod(method);", "")
+ else:
+ source = source.replace("req.setMethod(method);", f"req.setMethod(method); {verb}")
+ assert ids(source) == set()
+
+ def test_repeated_setters_that_resolve_to_the_same_verb_are_unambiguous(self) -> None:
+ source = wrapper("makeApiCall('callout:Billing/invoices', 'GET');")
+ source = source.replace("req.setMethod(method);", "req.setMethod(method); req.setMethod('GET');")
+ assert ids(source) == {"http::GET::/invoices"}
+
+ @pytest.mark.parametrize("url", ["/relative/path", "callout:", "ftp://example.com/path"])
+ def test_unusable_literal_endpoints_are_refused(self, url: str) -> None:
+ assert ids(wrapper(f"makeApiCall('{url}', 'GET');")) == set()
+
+ def test_a_call_inside_a_nested_block_uses_the_enclosing_class(self) -> None:
+ source = wrapper("if (endpoint == null) { makeApiCall('callout:Billing/invoices', 'GET'); }")
+ assert ids(source) == {"http::GET::/invoices"}
+
+ def test_a_wrapper_inside_an_inner_class_has_its_own_call_sites(self) -> None:
+ source = "class Outer {\n" + wrapper("this.makeApiCall('callout:Billing/invoices', 'GET');") + "}\n"
+ assert ids(source) == {"http::GET::/invoices"}
+
+ def test_a_verb_parameter_named_after_a_verb_still_requires_a_literal(self) -> None:
+ source = wrapper("makeApiCall('callout:Billing/invoices', method);")
+ source = source.replace("String method)", "String GET)").replace("setMethod(method)", "setMethod(GET)")
+ assert ids(source) == set()
+
+ def test_a_field_initializer_call_is_not_an_overload(self) -> None:
+ source = wrapper(
+ "makeApiCall('callout:Billing/invoices', 'GET');",
+ "HttpResponse initial = makeApiCall('callout:Billing/payments', 'POST');",
+ )
+ assert ids(source) == {"http::GET::/invoices", "http::POST::/payments"}
+
+ def test_annotations_and_case_insensitive_parameters(self) -> None:
+ source = wrapper("makeApiCall('callout:Billing/invoices', 'GET');")
+ source = source.replace(
+ "private HttpResponse", "@AuraEnabled(cacheable=true) public static HttpResponse"
+ )
+ source = source.replace("setEndpoint(endpoint)", "setEndpoint(ENDPOINT)")
+ source = source.replace("setMethod(method)", "setMethod(METHOD)")
+ assert ids(source) == {"http::GET::/invoices"}
+
+ @pytest.mark.parametrize(
+ "member",
+ [
+ "void makeApiCall(String endpoint) {}",
+ "void MAKEAPICALL(String endpoint, Integer method) {}",
+ "abstract HttpResponse makeApiCall(String endpoint);",
+ ],
+ )
+ def test_overloads_are_refused(self, member: str) -> None:
+ assert ids(wrapper("makeApiCall('callout:Billing/invoices', 'GET');", member)) == set()
+
+ def test_a_forwarded_parameter_is_not_traced_a_second_level(self) -> None:
+ source = wrapper(
+ "forward('callout:Billing/invoices', 'GET');",
+ "void forward(String endpoint, String method) { makeApiCall(endpoint, method); }",
+ )
+ assert ids(source) == set()
+
+ @pytest.mark.parametrize("receiver", ["", "this.", "Client.", "THIS . "])
+ def test_unambiguous_same_class_receivers(self, receiver: str) -> None:
+ source = wrapper(f"{receiver}MAKEAPICALL('callout:Billing/invoices', 'GET');")
+ assert ids(source) == {"http::GET::/invoices"}
+
+ @pytest.mark.parametrize(
+ "receiver", ["other.", "OtherClass.", "holder.Client.", "getClient()."]
+ )
+ def test_calls_on_other_objects_are_refused(self, receiver: str) -> None:
+ assert ids(wrapper(f"{receiver}makeApiCall('callout:Billing/invoices', 'GET');")) == set()
+
+ def test_callers_and_overloads_in_other_classes_are_ignored(self) -> None:
+ source = wrapper(
+ "makeApiCall('callout:Billing/invoices', 'GET');",
+ "class Inner { void run() { makeApiCall('callout:Wrong/inner', 'DELETE'); } "
+ "void makeApiCall(String endpoint) {} }",
+ )
+ source += (
+ "class Other { void run() { Client.makeApiCall('callout:Wrong/outer', 'POST'); } }"
+ )
+ assert ids(source) == {"http::GET::/invoices"}
+
+ def test_comments_and_strings_do_not_count_as_call_sites(self) -> None:
+ source = wrapper(
+ "// makeApiCall('callout:Wrong/comment', 'GET');\n"
+ r"String example = 'makeApiCall(\'callout:Wrong/string\', \'GET\');';"
+ )
+ assert ids(source) == set()
+
+ @pytest.mark.parametrize(
+ "assignment",
+ ["endpoint = 'callout:Wrong/path';", "endpoint += '/more';", "method = 'DELETE';"],
+ )
+ def test_reassigned_parameters_are_not_read_from_the_caller(self, assignment: str) -> None:
+ source = wrapper("makeApiCall('callout:Billing/invoices', 'GET');")
+ source = source.replace("HttpRequest req", f"{assignment}\n HttpRequest req")
+ assert ids(source) == set()
+
+ def test_argument_positions_and_nested_arguments(self) -> None:
+ source = wrapper("makeApiCall(buildOptions('a', 'b'), 'GET', 'callout:Billing/invoices');")
+ source = source.replace(
+ "String endpoint, String method",
+ "Map<String, String> options, String method, String endpoint",
+ 1,
+ )
+ assert ids(source) == {"http::GET::/invoices"}
+
+
JS_CONSUMER = """export async function load(id) {
return fetch(`/services/apexrest/integration-service/${id}`);
}