Repository navigation
Expand file tree
/
Copy pathtest_librepy_import_graph.py
More file actions
395 lines (355 loc) · 16.4 KB
/
Copy pathtest_librepy_import_graph.py
File metadata and controls
395 lines (355 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
"""LibrePy allowlist must cover top-level plugin imports of shipped modules."""
from __future__ import annotations
import ast
import subprocess
import sys
from pathlib import Path
_REPO_ROOT = Path(__file__).resolve().parents[2]
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))
from scripts.build_librepy_oxt import stage_librepy_plugin_tree # noqa: E402
from scripts.build_oxt import sync_vendor_into_lib # noqa: E402
from scripts.librepy_bundle_paths import ( # noqa: E402
LIBREPY_VENDOR_PACKAGES,
collect_librepy_plugin_paths,
)
# Lazy attrs on plugin.framework.client that load modules not in the LibrePy OXT.
_FORBIDDEN_CLIENT_ATTRS = frozenset(
{
"LlmClient",
"OPENROUTER_CHAT_EXTRA_BLOCKLIST",
"merge_openrouter_chat_extra",
"strip_leaked_chat_template_control_tokens",
"EmbeddingBatch",
"embed_texts",
"get_embedding_model",
"iterate_sse",
"run_trusted_analysis",
}
)
from scripts.plugin_import_graph import ( # noqa: E402
_is_shipped_plugin_module,
_module_level_import_nodes,
_plugin_mod_to_candidates,
_resolved_import_from_module,
)
def _get_shipped_paths() -> set[str]:
return set(collect_librepy_plugin_paths(str(_REPO_ROOT)))
def _imported_plugin_modules(path: Path, tree: ast.AST) -> list[str]:
pkg_parts = path.relative_to(_REPO_ROOT).with_suffix("").parts
parent_pkg = pkg_parts[:-1]
found: list[str] = []
for node in _module_level_import_nodes(tree):
if isinstance(node, ast.Import):
for alias in node.names:
if alias.name == "plugin" or alias.name.startswith("plugin."):
found.append(alias.name)
elif isinstance(node, ast.ImportFrom):
if node.level:
if node.level > len(parent_pkg):
continue
rel_base = parent_pkg[: len(parent_pkg) - node.level + 1]
if node.module:
mods = [".".join(rel_base + tuple(node.module.split(".")))]
else:
mods = [".".join(rel_base + (alias.name,)) for alias in node.names]
else:
mods = [node.module] if node.module else []
for mod in mods:
if mod == "plugin" or mod.startswith("plugin."):
found.append(mod)
return found
def _forbidden_client_attr_hits(path: Path, tree: ast.AST) -> list[str]:
"""``from plugin.framework.client import LlmClient`` is not a llm_client prefix hit."""
hits: list[str] = []
for node in _module_level_import_nodes(tree):
if not isinstance(node, ast.ImportFrom):
continue
if _resolved_import_from_module(path, node) != "plugin.framework.client":
continue
if node.names and node.names[0].name == "*":
hits.append("*")
continue
for alias in node.names:
if alias.name in _FORBIDDEN_CLIENT_ATTRS:
hits.append(alias.name)
return hits
def test_librepy_shipped_toplevel_plugin_imports_are_bundled():
shipped = _get_shipped_paths()
missing: list[str] = []
for rel in sorted(shipped):
if not rel.endswith(".py"):
continue
path = _REPO_ROOT / rel
tree = ast.parse(path.read_text(encoding="utf-8"), filename=rel)
for attr in _forbidden_client_attr_hits(path, tree):
missing.append(f"{rel} top-level-imports-forbidden plugin.framework.client.{attr}")
for mod in _imported_plugin_modules(path, tree):
if rel == "plugin/contrib/smolagents/__init__.py":
# build_librepy_oxt.py replaces this with a slim stub.
continue
if not _is_shipped_plugin_module(mod, shipped):
missing.append(f"{rel} -> {mod} (not in LibrePy allowlist)")
assert missing == []
def test_from_client_import_llmclient_is_forbidden():
dummy = _REPO_ROOT / "plugin" / "librepy" / "settings.py"
tree = ast.parse("from plugin.framework.client import LlmClient, sync_request")
assert _forbidden_client_attr_hits(dummy, tree) == ["LlmClient"]
tree_ok = ast.parse("from plugin.framework.client import sync_request")
assert _forbidden_client_attr_hits(dummy, tree_ok) == []
def test_librepy_shipped_function_level_imports_are_safe():
"""Verify that any function-level import of unbundled modules in shipped files is safely guarded."""
shipped = _get_shipped_paths()
known_special_cases = {
# Vendored upstream smolagents helper (unused in LibrePy runtime; executor uses AST helpers)
"plugin/contrib/smolagents/utils.py",
# WriterAgent-only API helper in config (get_api_config for LlmClient)
"plugin/framework/config.py",
# WriterAgent-only core handler registration (register_core_handlers is not called in LibrePy)
"plugin/framework/main_shared.py",
# Venv worker trusted dispatch for domains only registered in WriterAgent
"plugin/scripting/venv/trusted_dispatch.py",
"plugin/scripting/venv/worker_harness.py",
# Image insert page style resolution
"plugin/writer/images/image_tools.py",
# Undo manager title helper in html_import (next_agent_edit_undo_title)
"plugin/writer/html_import.py",
}
def is_guarded(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> bool:
curr = node
while curr in parents:
par = parents[curr]
if isinstance(par, ast.If):
test = par.test
if (isinstance(test, ast.Name) and test.id == "TYPE_CHECKING") or (
isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING"
):
if curr in par.body:
return True
elif isinstance(par, ast.Try):
if curr in par.body:
handler_names = []
for h in par.handlers:
if h.type is None:
handler_names.append("bare")
elif isinstance(h.type, ast.Name):
handler_names.append(h.type.id)
elif isinstance(h.type, ast.Tuple):
handler_names.extend(
elt.id for elt in h.type.elts if isinstance(elt, ast.Name)
)
if any(
n in ("ImportError", "ModuleNotFoundError", "Exception", "BaseException", "bare")
for n in handler_names
):
return True
curr = par
return False
unexpected: list[tuple[str, int, str]] = []
for rel in sorted(shipped):
if not rel.endswith(".py") or rel == "plugin/contrib/smolagents/__init__.py":
continue
if rel in known_special_cases:
continue
path = _REPO_ROOT / rel
tree = ast.parse(path.read_text(encoding="utf-8"), filename=rel)
parents: dict[ast.AST, ast.AST] = {}
for node in ast.walk(tree):
for child in ast.iter_child_nodes(node):
parents[child] = node
pkg_parts = Path(rel).with_suffix("").parts[:-1]
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
if alias.name.startswith("plugin."):
if not _is_shipped_plugin_module(alias.name, shipped):
if not is_guarded(node, parents):
unexpected.append((rel, node.lineno, alias.name))
elif isinstance(node, ast.ImportFrom):
level = node.level
mod = node.module or ""
if level > 0:
if level <= len(pkg_parts):
base = pkg_parts[: len(pkg_parts) - level + 1]
full_mod = ".".join(base + (tuple(mod.split(".")) if mod else ()))
else:
full_mod = None
else:
full_mod = mod if mod.startswith("plugin.") else None
if full_mod and full_mod.startswith("plugin."):
if not _is_shipped_plugin_module(full_mod, shipped):
sub_cands = [
_plugin_mod_to_candidates(f"{full_mod}.{alias.name}")
for alias in node.names
]
if not any(any(sc in shipped for sc in scands) for scands in sub_cands):
if not is_guarded(node, parents):
unexpected.append((rel, node.lineno, full_mod))
assert unexpected == []
def test_librepy_writer_all_plugin_imports_resolve_to_shipped_files():
"""All import statements in LibrePy-shipped plugin/writer files must resolve to shipped files."""
shipped = _get_shipped_paths()
writer_shipped = [
rel for rel in sorted(shipped)
if rel.startswith("plugin/writer/") and rel.endswith(".py")
]
# Pre-existing intentional lazy WriterAgent-only imports (review tracking and search fallbacks).
allowed_lazy = {
"plugin.writer.edit_review",
"plugin.writer.page",
"plugin.writer.review_authors",
"plugin.writer.search",
"plugin.writer.styles",
}
missing: list[str] = []
for rel in writer_shipped:
path = _REPO_ROOT / rel
tree = ast.parse(path.read_text(encoding="utf-8"), filename=rel)
pkg_parts = Path(rel).with_suffix("").parts[:-1]
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
if alias.name.startswith("plugin.") and not _is_shipped_plugin_module(alias.name, shipped):
if alias.name not in allowed_lazy:
missing.append(f"{rel}:{node.lineno} -> {alias.name}")
elif isinstance(node, ast.ImportFrom):
level = node.level
mod = node.module or ""
if level > 0:
base = pkg_parts[: len(pkg_parts) - level + 1]
full_mod = ".".join(base + (tuple(mod.split(".")) if mod else ()))
else:
full_mod = mod
if full_mod and full_mod.startswith("plugin."):
if not _is_shipped_plugin_module(full_mod, shipped):
sub_cands = [
_plugin_mod_to_candidates(f"{full_mod}.{alias.name}")
for alias in node.names
]
if not any(any(sc in shipped for sc in scands) for scands in sub_cands):
if full_mod not in allowed_lazy:
missing.append(f"{rel}:{node.lineno} -> {full_mod}")
assert missing == []
def test_librepy_staged_bundle_imports_without_writeragent(tmp_path: Path):
"""Verify that every shipped LibrePy module imports cleanly in an isolated tree."""
staged = tmp_path / "staged"
stage_librepy_plugin_tree(str(_REPO_ROOT), str(staged))
# Provide slim manifest for testing
(staged / "plugin" / "_manifest.py").write_text(
'"""Slim LibrePy test manifest."""\nMODULES = {}\n',
encoding="utf-8",
)
# Vendor packages into plugin/lib
vendor_dir = _REPO_ROOT / "vendor"
lib_dir = staged / "plugin" / "lib"
sync_vendor_into_lib(
str(vendor_dir),
str(lib_dir),
prune_websockets=False,
only=LIBREPY_VENDOR_PACKAGES,
)
# In production LibrePy builds, thread_guard is replaced with release stubs.
from scripts.strip_code import replace_thread_guard_implementation
replace_thread_guard_implementation(str(staged))
# Isolate subprocess to staged tree without editable finder hooks
script = r"""
import sys, types, os, importlib
from pathlib import Path
staged = sys.argv[1]
# Clear editable finder hooks and site-packages to ensure clean hermetic evaluation
sys.meta_path = [
finder for finder in sys.meta_path
if "editable" not in finder.__class__.__name__.lower() and "writeragent" not in str(finder).lower()
]
sys.path_hooks = [
h for h in sys.path_hooks
if "editable" not in h.__class__.__name__.lower() and "writeragent" not in str(h).lower()
]
sys.path = [staged, os.path.join(staged, "plugin", "lib")] + [
p for p in sys.path if "writeragent" not in p and "site-packages" not in p
]
# Set up UNO mocks in the isolated child process
uno = types.ModuleType("uno")
unohelper = types.ModuleType("unohelper")
class _Base: pass
class _ImplementationHelper:
def addImplementation(self, *args, **kwargs): return None
unohelper.Base = _Base
unohelper.ImplementationHelper = _ImplementationHelper
sys.modules["uno"] = uno
sys.modules["unohelper"] = unohelper
for name in (
"com", "com.sun", "com.sun.star",
"com.sun.star.awt", "com.sun.star.awt.FontSlant", "com.sun.star.awt.grid", "com.sun.star.awt.tree",
"com.sun.star.beans", "com.sun.star.container", "com.sun.star.datatransfer",
"com.sun.star.datatransfer.clipboard",
"com.sun.star.document", "com.sun.star.drawing", "com.sun.star.frame",
"com.sun.star.lang", "com.sun.star.sheet", "com.sun.star.sheet.FormulaResult", "com.sun.star.style",
"com.sun.star.system",
"com.sun.star.table", "com.sun.star.table.CellContentType", "com.sun.star.table.CellHoriJustify",
"com.sun.star.task", "com.sun.star.text",
"com.sun.star.text.ControlCharacter", "com.sun.star.text.TextContentAnchorType",
"com.sun.star.ui", "com.sun.star.ui.ContextMenuInterceptorAction",
"com.sun.star.uno", "com.sun.star.util", "com.sun.star.view", "com.sun.star.xml",
):
mod = types.ModuleType(name)
mod.__path__ = []
sys.modules[name] = mod
for name in list(sys.modules):
if "." in name and name.startswith("com."):
parent_name, child_name = name.rsplit(".", 1)
if parent_name in sys.modules:
setattr(sys.modules[parent_name], child_name, sys.modules[name])
def _iface(mod_name, attr):
cls = type(attr, (), {})
setattr(sys.modules[mod_name], attr, cls)
for mod_name in list(sys.modules):
if mod_name.startswith("com.sun.star"):
for attr in (
"AS_CHARACTER", "AT_CHARACTER", "AT_PARAGRAPH", "AT_PAGE", "AT_FRAME", "PARAGRAPH_BREAK",
"DisposedException", "NoSuchElementException", "IllegalArgumentException",
"RuntimeException", "Exception",
"XDispatch", "XDispatchProvider", "XInitialization", "XServiceInfo",
"XJob", "XJobExecutor", "XModifyListener", "XCloseListener",
"XTerminateListener", "DispatchDescriptor", "PropertyValue", "NamedValue",
"XControlModel", "XControl", "XWindow", "XActionListener", "XItemListener",
"XTextListener", "XTextComponent", "XListBox", "XComboBox", "XCheckBox", "XRadioButton",
"XDialog", "XDialogProvider2", "XTopWindow", "XTopWindowListener",
"XSidebarPanel", "XToolPanel", "XUIElement", "XUIElementFactory",
"Size", "Point", "FontWeight",
"NONE", "OBLIQUE", "ITALIC",
"EMPTY", "VALUE", "TEXT", "FORMULA", "ERROR",
"CENTER", "LEFT", "RIGHT", "BLOCK", "STANDARD",
"EmptyUndoStackException", "MalformedNumberFormatException", "NotNumericException",
"BorderLineStyle", "CellRangeAddress", "TableSortField",
"ActionTriggerSeparatorType", "XContextMenuInterceptor", "IGNORED", "CONTINUE_MODIFIED",
"AttributeData", "SystemShellExecuteFlags", "XTransferable", "DataFlavor",
"XUndoAction", "ImageType", "Rectangle",
):
_iface(mod_name, attr)
paths = sys.argv[2:]
errors = []
for p in paths:
if p.endswith(".py"):
rel = p[:-3].replace("/", ".")
if rel.endswith(".__init__"):
rel = rel[:-9]
try:
importlib.import_module(rel)
except Exception as e:
errors.append((rel, f"{type(e).__name__}: {e}"))
if errors:
print(f"FAILED_IMPORTS: {len(errors)}")
for rel, err in errors:
print(f" {rel}: {err}")
sys.exit(1)
"""
paths = collect_librepy_plugin_paths(str(_REPO_ROOT))
proc = subprocess.run(
[sys.executable, "-c", script, str(staged), *paths],
cwd=str(staged),
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, proc.stdout + "\n" + proc.stderr