@dataparade/cli 0.0.31 → 0.0.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/package.json +2 -2
- package/dist/src/ai-enrichment/fallbacks.js +12 -1
- package/dist/src/cli.js +3 -0
- package/dist/src/core/pipeline/omit-internal-implementation.js +13 -6
- package/dist/src/output/git-context.d.ts +17 -0
- package/dist/src/output/git-context.js +104 -0
- package/dist/tests/unit/ai-enrichment/fallbacks.spec.js +30 -0
- package/dist/tests/unit/core/omit-internal-implementation.spec.js +21 -0
- package/dist/tests/unit/output/git-context.spec.d.ts +1 -0
- package/dist/tests/unit/output/git-context.spec.js +79 -0
- package/dist/vendor/scanner/dist/src/analyzers/python/python-detection-config.d.ts +11 -0
- package/dist/vendor/scanner/dist/src/analyzers/python/python-detection-config.js +2 -0
- package/dist/vendor/scanner/dist/src/analyzers/registry.d.ts +2 -0
- package/dist/vendor/scanner/dist/src/analyzers/registry.js +3 -2
- package/dist/vendor/scanner/dist/src/analyzers/typescript/typescript-detection-config.d.ts +17 -0
- package/dist/vendor/scanner/dist/src/analyzers/typescript/typescript-detection-config.js +11 -0
- package/dist/vendor/scanner/dist/src/classifier/component-factory.js +33 -3
- package/dist/vendor/scanner/dist/src/classifier/enhance.js +14 -0
- package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.d.ts +8 -0
- package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.js +43 -2
- package/dist/vendor/scanner/dist/src/classifier/postprocessing.js +4 -1
- package/dist/vendor/scanner/dist/src/config/third-party-detection-config.d.ts +41 -0
- package/dist/vendor/scanner/dist/src/config/third-party-detection-config.js +65 -1
- package/dist/vendor/scanner/dist/src/core/pipeline/structural-scan.js +2 -0
- package/dist/vendor/scanner/dist/src/eval/canonical/scanner/components.d.ts +5 -0
- package/dist/vendor/scanner/dist/src/eval/canonical/scanner/components.js +10 -2
- package/dist/vendor/scanner/dist/src/eval/canonical/scanner/data-flows.js +4 -4
- package/dist/vendor/scanner/dist/src/patterns/config.js +7 -1
- package/dist/vendor/scanner/dist/src/patterns/detectors/git-remote-owner.d.ts +14 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/git-remote-owner.js +108 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python-outbound-http.d.ts +93 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python-outbound-http.js +1206 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python-source.d.ts +180 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python-source.js +1022 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python.d.ts +6 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/python.js +49 -1
- package/dist/vendor/scanner/dist/src/patterns/detectors/repo-declared-domains.d.ts +2 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/repo-declared-domains.js +80 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/source-module-index.d.ts +23 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/source-module-index.js +145 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/typescript-outbound-http.d.ts +30 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/typescript-outbound-http.js +575 -0
- package/dist/vendor/scanner/dist/src/patterns/detectors/typescript.js +12 -0
- package/dist/vendor/scanner/dist/src/patterns/engine.js +6 -1
- package/dist/vendor/scanner/patterns/classifier/third-party.classifier.yaml +188 -0
- package/dist/vendor/scanner/patterns/python.patterns.yaml +10 -0
- package/dist/vendor/scanner/patterns/third-party.patterns.yaml +246 -0
- package/dist/vendor/scanner/patterns/typescript.patterns.yaml +21 -0
- package/package.json +2 -2
|
@@ -0,0 +1,1206 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Python outbound HTTP destinations (DATAP-818).
|
|
4
|
+
*
|
|
5
|
+
* Finds request calls made with a raw HTTP library (httpx, requests, aiohttp), with an
|
|
6
|
+
* OpenAI-compatible client pointed at another provider, with an MCP-over-HTTP client, with
|
|
7
|
+
* Phoenix tracing, or through an unresolved `(method, url)` helper, and resolves the URL the
|
|
8
|
+
* call reaches in the same file. A known host names the third party; an unknown host gives an
|
|
9
|
+
* outbound-HTTP finding with no vendor. The HTTP library is never the destination.
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.DestinationRouter = exports.OUTBOUND_HTTP_UNKNOWN_FINDING_NAME = void 0;
|
|
13
|
+
exports.detectPythonOutboundHttp = detectPythonOutboundHttp;
|
|
14
|
+
exports.remoteServiceProperties = remoteServiceProperties;
|
|
15
|
+
exports.remoteServiceName = remoteServiceName;
|
|
16
|
+
const external_url_third_party_1 = require("../../classifier/external-url-third-party");
|
|
17
|
+
const organization_domains_scan_scope_1 = require("../../classifier/organization-domains-scan-scope");
|
|
18
|
+
const third_party_detection_config_1 = require("../../config/third-party-detection-config");
|
|
19
|
+
const git_remote_owner_1 = require("./git-remote-owner");
|
|
20
|
+
const source_module_index_1 = require("./source-module-index");
|
|
21
|
+
const python_source_1 = require("./python-source");
|
|
22
|
+
/** Finding name for an outbound HTTP call whose destination host is not known. */
|
|
23
|
+
exports.OUTBOUND_HTTP_UNKNOWN_FINDING_NAME = "outbound_http_call";
|
|
24
|
+
const MAX_VALUES = 8;
|
|
25
|
+
const MAX_DEPTH = 12;
|
|
26
|
+
const MAX_CALLER_HOPS = 3;
|
|
27
|
+
const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
|
|
28
|
+
const REQUEST_VERBS = new Set(["get", "post", "put", "patch", "delete", "head", "options", "request", "stream"]);
|
|
29
|
+
const METHOD_FIRST_VERBS = new Set(["request", "stream"]);
|
|
30
|
+
const STRING_METHODS = new Set(["rstrip", "strip", "lstrip", "lower", "format", "removesuffix", "removeprefix", "encode"]);
|
|
31
|
+
const OPENAI_CLIENTS = new Set(["OpenAI", "AsyncOpenAI"]);
|
|
32
|
+
const VALIDATOR_METHODS = new Set(["validate_python", "validate_strings", "validate_json", "parse_obj_as"]);
|
|
33
|
+
const LITELLM_CALLS = new Set(["completion", "acompletion", "text_completion", "atext_completion", "embedding", "aembedding", "responses", "aresponses"]);
|
|
34
|
+
const MCP_URL_CALLS = new Set(["streamablehttp_client", "streamable_http_client", "sse_client"]);
|
|
35
|
+
const MCP_URL_PARAMS = new Set(["StreamableHTTPServerParams", "SseServerParams", "StreamableHTTPConnectionParams", "SseConnectionParams"]);
|
|
36
|
+
/** Packages that are plumbing, never destinations, besides the configured HTTP clients. */
|
|
37
|
+
const EXTRA_LIBRARY_NAMES = ["httpx_retries", "urllib3", "tenacity"];
|
|
38
|
+
const MAX_SYMBOL_DEPTH = 8;
|
|
39
|
+
// ── Value resolution ──────────────────────────────────────────────────────
|
|
40
|
+
class Resolver {
|
|
41
|
+
constructor(model, filePath) {
|
|
42
|
+
this.model = model;
|
|
43
|
+
this.active = new Set();
|
|
44
|
+
/** Module scope -> its model and repo-relative path (the scanned file and imported modules). */
|
|
45
|
+
this.modules = new Map();
|
|
46
|
+
this.loaded = new Map();
|
|
47
|
+
this.modules.set(model.module, { model, path: filePath, id: 0 });
|
|
48
|
+
this.loaded.set(filePath, model.module);
|
|
49
|
+
}
|
|
50
|
+
rootOf(scope) {
|
|
51
|
+
let current = scope;
|
|
52
|
+
while (current.parent)
|
|
53
|
+
current = current.parent;
|
|
54
|
+
return current;
|
|
55
|
+
}
|
|
56
|
+
moduleOf(scope) {
|
|
57
|
+
return this.modules.get(this.rootOf(scope)) ?? { model: this.model, path: "", id: 0 };
|
|
58
|
+
}
|
|
59
|
+
moduleModelOf(scope) {
|
|
60
|
+
return this.moduleOf(scope).model;
|
|
61
|
+
}
|
|
62
|
+
text(scope, expr) {
|
|
63
|
+
return (0, python_source_1.exprText)(this.moduleOf(scope).model, expr);
|
|
64
|
+
}
|
|
65
|
+
/** Module scope of a same-repo import seen from `fromScope`'s file, loaded on demand. */
|
|
66
|
+
loadModule(fromScope, spec) {
|
|
67
|
+
const from = this.moduleOf(fromScope).path;
|
|
68
|
+
const path = (0, source_module_index_1.resolvePythonModulePath)(from, spec);
|
|
69
|
+
if (!path)
|
|
70
|
+
return undefined;
|
|
71
|
+
if (this.loaded.has(path))
|
|
72
|
+
return this.loaded.get(path);
|
|
73
|
+
const source = (0, source_module_index_1.pythonModuleSource)(path);
|
|
74
|
+
let root;
|
|
75
|
+
if (source !== undefined) {
|
|
76
|
+
const model = (0, python_source_1.buildPySourceModel)(source);
|
|
77
|
+
root = model.module;
|
|
78
|
+
this.modules.set(root, { model, path, id: this.modules.size });
|
|
79
|
+
}
|
|
80
|
+
this.loaded.set(path, root);
|
|
81
|
+
return root;
|
|
82
|
+
}
|
|
83
|
+
eval(expr, ctx) {
|
|
84
|
+
if (ctx.depth > MAX_DEPTH)
|
|
85
|
+
return [];
|
|
86
|
+
const key = `${this.moduleOf(ctx.scope).id}:${expr.start}:${expr.end}:${ctx.hops}:${ctx.bindings ? [...ctx.bindings.keys()].join(",") : ""}`;
|
|
87
|
+
if (this.active.has(key))
|
|
88
|
+
return [];
|
|
89
|
+
this.active.add(key);
|
|
90
|
+
try {
|
|
91
|
+
return cap(this.evalInner(expr, { ...ctx, depth: ctx.depth + 1 }));
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
this.active.delete(key);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
evalInner(expr, ctx) {
|
|
98
|
+
switch (expr.kind) {
|
|
99
|
+
case "str": {
|
|
100
|
+
let acc = [{ text: "", sites: [], hint: "" }];
|
|
101
|
+
for (const part of expr.parts) {
|
|
102
|
+
if (typeof part === "string") {
|
|
103
|
+
acc = acc.map((v) => ({ ...v, text: v.text + part }));
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const values = this.eval(part, ctx);
|
|
107
|
+
const pieces = values.length > 0 ? values : [placeholder(this.text(ctx.scope, part))];
|
|
108
|
+
acc = product(acc, pieces);
|
|
109
|
+
}
|
|
110
|
+
return acc;
|
|
111
|
+
}
|
|
112
|
+
case "name":
|
|
113
|
+
return this.resolveName(expr.id, ctx);
|
|
114
|
+
case "attr": {
|
|
115
|
+
const base = (0, python_source_1.dottedName)(expr.object);
|
|
116
|
+
if (base === "self" || base === "cls")
|
|
117
|
+
return this.resolveSelfAttr(expr.attr, ctx);
|
|
118
|
+
// `settings.BASE_URL` where `settings` is a class, an instance or a module (DATAP-818).
|
|
119
|
+
const sym = this.symbolOf(expr.object, ctx.scope, ctx.line, 0);
|
|
120
|
+
if (sym?.kind === "class")
|
|
121
|
+
return this.classAttr(sym.scope, expr.attr, ctx);
|
|
122
|
+
if (sym?.kind === "module")
|
|
123
|
+
return this.resolveName(expr.attr, { scope: sym.root, line: Number.MAX_SAFE_INTEGER, hops: 0, depth: ctx.depth });
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
case "coll":
|
|
127
|
+
return expr.elts.flatMap((e) => this.eval(e, ctx));
|
|
128
|
+
case "subscript":
|
|
129
|
+
// `MODELS[tier]`: every value the container can hold.
|
|
130
|
+
return this.eval(expr.value, ctx);
|
|
131
|
+
case "call":
|
|
132
|
+
return this.evalCall(expr, ctx);
|
|
133
|
+
case "binop": {
|
|
134
|
+
if (expr.op === "%")
|
|
135
|
+
return this.eval(expr.left, ctx);
|
|
136
|
+
if (expr.op !== "+")
|
|
137
|
+
return [];
|
|
138
|
+
const left = this.eval(expr.left, ctx);
|
|
139
|
+
const right = this.eval(expr.right, ctx);
|
|
140
|
+
if (left.length === 0 && right.length === 0)
|
|
141
|
+
return [];
|
|
142
|
+
const l = left.length > 0 ? left : [placeholder(this.text(ctx.scope, expr.left))];
|
|
143
|
+
const r = right.length > 0 ? right : [placeholder(this.text(ctx.scope, expr.right))];
|
|
144
|
+
return product(l, r);
|
|
145
|
+
}
|
|
146
|
+
case "boolop":
|
|
147
|
+
if (expr.op === "and")
|
|
148
|
+
return this.eval(expr.values[expr.values.length - 1], ctx);
|
|
149
|
+
return expr.values.flatMap((v) => this.eval(v, ctx));
|
|
150
|
+
case "ifexp":
|
|
151
|
+
return [...this.eval(expr.body, ctx), ...this.eval(expr.orelse, ctx)];
|
|
152
|
+
case "tuple":
|
|
153
|
+
return expr.elts.flatMap((e) => this.eval(e, ctx));
|
|
154
|
+
default:
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
evalCall(expr, ctx) {
|
|
159
|
+
const callee = (0, python_source_1.dottedName)(expr.func);
|
|
160
|
+
// os.environ.get("X", default), os.getenv("X", default)
|
|
161
|
+
if (callee && /(^|\.)(environ\.get|getenv)$/.test(callee)) {
|
|
162
|
+
const fallback = expr.args[1] ?? expr.kwargs.find((k) => k.name === "default")?.value;
|
|
163
|
+
// An empty default says nothing about the value: keep it as a placeholder.
|
|
164
|
+
return fallback ? this.eval(fallback, ctx).filter((v) => v.text.length > 0) : [];
|
|
165
|
+
}
|
|
166
|
+
if (callee === "str" && expr.args[0])
|
|
167
|
+
return this.eval(expr.args[0], ctx);
|
|
168
|
+
// Validator wrappers keep the value: cast(str, x), TypeAdapter(str).validate_python(x).
|
|
169
|
+
if (callee && /(^|\.)cast$/.test(callee) && expr.args.length === 2)
|
|
170
|
+
return this.eval(expr.args[1], ctx);
|
|
171
|
+
if (expr.func.kind === "attr" && VALIDATOR_METHODS.has(expr.func.attr) && expr.args.length === 1) {
|
|
172
|
+
return this.eval(expr.args[0], ctx);
|
|
173
|
+
}
|
|
174
|
+
if (callee && /(^|\.)urljoin$/.test(callee) && expr.args.length >= 2) {
|
|
175
|
+
const base = this.eval(expr.args[0], ctx);
|
|
176
|
+
const rel = this.eval(expr.args[1], ctx);
|
|
177
|
+
return product(base, rel.length > 0 ? rel : [placeholder("…", "/")]);
|
|
178
|
+
}
|
|
179
|
+
if (expr.func.kind === "attr" && STRING_METHODS.has(expr.func.attr)) {
|
|
180
|
+
const receiver = this.eval(expr.func.object, ctx);
|
|
181
|
+
if (expr.func.attr === "rstrip" || expr.func.attr === "strip") {
|
|
182
|
+
return receiver.map((v) => ({ ...v, text: v.text.replace(/\/+$/, "") }));
|
|
183
|
+
}
|
|
184
|
+
return receiver;
|
|
185
|
+
}
|
|
186
|
+
// Same-file function or method: evaluate its return values with the arguments bound.
|
|
187
|
+
const target = this.callTarget(expr, ctx);
|
|
188
|
+
if (!target)
|
|
189
|
+
return [];
|
|
190
|
+
const { fn, bindings, hint } = target;
|
|
191
|
+
const lineOf = this.moduleOf(fn).model.lineOf;
|
|
192
|
+
return fn.returns
|
|
193
|
+
.flatMap((ret) => this.eval(ret, { scope: fn, line: lineOf(ret.start), bindings, hops: 0, depth: ctx.depth }))
|
|
194
|
+
.map((v) => (hint ? { ...v, hint: `${v.hint} ${hint}` } : v));
|
|
195
|
+
}
|
|
196
|
+
/** The same-repo function a call runs, with its arguments bound. */
|
|
197
|
+
callTarget(expr, ctx) {
|
|
198
|
+
const func = expr.func;
|
|
199
|
+
let target;
|
|
200
|
+
let hint = "";
|
|
201
|
+
if (func.kind === "name")
|
|
202
|
+
target = this.lookupFunction(func.id, ctx.scope) ?? this.importedFunction(func.id, ctx.scope);
|
|
203
|
+
else if (func.kind === "attr" && ((0, python_source_1.dottedName)(func.object) === "self" || (0, python_source_1.dottedName)(func.object) === "cls")) {
|
|
204
|
+
target = this.enclosingClass(ctx.scope)?.children.find((c) => c.kind === "function" && c.name === func.attr);
|
|
205
|
+
}
|
|
206
|
+
else if (func.kind === "attr") {
|
|
207
|
+
// `store.mcp_endpoint()` on a same-repo class, `module.helper()` on a same-repo module.
|
|
208
|
+
const sym = this.symbolOf(func.object, ctx.scope, ctx.line, 0);
|
|
209
|
+
if (sym?.kind === "class") {
|
|
210
|
+
target = sym.scope.children.find((c) => c.kind === "function" && c.name === func.attr);
|
|
211
|
+
hint = this.hintOf(sym.scope);
|
|
212
|
+
}
|
|
213
|
+
else if (sym?.kind === "module") {
|
|
214
|
+
target = sym.root.children.find((c) => c.kind === "function" && c.name === func.attr);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (!target)
|
|
218
|
+
return undefined;
|
|
219
|
+
return { fn: target, bindings: this.bindArguments(target, expr, ctx), hint };
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Expressions a keyword reaches a call with: `name=...`, or the `name` entry of a `**mapping`
|
|
223
|
+
* built from dict literals, `{**a, **b}` merges, assigned names and helper returns.
|
|
224
|
+
*/
|
|
225
|
+
kwargExprs(call, name, ctx) {
|
|
226
|
+
const explicit = call.kwargs.find((k) => k.name === name);
|
|
227
|
+
if (explicit)
|
|
228
|
+
return [{ expr: explicit.value, ctx }];
|
|
229
|
+
return call.starKwargs.flatMap((mapping) => this.dictEntryExprs(mapping, name, ctx, 0));
|
|
230
|
+
}
|
|
231
|
+
dictEntryExprs(expr, key, ctx, depth) {
|
|
232
|
+
if (depth > MAX_SYMBOL_DEPTH)
|
|
233
|
+
return [];
|
|
234
|
+
const next = depth + 1;
|
|
235
|
+
if (expr.kind === "coll" && expr.entries) {
|
|
236
|
+
// Later entries override earlier ones; any of them may be the value at runtime.
|
|
237
|
+
return [
|
|
238
|
+
...expr.entries.filter((e) => e.key === key).map((e) => ({ expr: e.value, ctx })),
|
|
239
|
+
...(expr.spreads ?? []).flatMap((spread) => this.dictEntryExprs(spread, key, ctx, next)),
|
|
240
|
+
];
|
|
241
|
+
}
|
|
242
|
+
if (expr.kind === "name") {
|
|
243
|
+
const bound = ctx.bindings?.get(expr.id);
|
|
244
|
+
if (bound)
|
|
245
|
+
return this.dictEntryExprs(bound.expr, key, bound.ctx, next);
|
|
246
|
+
let scope = ctx.scope;
|
|
247
|
+
let first = true;
|
|
248
|
+
while (scope) {
|
|
249
|
+
const assigned = scope.kind === "class" && !first ? [] : scope.assignments.filter((a) => a.target === expr.id);
|
|
250
|
+
if (assigned.length > 0) {
|
|
251
|
+
const before = first ? assigned.filter((a) => a.line <= ctx.line) : assigned;
|
|
252
|
+
const chosen = (before.length > 0 ? before : assigned).slice(-1)[0];
|
|
253
|
+
return this.dictEntryExprs(chosen.value, key, { scope: chosen.scope, line: chosen.line, hops: 0, depth: ctx.depth, bindings: first ? ctx.bindings : undefined }, next);
|
|
254
|
+
}
|
|
255
|
+
if (scope.kind === "function" && scope.params.some((p) => p.name === expr.id))
|
|
256
|
+
return [];
|
|
257
|
+
scope = scope.parent;
|
|
258
|
+
first = false;
|
|
259
|
+
}
|
|
260
|
+
return [];
|
|
261
|
+
}
|
|
262
|
+
if (expr.kind === "call") {
|
|
263
|
+
if ((0, python_source_1.dottedName)(expr.func) === "dict") {
|
|
264
|
+
return [
|
|
265
|
+
...expr.kwargs.filter((k) => k.name === key).map((k) => ({ expr: k.value, ctx })),
|
|
266
|
+
...[...expr.args, ...expr.starKwargs].flatMap((a) => this.dictEntryExprs(a, key, ctx, next)),
|
|
267
|
+
];
|
|
268
|
+
}
|
|
269
|
+
const target = this.callTarget(expr, ctx);
|
|
270
|
+
if (!target)
|
|
271
|
+
return [];
|
|
272
|
+
const lineOf = this.moduleOf(target.fn).model.lineOf;
|
|
273
|
+
return target.fn.returns.flatMap((ret) => this.dictEntryExprs(ret, key, { scope: target.fn, line: lineOf(ret.start), bindings: target.bindings, hops: 0, depth: ctx.depth }, next));
|
|
274
|
+
}
|
|
275
|
+
return [];
|
|
276
|
+
}
|
|
277
|
+
bindArguments(fn, call, ctx) {
|
|
278
|
+
const bindings = new Map();
|
|
279
|
+
const params = positionalParams(fn);
|
|
280
|
+
call.args.forEach((arg, index) => {
|
|
281
|
+
const param = params[index];
|
|
282
|
+
if (param)
|
|
283
|
+
bindings.set(param, { expr: arg, ctx });
|
|
284
|
+
});
|
|
285
|
+
for (const kw of call.kwargs)
|
|
286
|
+
bindings.set(kw.name, { expr: kw.value, ctx });
|
|
287
|
+
return bindings;
|
|
288
|
+
}
|
|
289
|
+
resolveName(id, ctx) {
|
|
290
|
+
const bound = ctx.bindings?.get(id);
|
|
291
|
+
if (bound)
|
|
292
|
+
return this.eval(bound.expr, bound.ctx);
|
|
293
|
+
let scope = ctx.scope;
|
|
294
|
+
let first = true;
|
|
295
|
+
while (scope) {
|
|
296
|
+
if (scope.kind === "class" && !first) {
|
|
297
|
+
scope = scope.parent;
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (scope.kind === "function") {
|
|
301
|
+
const param = scope.params.find((p) => p.name === id);
|
|
302
|
+
if (param) {
|
|
303
|
+
if (first && ctx.hops > 0) {
|
|
304
|
+
const viaCallers = this.resolveThroughCallers(scope, id, ctx);
|
|
305
|
+
if (viaCallers.length > 0)
|
|
306
|
+
return viaCallers;
|
|
307
|
+
}
|
|
308
|
+
return param.defaultExpr ? this.eval(param.defaultExpr, { ...ctx, scope: scope.parent ?? scope, hops: 0 }) : [];
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const assigned = scope.assignments.filter((a) => a.target === id);
|
|
312
|
+
if (assigned.length > 0) {
|
|
313
|
+
const before = first ? assigned.filter((a) => a.line <= ctx.line) : assigned;
|
|
314
|
+
const chosen = before.length > 0 ? [before[before.length - 1]] : assigned;
|
|
315
|
+
return chosen.flatMap((a) => this.eval(a.value, { scope: a.scope, line: a.line, hops: first ? ctx.hops : 0, depth: ctx.depth, bindings: first ? ctx.bindings : undefined }));
|
|
316
|
+
}
|
|
317
|
+
if (!scope.parent)
|
|
318
|
+
return this.importedName(id, scope, ctx);
|
|
319
|
+
scope = scope.parent;
|
|
320
|
+
first = false;
|
|
321
|
+
}
|
|
322
|
+
return [];
|
|
323
|
+
}
|
|
324
|
+
/** A module-level name bound by `from M import name` in a same-repo module. */
|
|
325
|
+
importedName(id, root, ctx) {
|
|
326
|
+
const imp = this.moduleOf(root).model.imports.find((i) => i.names.length > 0 && i.aliases.has(id));
|
|
327
|
+
if (!imp)
|
|
328
|
+
return [];
|
|
329
|
+
const target = this.loadModule(root, imp.module);
|
|
330
|
+
if (!target || target === root)
|
|
331
|
+
return [];
|
|
332
|
+
const name = imp.aliases.get(id);
|
|
333
|
+
return this.resolveName(name, { scope: target, line: Number.MAX_SAFE_INTEGER, hops: 0, depth: ctx.depth + 1 });
|
|
334
|
+
}
|
|
335
|
+
importedFunction(id, scope) {
|
|
336
|
+
const root = this.rootOf(scope);
|
|
337
|
+
const imp = this.moduleOf(root).model.imports.find((i) => i.names.length > 0 && i.aliases.has(id));
|
|
338
|
+
if (!imp)
|
|
339
|
+
return undefined;
|
|
340
|
+
const target = this.loadModule(root, imp.module);
|
|
341
|
+
const name = imp.aliases.get(id);
|
|
342
|
+
return target?.children.find((c) => c.kind === "function" && c.name === name);
|
|
343
|
+
}
|
|
344
|
+
/** Class, instance or module a name or dotted expression refers to, across same-repo imports. */
|
|
345
|
+
symbolOf(expr, scope, line, depth) {
|
|
346
|
+
if (depth > MAX_SYMBOL_DEPTH)
|
|
347
|
+
return undefined;
|
|
348
|
+
if (expr.kind === "call") {
|
|
349
|
+
const sym = this.symbolOf(expr.func, scope, line, depth + 1);
|
|
350
|
+
return sym?.kind === "class" ? sym : undefined;
|
|
351
|
+
}
|
|
352
|
+
if (expr.kind === "attr") {
|
|
353
|
+
const base = this.symbolOf(expr.object, scope, line, depth + 1);
|
|
354
|
+
if (base?.kind === "module")
|
|
355
|
+
return this.symbolOfName(expr.attr, base.root, Number.MAX_SAFE_INTEGER, depth + 1);
|
|
356
|
+
return undefined;
|
|
357
|
+
}
|
|
358
|
+
if (expr.kind === "name")
|
|
359
|
+
return this.symbolOfName(expr.id, scope, line, depth + 1);
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
362
|
+
symbolOfName(id, start, line, depth) {
|
|
363
|
+
if (depth > MAX_SYMBOL_DEPTH)
|
|
364
|
+
return undefined;
|
|
365
|
+
let scope = start;
|
|
366
|
+
let first = true;
|
|
367
|
+
while (scope) {
|
|
368
|
+
if (scope.kind !== "class" || first) {
|
|
369
|
+
if (scope.kind === "function") {
|
|
370
|
+
const param = scope.params.find((p) => p.name === id);
|
|
371
|
+
if (param)
|
|
372
|
+
return param.annotation ? this.symbolOfAnnotation(param.annotation, scope, depth + 1) : undefined;
|
|
373
|
+
}
|
|
374
|
+
const cls = scope.children.find((c) => c.kind === "class" && c.name === id);
|
|
375
|
+
if (cls)
|
|
376
|
+
return { kind: "class", scope: cls };
|
|
377
|
+
const assigned = scope.assignments.filter((a) => a.target === id);
|
|
378
|
+
if (assigned.length > 0) {
|
|
379
|
+
const before = first ? assigned.filter((a) => a.line <= line) : assigned;
|
|
380
|
+
const chosen = (before.length > 0 ? before : assigned).slice(-1)[0];
|
|
381
|
+
return this.symbolOf(chosen.value, chosen.scope, chosen.line, depth + 1);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (!scope.parent)
|
|
385
|
+
return this.importedSymbol(id, scope, depth + 1);
|
|
386
|
+
scope = scope.parent;
|
|
387
|
+
first = false;
|
|
388
|
+
}
|
|
389
|
+
return undefined;
|
|
390
|
+
}
|
|
391
|
+
symbolOfAnnotation(annotation, scope, depth) {
|
|
392
|
+
const name = /^["']?([A-Za-z_][\w.]*)/.exec(annotation.trim())?.[1];
|
|
393
|
+
if (!name)
|
|
394
|
+
return undefined;
|
|
395
|
+
const [head, ...rest] = name.split(".");
|
|
396
|
+
let sym = this.symbolOfName(head, scope, Number.MAX_SAFE_INTEGER, depth + 1);
|
|
397
|
+
for (const part of rest) {
|
|
398
|
+
if (sym?.kind !== "module")
|
|
399
|
+
return undefined;
|
|
400
|
+
sym = this.symbolOfName(part, sym.root, Number.MAX_SAFE_INTEGER, depth + 1);
|
|
401
|
+
}
|
|
402
|
+
return sym;
|
|
403
|
+
}
|
|
404
|
+
importedSymbol(id, root, depth) {
|
|
405
|
+
const imports = this.moduleOf(root).model.imports;
|
|
406
|
+
for (const imp of imports) {
|
|
407
|
+
const target = imp.aliases.get(id);
|
|
408
|
+
if (target === undefined)
|
|
409
|
+
continue;
|
|
410
|
+
if (imp.names.length === 0) {
|
|
411
|
+
const mod = this.loadModule(root, target);
|
|
412
|
+
return mod ? { kind: "module", root: mod } : undefined;
|
|
413
|
+
}
|
|
414
|
+
const mod = this.loadModule(root, imp.module);
|
|
415
|
+
if (mod && mod !== root) {
|
|
416
|
+
const sym = this.symbolOfName(target, mod, Number.MAX_SAFE_INTEGER, depth + 1);
|
|
417
|
+
if (sym)
|
|
418
|
+
return sym;
|
|
419
|
+
}
|
|
420
|
+
// `from pkg import settings` where `settings` is itself a module.
|
|
421
|
+
const sub = this.loadModule(root, `${imp.module}${imp.module.endsWith(".") ? "" : "."}${target}`);
|
|
422
|
+
return sub ? { kind: "module", root: sub } : undefined;
|
|
423
|
+
}
|
|
424
|
+
return undefined;
|
|
425
|
+
}
|
|
426
|
+
hintOf(cls) {
|
|
427
|
+
return `${cls.name} ${this.moduleOf(cls).path}`.toLowerCase();
|
|
428
|
+
}
|
|
429
|
+
/** Values of `obj.attr` on a class or instance: class attributes, `self.attr = ...`, `@property`. */
|
|
430
|
+
classAttr(cls, attr, ctx) {
|
|
431
|
+
const hint = this.hintOf(cls);
|
|
432
|
+
return this.attrValues(cls, attr, ctx).map((v) => ({ ...v, hint: `${v.hint} ${hint}` }));
|
|
433
|
+
}
|
|
434
|
+
/** Values a parameter takes at same-file call sites of its function, with those sites. */
|
|
435
|
+
resolveThroughCallers(fn, param, ctx) {
|
|
436
|
+
const params = positionalParams(fn);
|
|
437
|
+
const index = params.indexOf(param);
|
|
438
|
+
const isMethod = fn.parent?.kind === "class";
|
|
439
|
+
const out = [];
|
|
440
|
+
for (const call of this.model.calls) {
|
|
441
|
+
const callee = call.callee;
|
|
442
|
+
if (!callee)
|
|
443
|
+
continue;
|
|
444
|
+
const matches = isMethod ? callee === `self.${fn.name}` || callee === `cls.${fn.name}` : callee === fn.name;
|
|
445
|
+
if (!matches)
|
|
446
|
+
continue;
|
|
447
|
+
const arg = call.node.kwargs.find((k) => k.name === param)?.value ?? (index >= 0 ? call.node.args[index] : undefined);
|
|
448
|
+
if (!arg)
|
|
449
|
+
continue;
|
|
450
|
+
const site = { startLine: call.startLine, endLine: call.endLine };
|
|
451
|
+
const values = this.eval(arg, { scope: call.scope, line: call.startLine, hops: ctx.hops - 1, depth: ctx.depth });
|
|
452
|
+
// The caller's class and function names count as routing hints (ShopifyCatalogTools).
|
|
453
|
+
const callerNames = [];
|
|
454
|
+
for (let s = call.scope; s?.parent; s = s.parent)
|
|
455
|
+
callerNames.push(s.name);
|
|
456
|
+
const hint = callerNames.join(" ").toLowerCase();
|
|
457
|
+
for (const v of values)
|
|
458
|
+
out.push({ ...v, sites: [...v.sites, site], hint: `${v.hint} ${hint}`.trim() });
|
|
459
|
+
}
|
|
460
|
+
return out;
|
|
461
|
+
}
|
|
462
|
+
resolveSelfAttr(attr, ctx) {
|
|
463
|
+
const cls = this.enclosingClass(ctx.scope);
|
|
464
|
+
if (!cls)
|
|
465
|
+
return [];
|
|
466
|
+
return this.attrValues(cls, attr, ctx);
|
|
467
|
+
}
|
|
468
|
+
attrValues(cls, attr, ctx) {
|
|
469
|
+
const lineOf = this.moduleOf(cls).model.lineOf;
|
|
470
|
+
const out = [];
|
|
471
|
+
for (const member of cls.children) {
|
|
472
|
+
if (member.kind !== "function")
|
|
473
|
+
continue;
|
|
474
|
+
if (member.name === attr && member.decorators.some((d) => /(^|\.)(property|cached_property)$/.test(d))) {
|
|
475
|
+
for (const ret of member.returns) {
|
|
476
|
+
out.push(...this.eval(ret, { scope: member, line: lineOf(ret.start), hops: 0, depth: ctx.depth }));
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
for (const a of member.assignments) {
|
|
480
|
+
if (a.target !== `self.${attr}`)
|
|
481
|
+
continue;
|
|
482
|
+
out.push(...this.eval(a.value, { scope: member, line: a.line, hops: 0, depth: ctx.depth }));
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
for (const a of cls.assignments) {
|
|
486
|
+
if (a.target === attr)
|
|
487
|
+
out.push(...this.eval(a.value, { scope: cls, line: a.line, hops: 0, depth: ctx.depth }));
|
|
488
|
+
}
|
|
489
|
+
return out;
|
|
490
|
+
}
|
|
491
|
+
/** Assignment and `with ... as` values bound to a name or `self.attr` (for client receivers). */
|
|
492
|
+
bindingsOf(receiver, scope, line) {
|
|
493
|
+
if (receiver.startsWith("self.")) {
|
|
494
|
+
const cls = this.enclosingClass(scope);
|
|
495
|
+
if (!cls)
|
|
496
|
+
return [];
|
|
497
|
+
const attr = receiver.slice("self.".length);
|
|
498
|
+
const out = [];
|
|
499
|
+
for (const member of cls.children) {
|
|
500
|
+
if (member.kind !== "function")
|
|
501
|
+
continue;
|
|
502
|
+
for (const a of member.assignments)
|
|
503
|
+
if (a.target === receiver)
|
|
504
|
+
out.push(a);
|
|
505
|
+
}
|
|
506
|
+
for (const a of cls.assignments)
|
|
507
|
+
if (a.target === attr)
|
|
508
|
+
out.push(a);
|
|
509
|
+
return out;
|
|
510
|
+
}
|
|
511
|
+
let current = scope;
|
|
512
|
+
let first = true;
|
|
513
|
+
while (current) {
|
|
514
|
+
if (current.kind !== "class" || first) {
|
|
515
|
+
const assigned = current.assignments.filter((a) => a.target === receiver);
|
|
516
|
+
if (assigned.length > 0) {
|
|
517
|
+
const before = first ? assigned.filter((a) => a.line <= line) : assigned;
|
|
518
|
+
return before.length > 0 ? before : assigned;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
current = current.parent;
|
|
522
|
+
first = false;
|
|
523
|
+
}
|
|
524
|
+
return [];
|
|
525
|
+
}
|
|
526
|
+
enclosingClass(scope) {
|
|
527
|
+
let current = scope;
|
|
528
|
+
while (current) {
|
|
529
|
+
if (current.kind === "class")
|
|
530
|
+
return current;
|
|
531
|
+
current = current.parent;
|
|
532
|
+
}
|
|
533
|
+
return undefined;
|
|
534
|
+
}
|
|
535
|
+
lookupFunction(name, scope) {
|
|
536
|
+
let current = scope;
|
|
537
|
+
while (current) {
|
|
538
|
+
const fn = current.children.find((c) => c.kind === "function" && c.name === name);
|
|
539
|
+
if (fn && current.kind !== "class")
|
|
540
|
+
return fn;
|
|
541
|
+
current = current.parent;
|
|
542
|
+
}
|
|
543
|
+
return undefined;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
function positionalParams(fn) {
|
|
547
|
+
const names = fn.params.map((p) => p.name);
|
|
548
|
+
const isMethod = fn.parent?.kind === "class";
|
|
549
|
+
const isStatic = fn.decorators.some((d) => d === "staticmethod");
|
|
550
|
+
return isMethod && !isStatic && (names[0] === "self" || names[0] === "cls") ? names.slice(1) : names;
|
|
551
|
+
}
|
|
552
|
+
function product(left, right) {
|
|
553
|
+
const out = [];
|
|
554
|
+
for (const l of left) {
|
|
555
|
+
for (const r of right) {
|
|
556
|
+
out.push({ text: l.text + r.text, sites: [...l.sites, ...r.sites], hint: `${l.hint} ${r.hint}`.trim() });
|
|
557
|
+
if (out.length >= MAX_VALUES)
|
|
558
|
+
return out;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return out;
|
|
562
|
+
}
|
|
563
|
+
function placeholder(text, prefix = "") {
|
|
564
|
+
return { text: `${prefix}{${text}}`, sites: [], hint: "" };
|
|
565
|
+
}
|
|
566
|
+
function cap(values) {
|
|
567
|
+
const seen = new Set();
|
|
568
|
+
const out = [];
|
|
569
|
+
for (const v of values) {
|
|
570
|
+
const key = `${v.text}|${v.sites.map((s) => s.startLine).join(",")}`;
|
|
571
|
+
if (seen.has(key))
|
|
572
|
+
continue;
|
|
573
|
+
seen.add(key);
|
|
574
|
+
out.push(v);
|
|
575
|
+
if (out.length >= MAX_VALUES)
|
|
576
|
+
break;
|
|
577
|
+
}
|
|
578
|
+
return out;
|
|
579
|
+
}
|
|
580
|
+
const ABSOLUTE_URL = /^(?:https?|wss?):\/\/([^/?#\s]+)([^?#\s]*)/i;
|
|
581
|
+
function parseUrl(text) {
|
|
582
|
+
const m = ABSOLUTE_URL.exec(text.trim());
|
|
583
|
+
if (!m)
|
|
584
|
+
return undefined;
|
|
585
|
+
let host = m[1].toLowerCase();
|
|
586
|
+
host = host.slice(host.lastIndexOf("@") + 1).replace(/:\d+$/, "");
|
|
587
|
+
if (!host || host.includes("{") || !host.includes("."))
|
|
588
|
+
return undefined;
|
|
589
|
+
return { host, path: m[2] || "/" };
|
|
590
|
+
}
|
|
591
|
+
function hostMatches(host, pattern) {
|
|
592
|
+
const p = pattern.toLowerCase().replace(/^\./, "").replace(/^https?:\/\//, "").replace(/\/.*$/, "");
|
|
593
|
+
return host === p || host.endsWith(`.${p}`);
|
|
594
|
+
}
|
|
595
|
+
class DestinationRouter {
|
|
596
|
+
constructor(config, libraryNames) {
|
|
597
|
+
this.catalogSubTypes = new Map();
|
|
598
|
+
this.hostPatterns = config.thirdParty.services.flatMap((svc) => svc.urlHostPatterns.map((pattern) => ({ pattern, serviceName: svc.serviceName })));
|
|
599
|
+
this.routes = config.thirdParty.urlRoutes;
|
|
600
|
+
this.pathRoutes = config.thirdParty.urlPathRoutes;
|
|
601
|
+
this.modelPrefixes = config.thirdParty.llmModelPrefixes;
|
|
602
|
+
for (const tp of config.classifier.thirdParties) {
|
|
603
|
+
if (!this.catalogSubTypes.has(tp.serviceName.toLowerCase())) {
|
|
604
|
+
this.catalogSubTypes.set(tp.serviceName.toLowerCase(), tp.subType);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
this.libraryNames = new Set([...libraryNames, ...EXTRA_LIBRARY_NAMES].map((n) => n.toLowerCase()));
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Service for a URL. `fallback` allows the registrable host (`acme.io`) for public hosts
|
|
611
|
+
* the catalog does not know. Returns "unknown" for local, placeholder and dynamic hosts,
|
|
612
|
+
* and `{ remote }` for a service of its own: the organization's domains (including the
|
|
613
|
+
* ones the repository declares) or a shared hosting platform host.
|
|
614
|
+
*/
|
|
615
|
+
route(url, hint, fallback) {
|
|
616
|
+
const parsed = parseUrl(url);
|
|
617
|
+
if (!parsed) {
|
|
618
|
+
// Host known only at runtime: a path route needs both its path and its hint.
|
|
619
|
+
const runtimeHost = /^(?:https?|wss?):\/\/[^/?#\s]*\{[^}]*\}[^/?#\s]*([^?#\s]*)/i.exec(url.trim());
|
|
620
|
+
if (!runtimeHost)
|
|
621
|
+
return "unknown";
|
|
622
|
+
const path = runtimeHost[1] || "/";
|
|
623
|
+
const rule = this.pathRoutes.find((r) => r.path?.test(path) && r.hint?.test(hint));
|
|
624
|
+
return rule ? this.named(rule.serviceName, rule.subType) : "unknown";
|
|
625
|
+
}
|
|
626
|
+
// Configured organization domains win; without them, the domains the repository
|
|
627
|
+
// declares as its own (package.json homepage, site URL settings) stand in.
|
|
628
|
+
const configured = (0, organization_domains_scan_scope_1.getActiveOrganizationDomains)() ?? [];
|
|
629
|
+
const organizationDomains = configured.length > 0 ? configured : (0, source_module_index_1.repoDeclaredDomains)();
|
|
630
|
+
if ((0, external_url_third_party_1.hostMatchesOrganizationDomains)(parsed.host, organizationDomains))
|
|
631
|
+
return { remote: { host: parsed.host, firstParty: true } };
|
|
632
|
+
// Without configured domains, a host whose domain label is the git remote owner's name
|
|
633
|
+
// (owner `Acme-Widgets-AI`, host `api.acmewidgets.ai`) is the organization's own, unless
|
|
634
|
+
// the catalog knows the host as a vendor.
|
|
635
|
+
const owner = configured.length > 0 ? undefined : (0, source_module_index_1.repoOwnerKey)();
|
|
636
|
+
if (owner &&
|
|
637
|
+
(0, git_remote_owner_1.normalizeOrganizationName)((0, external_url_third_party_1.vendorNameFromHostname)(parsed.host)) === owner &&
|
|
638
|
+
!this.hostPatterns.some((c) => hostMatches(parsed.host, c.pattern))) {
|
|
639
|
+
return { remote: { host: parsed.host, firstParty: true } };
|
|
640
|
+
}
|
|
641
|
+
const platform = (0, third_party_detection_config_1.platformOfHost)(parsed.host);
|
|
642
|
+
if (platform)
|
|
643
|
+
return { remote: { host: parsed.host, platform } };
|
|
644
|
+
const concrete = `https://${parsed.host}${parsed.path.replace(/\{[^}]*\}/g, "x")}`;
|
|
645
|
+
if ((0, external_url_third_party_1.shouldIgnoreExternalHttpUrl)(concrete))
|
|
646
|
+
return "unknown";
|
|
647
|
+
for (const route of this.routes) {
|
|
648
|
+
if (!hostMatches(parsed.host, route.host))
|
|
649
|
+
continue;
|
|
650
|
+
for (const rule of route.rules) {
|
|
651
|
+
if (rule.path && !rule.path.test(parsed.path))
|
|
652
|
+
continue;
|
|
653
|
+
if (rule.hint && !rule.hint.test(hint))
|
|
654
|
+
continue;
|
|
655
|
+
return this.named(rule.serviceName, rule.subType);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
let best;
|
|
659
|
+
for (const candidate of this.hostPatterns) {
|
|
660
|
+
if (!hostMatches(parsed.host, candidate.pattern))
|
|
661
|
+
continue;
|
|
662
|
+
if (!best || candidate.pattern.length > best.pattern.length)
|
|
663
|
+
best = candidate;
|
|
664
|
+
}
|
|
665
|
+
if (best)
|
|
666
|
+
return this.named(best.serviceName);
|
|
667
|
+
if (!fallback)
|
|
668
|
+
return "unknown";
|
|
669
|
+
const derived = (0, external_url_third_party_1.defaultServiceNameFromLiteralPublicUrl)(concrete);
|
|
670
|
+
return derived ? this.named(derived) : "unknown";
|
|
671
|
+
}
|
|
672
|
+
/** Provider of an LLM gateway model id (`groq/llama-3.1-8b-instant` -> groq). */
|
|
673
|
+
routeModel(model) {
|
|
674
|
+
const prefix = model.trim().toLowerCase().split("/")[0];
|
|
675
|
+
if (!prefix || prefix === model.trim().toLowerCase())
|
|
676
|
+
return "unknown";
|
|
677
|
+
const entry = this.modelPrefixes.find((p) => p.prefix === prefix);
|
|
678
|
+
return entry ? this.named(entry.serviceName) : "unknown";
|
|
679
|
+
}
|
|
680
|
+
isLibrary(name) {
|
|
681
|
+
return this.libraryNames.has(name.toLowerCase());
|
|
682
|
+
}
|
|
683
|
+
named(serviceName, subType) {
|
|
684
|
+
if (this.isLibrary(serviceName))
|
|
685
|
+
return "unknown";
|
|
686
|
+
const catalog = this.catalogSubTypes.get(serviceName.toLowerCase());
|
|
687
|
+
return subType && subType !== catalog ? { serviceName, subType } : { serviceName };
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
exports.DestinationRouter = DestinationRouter;
|
|
691
|
+
const resultCache = new Map();
|
|
692
|
+
function detectPythonOutboundHttp(input) {
|
|
693
|
+
const key = `${(0, source_module_index_1.pythonModuleIndexGeneration)()}\u0000${input.filePath}\u0000${input.content}`;
|
|
694
|
+
const cached = resultCache.get(key);
|
|
695
|
+
if (cached)
|
|
696
|
+
return cached;
|
|
697
|
+
let result;
|
|
698
|
+
try {
|
|
699
|
+
result = detectUncached(input);
|
|
700
|
+
}
|
|
701
|
+
catch {
|
|
702
|
+
// Resolution is best effort: a construct the small parser cannot follow must not fail the scan.
|
|
703
|
+
result = { findings: [], outgoingRequestLines: [], openAiClientsRedirected: false };
|
|
704
|
+
}
|
|
705
|
+
resultCache.clear();
|
|
706
|
+
resultCache.set(key, result);
|
|
707
|
+
return result;
|
|
708
|
+
}
|
|
709
|
+
const moduleInfoCache = new WeakMap();
|
|
710
|
+
/** What a module imports that marks outbound calls (HTTP libraries, SDKs). */
|
|
711
|
+
function moduleInfoFor(model, libraries) {
|
|
712
|
+
const cached = moduleInfoCache.get(model);
|
|
713
|
+
if (cached)
|
|
714
|
+
return cached;
|
|
715
|
+
const imported = (prefix) => model.imports.some((imp) => imp.module === prefix || imp.module.startsWith(`${prefix}.`));
|
|
716
|
+
const importedLibraries = libraries.filter((lib) => lib.importModules.some((mod) => imported(mod)));
|
|
717
|
+
const moduleAliases = new Map();
|
|
718
|
+
const constructorAliases = new Map();
|
|
719
|
+
for (const imp of model.imports) {
|
|
720
|
+
const lib = importedLibraries.find((l) => l.importModules.some((m) => imp.module === m || imp.module.startsWith(`${m}.`)));
|
|
721
|
+
if (!lib)
|
|
722
|
+
continue;
|
|
723
|
+
if (imp.names.length === 0) {
|
|
724
|
+
for (const [alias, target] of imp.aliases)
|
|
725
|
+
if (target === imp.module)
|
|
726
|
+
moduleAliases.set(alias, lib);
|
|
727
|
+
}
|
|
728
|
+
else {
|
|
729
|
+
for (const [alias, name] of imp.aliases)
|
|
730
|
+
if (lib.constructors.includes(name))
|
|
731
|
+
constructorAliases.set(alias, lib);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
const constructorLibrary = (ctor) => {
|
|
735
|
+
const dot = ctor.lastIndexOf(".");
|
|
736
|
+
if (dot === -1)
|
|
737
|
+
return constructorAliases.get(ctor);
|
|
738
|
+
const lib = moduleAliases.get(ctor.slice(0, dot));
|
|
739
|
+
return lib && lib.constructors.includes(ctor.slice(dot + 1)) ? lib : undefined;
|
|
740
|
+
};
|
|
741
|
+
// Phoenix tracing: `register(...)`, `phoenix.otel.BatchSpanProcessor(...)` and the other
|
|
742
|
+
// phoenix.otel entry points send spans to Arize Phoenix whatever the endpoint value.
|
|
743
|
+
const phoenixModuleAliases = new Set();
|
|
744
|
+
const phoenixNames = new Set();
|
|
745
|
+
for (const imp of model.imports) {
|
|
746
|
+
if (imp.module !== "phoenix.otel" && !imp.module.startsWith("phoenix.otel.")) {
|
|
747
|
+
if (imp.module === "phoenix" && imp.names.includes("otel")) {
|
|
748
|
+
for (const [alias, name] of imp.aliases)
|
|
749
|
+
if (name === "otel")
|
|
750
|
+
phoenixModuleAliases.add(alias);
|
|
751
|
+
}
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
if (imp.names.length === 0) {
|
|
755
|
+
for (const [alias, target] of imp.aliases)
|
|
756
|
+
phoenixModuleAliases.add(alias === "phoenix" ? "phoenix.otel" : alias === target ? target : alias);
|
|
757
|
+
}
|
|
758
|
+
else {
|
|
759
|
+
for (const alias of imp.aliases.keys())
|
|
760
|
+
phoenixNames.add(alias);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
// LiteLLM: completion(model="groq/...") names the provider from the model prefix.
|
|
764
|
+
const litellmAliases = new Set();
|
|
765
|
+
const litellmNames = new Set();
|
|
766
|
+
for (const imp of model.imports) {
|
|
767
|
+
if (imp.module !== "litellm" && !imp.module.startsWith("litellm."))
|
|
768
|
+
continue;
|
|
769
|
+
if (imp.names.length === 0)
|
|
770
|
+
for (const alias of imp.aliases.keys())
|
|
771
|
+
litellmAliases.add(alias);
|
|
772
|
+
else
|
|
773
|
+
for (const [alias, name] of imp.aliases)
|
|
774
|
+
if (LITELLM_CALLS.has(name))
|
|
775
|
+
litellmNames.add(alias);
|
|
776
|
+
}
|
|
777
|
+
// Google ADK's LiteLlm(model="provider/...") wraps LiteLLM.
|
|
778
|
+
const adkLiteLlmNames = new Set();
|
|
779
|
+
for (const imp of model.imports) {
|
|
780
|
+
if (!imp.module.startsWith("google.adk"))
|
|
781
|
+
continue;
|
|
782
|
+
for (const [alias, name] of imp.aliases)
|
|
783
|
+
if (name === "LiteLlm")
|
|
784
|
+
adkLiteLlmNames.add(alias);
|
|
785
|
+
}
|
|
786
|
+
// Google API clients: `from googleapiclient.discovery import build` (often inside a function).
|
|
787
|
+
const googleBuildNames = new Set();
|
|
788
|
+
const googleDiscoveryModules = new Set();
|
|
789
|
+
for (const imp of model.imports) {
|
|
790
|
+
if (imp.module === "googleapiclient.discovery" && imp.names.length > 0) {
|
|
791
|
+
for (const [alias, name] of imp.aliases)
|
|
792
|
+
if (name === "build")
|
|
793
|
+
googleBuildNames.add(alias);
|
|
794
|
+
}
|
|
795
|
+
else if (imp.module === "googleapiclient" && imp.names.includes("discovery")) {
|
|
796
|
+
for (const [alias, name] of imp.aliases)
|
|
797
|
+
if (name === "discovery")
|
|
798
|
+
googleDiscoveryModules.add(alias);
|
|
799
|
+
}
|
|
800
|
+
else if (imp.module === "googleapiclient.discovery") {
|
|
801
|
+
for (const alias of imp.aliases.keys())
|
|
802
|
+
googleDiscoveryModules.add(alias === "googleapiclient" ? "googleapiclient.discovery" : alias);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
const info = {
|
|
806
|
+
importedLibraries,
|
|
807
|
+
moduleAliases,
|
|
808
|
+
constructorLibrary,
|
|
809
|
+
openAiImported: imported("openai"),
|
|
810
|
+
mcpImported: imported("mcp") || imported("google.adk"),
|
|
811
|
+
isPhoenixCall: (callee) => {
|
|
812
|
+
if (phoenixNames.has(callee))
|
|
813
|
+
return true;
|
|
814
|
+
const dot = callee.lastIndexOf(".");
|
|
815
|
+
return dot > 0 && phoenixModuleAliases.has(callee.slice(0, dot));
|
|
816
|
+
},
|
|
817
|
+
isLitellmCall: (callee) => {
|
|
818
|
+
if (litellmNames.has(callee))
|
|
819
|
+
return true;
|
|
820
|
+
const dot = callee.lastIndexOf(".");
|
|
821
|
+
return dot > 0 && litellmAliases.has(callee.slice(0, dot)) && LITELLM_CALLS.has(callee.slice(dot + 1));
|
|
822
|
+
},
|
|
823
|
+
isAdkLiteLlm: (callee) => adkLiteLlmNames.has(callee) || /(^|\.)lite_llm\.LiteLlm$/.test(callee),
|
|
824
|
+
isGoogleBuild: (callee) => {
|
|
825
|
+
if (googleBuildNames.has(callee))
|
|
826
|
+
return true;
|
|
827
|
+
const dot = callee.lastIndexOf(".");
|
|
828
|
+
return dot > 0 && callee.slice(dot + 1) === "build" && googleDiscoveryModules.has(callee.slice(0, dot));
|
|
829
|
+
},
|
|
830
|
+
};
|
|
831
|
+
moduleInfoCache.set(model, info);
|
|
832
|
+
return info;
|
|
833
|
+
}
|
|
834
|
+
function isWithin(scope, fn) {
|
|
835
|
+
for (let s = scope; s; s = s.parent)
|
|
836
|
+
if (s === fn)
|
|
837
|
+
return true;
|
|
838
|
+
return false;
|
|
839
|
+
}
|
|
840
|
+
function detectUncached(input) {
|
|
841
|
+
const { filePath, content, libraries } = input;
|
|
842
|
+
const empty = { findings: [], outgoingRequestLines: [], openAiClientsRedirected: false };
|
|
843
|
+
// Files that import nothing outbound can still call a same-repo wrapper (call_model(**kw)),
|
|
844
|
+
// so with the module index active any file with a same-repo-looking import is analyzed.
|
|
845
|
+
const mentionsOutbound = /\b(httpx|requests|aiohttp|openai|mcp|phoenix|google\.adk|litellm|googleapiclient)\b|['"](GET|POST|PUT|PATCH|DELETE)['"]/.test(content);
|
|
846
|
+
const mayCallWrapper = (0, source_module_index_1.pythonModuleIndexSize)() > 1 && /^\s*(from\s+[\w.]+\s+import|import\s+\w)/m.test(content);
|
|
847
|
+
if (!mentionsOutbound && !mayCallWrapper) {
|
|
848
|
+
return empty;
|
|
849
|
+
}
|
|
850
|
+
const model = (0, python_source_1.buildPySourceModel)(content);
|
|
851
|
+
const resolver = new Resolver(model, filePath);
|
|
852
|
+
const router = new DestinationRouter(input.config, libraries.map((l) => l.name));
|
|
853
|
+
const lines = content.split(/\r?\n/);
|
|
854
|
+
const findings = [];
|
|
855
|
+
const emitted = new Set();
|
|
856
|
+
const location = (site) => ({
|
|
857
|
+
filePath,
|
|
858
|
+
startLine: site.startLine,
|
|
859
|
+
endLine: site.endLine,
|
|
860
|
+
code: lines[site.startLine - 1]?.trim() ?? "",
|
|
861
|
+
});
|
|
862
|
+
const hintFor = (call, urlText) => {
|
|
863
|
+
const names = [filePath];
|
|
864
|
+
let scope = call.scope;
|
|
865
|
+
while (scope) {
|
|
866
|
+
names.push(scope.name);
|
|
867
|
+
scope = scope.parent;
|
|
868
|
+
}
|
|
869
|
+
names.push(urlText);
|
|
870
|
+
return names.join(" ").toLowerCase();
|
|
871
|
+
};
|
|
872
|
+
const emit = (call, destinations, extra, patternId, confidence) => {
|
|
873
|
+
for (const d of destinations) {
|
|
874
|
+
if (d.remote) {
|
|
875
|
+
emitRemoteService(call, d, extra, patternId, confidence);
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
const name = d.subType ? `${d.serviceName} ${d.subType}` : d.serviceName;
|
|
879
|
+
const sites = [{ startLine: call.startLine, endLine: call.endLine }, ...d.sites];
|
|
880
|
+
for (const site of sites) {
|
|
881
|
+
const dedupe = `${name}|${site.startLine}|${site.endLine}`;
|
|
882
|
+
if (emitted.has(dedupe))
|
|
883
|
+
continue;
|
|
884
|
+
emitted.add(dedupe);
|
|
885
|
+
findings.push({
|
|
886
|
+
pattern: patternId,
|
|
887
|
+
name,
|
|
888
|
+
confidence,
|
|
889
|
+
location: location(site),
|
|
890
|
+
properties: {
|
|
891
|
+
serviceName: d.serviceName,
|
|
892
|
+
...(d.url ? { url: d.url } : {}),
|
|
893
|
+
...(d.subType ? { thirdPartySubType: d.subType } : {}),
|
|
894
|
+
...extra,
|
|
895
|
+
},
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
};
|
|
900
|
+
/** A call to a service of its own (organization host, hosting platform): an API asset, never a vendor. */
|
|
901
|
+
const emitRemoteService = (call, d, extra, patternId, confidence) => {
|
|
902
|
+
const remote = d.remote;
|
|
903
|
+
const host = remote.host;
|
|
904
|
+
for (const site of [{ startLine: call.startLine, endLine: call.endLine }, ...d.sites]) {
|
|
905
|
+
const dedupe = `remote|${host}|${site.startLine}|${site.endLine}`;
|
|
906
|
+
if (emitted.has(dedupe))
|
|
907
|
+
continue;
|
|
908
|
+
emitted.add(dedupe);
|
|
909
|
+
findings.push({
|
|
910
|
+
pattern: patternId,
|
|
911
|
+
name: remoteServiceName(remote),
|
|
912
|
+
confidence,
|
|
913
|
+
location: location(site),
|
|
914
|
+
properties: remoteServiceProperties(remote, d.url, extra),
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
/** Destinations for URL values; `fallback` allows hosts outside the catalog. */
|
|
919
|
+
const destinationsFor = (call, values, fallback) => {
|
|
920
|
+
const known = [];
|
|
921
|
+
let organization = false;
|
|
922
|
+
const seen = new Set();
|
|
923
|
+
for (const v of values) {
|
|
924
|
+
const routed = router.route(v.text, `${hintFor(call, v.text)} ${v.hint}`, fallback);
|
|
925
|
+
if (routed === "unknown")
|
|
926
|
+
continue;
|
|
927
|
+
if ("remote" in routed) {
|
|
928
|
+
if (routed.remote.firstParty)
|
|
929
|
+
organization = true;
|
|
930
|
+
const host = routed.remote.host;
|
|
931
|
+
if (!known.some((d) => d.remote?.host === host))
|
|
932
|
+
known.push({ serviceName: "", url: v.text, sites: v.sites, remote: routed.remote });
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
const key = `${routed.serviceName}|${routed.subType ?? ""}|${v.sites.map((s) => s.startLine).join(",")}`;
|
|
936
|
+
if (seen.has(key))
|
|
937
|
+
continue;
|
|
938
|
+
seen.add(key);
|
|
939
|
+
known.push({ ...routed, url: v.text, sites: v.sites });
|
|
940
|
+
}
|
|
941
|
+
return { known, organization };
|
|
942
|
+
};
|
|
943
|
+
const ctxFor = (call, hops) => ({ scope: call.scope, line: call.startLine, hops, depth: 0 });
|
|
944
|
+
/** Resolve a URL argument: literal/constant/attribute first, then base_url, then callers. */
|
|
945
|
+
const resolveRequestUrl = (call, urlExpr, client, fallback,
|
|
946
|
+
/** Where `urlExpr` lives when it came from a kwargs dict built elsewhere. */
|
|
947
|
+
exprCtx) => {
|
|
948
|
+
const at = (hops) => (exprCtx ? { ...exprCtx, hops } : ctxFor(call, hops));
|
|
949
|
+
const direct = urlExpr ? resolver.eval(urlExpr, at(0)) : [];
|
|
950
|
+
const absolute = direct.filter((v) => parseUrl(v.text));
|
|
951
|
+
if (absolute.length > 0) {
|
|
952
|
+
const result = destinationsFor(call, absolute, fallback);
|
|
953
|
+
return { ...result, literalUrl: absolute[0]?.text };
|
|
954
|
+
}
|
|
955
|
+
if (client?.baseUrl) {
|
|
956
|
+
const bases = resolver
|
|
957
|
+
.eval(client.baseUrl.expr, { scope: client.baseUrl.scope, line: client.baseUrl.line, hops: 0, depth: 0 })
|
|
958
|
+
.filter((v) => parseUrl(v.text));
|
|
959
|
+
if (bases.length > 0) {
|
|
960
|
+
const rel = direct.length > 0 ? direct : [urlExpr ? placeholder((0, python_source_1.exprText)(model, urlExpr)) : { text: "", sites: [], hint: "" }];
|
|
961
|
+
const joined = bases.flatMap((b) => rel.map((r) => ({ text: joinUrl(b.text, r.text), sites: [...b.sites, ...r.sites], hint: `${b.hint} ${r.hint}` })));
|
|
962
|
+
return destinationsFor(call, joined, fallback);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
const viaCallersAll = urlExpr ? resolver.eval(urlExpr, at(MAX_CALLER_HOPS)) : [];
|
|
966
|
+
const viaCallers = viaCallersAll.filter((v) => parseUrl(v.text));
|
|
967
|
+
if (viaCallers.length > 0)
|
|
968
|
+
return { ...destinationsFor(call, viaCallers, fallback), literalUrl: viaCallers[0]?.text };
|
|
969
|
+
// Absolute URL whose host is only known at runtime (`https://{shop}/api/mcp`): path routes.
|
|
970
|
+
const runtimeHost = [...direct, ...viaCallersAll].filter((v) => /^(?:https?|wss?):\/\/[^/?#\s]*\{/i.test(v.text));
|
|
971
|
+
if (runtimeHost.length > 0)
|
|
972
|
+
return destinationsFor(call, runtimeHost, false);
|
|
973
|
+
return { known: [], organization: false };
|
|
974
|
+
};
|
|
975
|
+
const clientOf = (receiver, call, info) => {
|
|
976
|
+
const name = (0, python_source_1.dottedName)(receiver);
|
|
977
|
+
if (!name)
|
|
978
|
+
return undefined;
|
|
979
|
+
if (info.moduleAliases.has(name))
|
|
980
|
+
return "module";
|
|
981
|
+
for (const binding of resolver.bindingsOf(name, call.scope, call.startLine)) {
|
|
982
|
+
const value = binding.value;
|
|
983
|
+
if (value.kind !== "call")
|
|
984
|
+
continue;
|
|
985
|
+
const ctor = (0, python_source_1.dottedName)(value.func);
|
|
986
|
+
if (!ctor)
|
|
987
|
+
continue;
|
|
988
|
+
const lib = info.constructorLibrary(ctor);
|
|
989
|
+
if (!lib)
|
|
990
|
+
continue;
|
|
991
|
+
const baseUrl = value.kwargs.find((k) => k.name === "base_url")?.value;
|
|
992
|
+
return { library: lib, ...(baseUrl ? { baseUrl: { expr: baseUrl, scope: binding.scope, line: binding.line } } : {}) };
|
|
993
|
+
}
|
|
994
|
+
return undefined;
|
|
995
|
+
};
|
|
996
|
+
let openAiClients = 0;
|
|
997
|
+
let openAiRedirected = 0;
|
|
998
|
+
const mainInfo = moduleInfoFor(model, libraries);
|
|
999
|
+
/**
|
|
1000
|
+
* Detect one outbound call. `ctx` evaluates its arguments; `site` is where findings go
|
|
1001
|
+
* (the call itself, or the caller of a wrapper the call sits in). Returns true when the
|
|
1002
|
+
* call is an outbound call kind, resolved or not.
|
|
1003
|
+
*/
|
|
1004
|
+
const handle = (call, info, ctx, site, viaWrapper) => {
|
|
1005
|
+
const { node } = call;
|
|
1006
|
+
const callee = call.callee ?? "";
|
|
1007
|
+
const last = callee.slice(callee.lastIndexOf(".") + 1);
|
|
1008
|
+
const resolveUrl = (urlExpr, client, fallback, exprCtx) => resolveRequestUrl(site, urlExpr, client, fallback, exprCtx ?? ctx);
|
|
1009
|
+
// 1. Raw HTTP library request calls.
|
|
1010
|
+
if (info.importedLibraries.length > 0 && node.func.kind === "attr" && REQUEST_VERBS.has(node.func.attr)) {
|
|
1011
|
+
const client = clientOf(node.func.object, call, info);
|
|
1012
|
+
if (client) {
|
|
1013
|
+
const library = client === "module" ? info.moduleAliases.get((0, python_source_1.dottedName)(node.func.object)) : client.library;
|
|
1014
|
+
if (client === "module" && library.name === "aiohttp" && node.func.attr !== "request")
|
|
1015
|
+
return true;
|
|
1016
|
+
const urlExpr = METHOD_FIRST_VERBS.has(node.func.attr)
|
|
1017
|
+
? (node.args[1] ?? node.kwargs.find((k) => k.name === "url")?.value)
|
|
1018
|
+
: (node.args[0] ?? node.kwargs.find((k) => k.name === "url" || k.name === "str_or_url")?.value);
|
|
1019
|
+
const resolved = resolveUrl(urlExpr, client === "module" ? undefined : client, true);
|
|
1020
|
+
if (resolved.known.length > 0) {
|
|
1021
|
+
emit(site, resolved.known, { httpClientLibrary: library.name }, library.patternId, library.confidence);
|
|
1022
|
+
}
|
|
1023
|
+
else if (!viaWrapper) {
|
|
1024
|
+
const dedupe = `${exports.OUTBOUND_HTTP_UNKNOWN_FINDING_NAME}|${call.startLine}|${call.endLine}`;
|
|
1025
|
+
if (!emitted.has(dedupe)) {
|
|
1026
|
+
emitted.add(dedupe);
|
|
1027
|
+
findings.push({
|
|
1028
|
+
pattern: library.patternId,
|
|
1029
|
+
name: exports.OUTBOUND_HTTP_UNKNOWN_FINDING_NAME,
|
|
1030
|
+
confidence: library.confidence,
|
|
1031
|
+
location: location({ startLine: call.startLine, endLine: call.endLine }),
|
|
1032
|
+
properties: {
|
|
1033
|
+
httpClientLibrary: library.name,
|
|
1034
|
+
destination: "unknown",
|
|
1035
|
+
...(resolved.literalUrl ? { url: resolved.literalUrl } : {}),
|
|
1036
|
+
},
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
return true;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
// 2. OpenAI-compatible clients pointed at another provider.
|
|
1044
|
+
if (info.openAiImported && OPENAI_CLIENTS.has(last) && (callee === last || callee === `openai.${last}`)) {
|
|
1045
|
+
if (!viaWrapper)
|
|
1046
|
+
openAiClients += 1;
|
|
1047
|
+
const baseUrls = resolver.kwargExprs(node, "base_url", ctx);
|
|
1048
|
+
const known = baseUrls.flatMap((b) => resolveUrl(b.expr, undefined, true, b.ctx).known);
|
|
1049
|
+
const elsewhere = known.filter((d) => d.serviceName.toLowerCase() !== "openai");
|
|
1050
|
+
if (!viaWrapper && elsewhere.length > 0 && elsewhere.length === known.length)
|
|
1051
|
+
openAiRedirected += 1;
|
|
1052
|
+
emit(site, known, { client: "openai_compatible" }, "external_api_call", 0.85);
|
|
1053
|
+
return true;
|
|
1054
|
+
}
|
|
1055
|
+
// 3. MCP over HTTP.
|
|
1056
|
+
if (info.mcpImported && (MCP_URL_CALLS.has(last) || MCP_URL_PARAMS.has(last))) {
|
|
1057
|
+
// `url=` directly, as the first argument, or inside a `**params` dict.
|
|
1058
|
+
const urlSources = !MCP_URL_PARAMS.has(last) && node.args[0] ? [{ expr: node.args[0], ctx }] : resolver.kwargExprs(node, "url", ctx);
|
|
1059
|
+
const known = urlSources.flatMap((source) => resolveUrl(source.expr, undefined, true, source.ctx).known);
|
|
1060
|
+
emit(site, known, { transport: "mcp_http" }, "external_api_call", 0.85);
|
|
1061
|
+
return true;
|
|
1062
|
+
}
|
|
1063
|
+
// 4. Phoenix tracing (not followed through wrappers: the package is the vendor).
|
|
1064
|
+
if (info.isPhoenixCall(callee)) {
|
|
1065
|
+
if (!viaWrapper)
|
|
1066
|
+
emit(site, [{ serviceName: "arize_phoenix", url: "", sites: [] }], { transport: "otlp" }, "external_api_call", 0.85);
|
|
1067
|
+
return true;
|
|
1068
|
+
}
|
|
1069
|
+
// 5. LiteLLM provider prefixes.
|
|
1070
|
+
if (info.isLitellmCall(callee) || info.isAdkLiteLlm(callee)) {
|
|
1071
|
+
// The request goes to api_base when it is set, whatever provider the model prefix
|
|
1072
|
+
// names (an OpenAI-compatible gateway serving "groq/..." is still the gateway). So a
|
|
1073
|
+
// known api_base host decides; the model prefix only counts when api_base is unknown.
|
|
1074
|
+
// A helper with several return branches gives one api_base per branch, so each
|
|
1075
|
+
// branch that names a host contributes its vendor.
|
|
1076
|
+
const bases = ["api_base", "base_url"].flatMap((name) => resolver.kwargExprs(node, name, ctx));
|
|
1077
|
+
const viaBase = bases.flatMap((b) => resolveUrl(b.expr, undefined, true, b.ctx).known);
|
|
1078
|
+
if (viaBase.length > 0) {
|
|
1079
|
+
emit(site, viaBase, { client: "litellm" }, "external_api_call", 0.85);
|
|
1080
|
+
return true;
|
|
1081
|
+
}
|
|
1082
|
+
const models = resolver.kwargExprs(node, "model", ctx);
|
|
1083
|
+
if (models.length === 0 && node.args[0])
|
|
1084
|
+
models.push({ expr: node.args[0], ctx });
|
|
1085
|
+
const providers = [];
|
|
1086
|
+
for (const m of models) {
|
|
1087
|
+
for (const v of resolver.eval(m.expr, m.ctx)) {
|
|
1088
|
+
const routed = router.routeModel(v.text);
|
|
1089
|
+
if (routed === "unknown" || providers.some((p) => p.serviceName === routed.serviceName))
|
|
1090
|
+
continue;
|
|
1091
|
+
providers.push({ ...routed, url: "", sites: [] });
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
emit(site, providers, { client: "litellm" }, "external_api_call", 0.85);
|
|
1095
|
+
return true;
|
|
1096
|
+
}
|
|
1097
|
+
// 6. Google API clients: build("gmail", "v1", ...) names the Google product.
|
|
1098
|
+
if (info.isGoogleBuild(callee)) {
|
|
1099
|
+
const apiExpr = node.args[0] ?? node.kwargs.find((k) => k.name === "serviceName")?.value;
|
|
1100
|
+
const services = [];
|
|
1101
|
+
for (const v of apiExpr ? resolver.eval(apiExpr, ctx) : []) {
|
|
1102
|
+
const serviceName = input.config.thirdParty.googleApiServices.get(v.text.toLowerCase());
|
|
1103
|
+
if (serviceName && !services.some((s) => s.serviceName === serviceName))
|
|
1104
|
+
services.push({ serviceName, url: "", sites: [] });
|
|
1105
|
+
}
|
|
1106
|
+
emit(site, services, { client: "googleapiclient" }, "external_api_call", 0.85);
|
|
1107
|
+
return true;
|
|
1108
|
+
}
|
|
1109
|
+
// 7. Unresolved `(method, url)` helpers such as nexus_call("POST", url, ...): only
|
|
1110
|
+
// catalog hosts count, so ordinary two-string calls do not become destinations.
|
|
1111
|
+
const methodArg = node.args[0];
|
|
1112
|
+
if (methodArg?.kind === "str" && node.args[1] && methodArg.parts.length === 1 && typeof methodArg.parts[0] === "string" && HTTP_METHODS.has(methodArg.parts[0].toUpperCase())) {
|
|
1113
|
+
if (node.func.kind === "attr" && clientOf(node.func.object, call, info))
|
|
1114
|
+
return true;
|
|
1115
|
+
const { known } = resolveUrl(node.args[1], undefined, false);
|
|
1116
|
+
emit(site, known, { client: last || "http_helper" }, "external_api_call", 0.8);
|
|
1117
|
+
return known.length > 0;
|
|
1118
|
+
}
|
|
1119
|
+
return false;
|
|
1120
|
+
};
|
|
1121
|
+
const outgoingLines = new Set();
|
|
1122
|
+
const recordOutgoing = (call) => {
|
|
1123
|
+
for (let l = call.startLine; l <= call.endLine; l += 1)
|
|
1124
|
+
outgoingLines.add(l);
|
|
1125
|
+
const headers = call.node.kwargs.find((k) => k.name === "headers")?.value;
|
|
1126
|
+
const name = headers ? (0, python_source_1.dottedName)(headers) : undefined;
|
|
1127
|
+
if (!name)
|
|
1128
|
+
return;
|
|
1129
|
+
for (const binding of resolver.bindingsOf(name, call.scope, call.startLine)) {
|
|
1130
|
+
const lineOf = resolver.moduleModelOf(binding.scope) === model ? model.lineOf : undefined;
|
|
1131
|
+
if (!lineOf)
|
|
1132
|
+
continue;
|
|
1133
|
+
const end = lineOf(Math.max(binding.value.start, binding.value.end - 1));
|
|
1134
|
+
for (let l = binding.line; l <= end; l += 1)
|
|
1135
|
+
outgoingLines.add(l);
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1138
|
+
for (const call of model.calls) {
|
|
1139
|
+
const ctx = ctxFor(call, 0);
|
|
1140
|
+
const callee = call.callee ?? "";
|
|
1141
|
+
if (mainInfo.constructorLibrary(callee))
|
|
1142
|
+
recordOutgoing(call);
|
|
1143
|
+
if (handle(call, mainInfo, ctx, call, false)) {
|
|
1144
|
+
recordOutgoing(call);
|
|
1145
|
+
continue;
|
|
1146
|
+
}
|
|
1147
|
+
// 8. Pass-through wrappers: a same-repo function whose parameters (named or **kwargs)
|
|
1148
|
+
// reach an outbound call. Evaluate that inner call with this call's arguments bound
|
|
1149
|
+
// and report at this call, where the destination is chosen (one level of wrapping).
|
|
1150
|
+
const target = resolver.callTarget(call.node, ctx);
|
|
1151
|
+
if (!target)
|
|
1152
|
+
continue;
|
|
1153
|
+
const { fn, bindings } = target;
|
|
1154
|
+
const varkw = fn.params.find((p) => p.star === "kwargs");
|
|
1155
|
+
if (varkw) {
|
|
1156
|
+
const { node } = call;
|
|
1157
|
+
const passed = {
|
|
1158
|
+
kind: "coll",
|
|
1159
|
+
elts: node.kwargs.map((k) => k.value),
|
|
1160
|
+
entries: node.kwargs.map((k) => ({ key: k.name, value: k.value })),
|
|
1161
|
+
spreads: node.starKwargs,
|
|
1162
|
+
start: node.start,
|
|
1163
|
+
end: node.end,
|
|
1164
|
+
};
|
|
1165
|
+
bindings.set(varkw.name, { expr: passed, ctx });
|
|
1166
|
+
}
|
|
1167
|
+
if (bindings.size === 0)
|
|
1168
|
+
continue;
|
|
1169
|
+
const owner = resolver.moduleModelOf(fn);
|
|
1170
|
+
const innerInfo = owner === model ? mainInfo : moduleInfoFor(owner, libraries);
|
|
1171
|
+
for (const inner of owner.calls) {
|
|
1172
|
+
if (!isWithin(inner.scope, fn))
|
|
1173
|
+
continue;
|
|
1174
|
+
handle(inner, innerInfo, { scope: inner.scope, line: inner.startLine, hops: 0, depth: 0, bindings }, call, true);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
return {
|
|
1178
|
+
findings,
|
|
1179
|
+
outgoingRequestLines: [...outgoingLines].sort((a, b) => a - b),
|
|
1180
|
+
openAiClientsRedirected: openAiClients > 0 && openAiRedirected === openAiClients,
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
/** Properties of a finding for a remote service of its own (see `Destination.remote`). */
|
|
1184
|
+
function remoteServiceProperties(remote, url, extra) {
|
|
1185
|
+
const displayName = remote.platform ? (0, third_party_detection_config_1.platformServiceDisplayName)(remote.host) : undefined;
|
|
1186
|
+
return {
|
|
1187
|
+
remoteService: true,
|
|
1188
|
+
host: remote.host,
|
|
1189
|
+
url,
|
|
1190
|
+
...(remote.firstParty ? { firstParty: true } : {}),
|
|
1191
|
+
...(remote.platform ? { platform: remote.platform } : {}),
|
|
1192
|
+
...(displayName ? { displayName } : {}),
|
|
1193
|
+
...extra,
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
1196
|
+
/** Finding name for a remote service of its own: the platform display name, else the host. */
|
|
1197
|
+
function remoteServiceName(remote) {
|
|
1198
|
+
return (remote.platform ? (0, third_party_detection_config_1.platformServiceDisplayName)(remote.host) : undefined) ?? remote.host;
|
|
1199
|
+
}
|
|
1200
|
+
function joinUrl(base, path) {
|
|
1201
|
+
if (!path)
|
|
1202
|
+
return base;
|
|
1203
|
+
if (parseUrl(path))
|
|
1204
|
+
return path;
|
|
1205
|
+
return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
1206
|
+
}
|