This is an automated email from the ASF dual-hosted git repository. jimjag pushed a commit to branch odf-devel in repository https://gitbox.apache.org/repos/asf/openoffice.git
commit cc94f217e7d4aa80575ebd7a126b5131714f3e85 Author: Jim Jagielski <[email protected]> AuthorDate: Mon Oct 26 12:14:45 2026 -0400 test/odf-validate: validate as an extended document with foreign content removed --- test/odf-validate/README.md | 6 +- test/odf-validate/foreign.py | 150 +++++++++++++++++++++++++++++++++++++ test/odf-validate/make-controls.py | 2 + test/odf-validate/report.py | 4 +- test/odf-validate/selftest.py | 30 ++++++++ test/odf-validate/validate.py | 23 ++++-- 6 files changed, 205 insertions(+), 10 deletions(-) diff --git a/test/odf-validate/README.md b/test/odf-validate/README.md index 570de79694..b862d0ddb4 100644 --- a/test/odf-validate/README.md +++ b/test/odf-validate/README.md @@ -42,7 +42,11 @@ The steps: - It resumes where it left off, kills a hung office and continues, and stops at the first crash. - `validate.py` checks content, styles, meta, settings and manifest streams - against 1.2 as written and against 1.4 with `office:version` rewritten. + against 1.2 as written, against 1.4 with `office:version` rewritten, and + against 1.2 as an extended document (`12x`): `foreign.py` first removes + foreign elements and attributes as Part 1 §2.2.2 B.1 and §3.17 describe (the + manifest is left as written). Use `report.py <val.json> <kinds.json> 12x` to + measure what is wrong apart from foreign content. Embedded objects whose `content.xml` is MathML are skipped (ODF 1.2 Part 1 §2.2.1 B.4). - `report.py` groups the errors by normalized message. diff --git a/test/odf-validate/foreign.py b/test/odf-validate/foreign.py new file mode 100644 index 0000000000..ca988c7a63 --- /dev/null +++ b/test/odf-validate/foreign.py @@ -0,0 +1,150 @@ +#************************************************************** +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +#************************************************************** + +# Removes foreign elements and attributes (ODF 1.2 Part 1 3.17) so that the rest can be validated as an +# extended document (2.2.2 B.1). Loaded by validate.py and selftest.py. +# foreign attribute: namespace outside tables 1-4 of 1.5 (xml: included), removed. +# foreign element: namespace outside tables 1-4, outside any element of tables 1-4 (their wildcard +# content is the schema's), removed with its content, except that its tags alone are removed when +# it sits in a text:p or text:h and every ancestor up to it permits character data in the schema. +# office:process-content (deprecated in 1.2) is not consulted. Table 4 names that the schema does not +# define are not removed, so they stay visible as errors. +import re +from xml.etree import ElementTree as ET +from xml.parsers import expat +from xml.sax.saxutils import escape, quoteattr + +ODF = "urn:oasis:names:tc:opendocument:xmlns:%s:1.0" +T123 = {ODF % x for x in "animation chart config database dr3d drawing form manifest meta datastyle office presentation script table text style " + "xsl-fo-compatible svg-compatible smil-compatible".split()} | {"http://docs.oasis-open.org/ns/office/1.2/meta/odf#"} +T4 = {"http://purl.org/dc/elements/1.1/", "http://www.w3.org/1998/Math/MathML", "http://www.w3.org/2002/xforms", "http://www.w3.org/1999/xlink", + "http://www.w3.org/1999/xhtml", "http://www.w3.org/2003/g/data-view#", "http://www.w3.org/XML/1998/namespace"} +RNG = "{http://relaxng.org/ns/structure/1.0}" +TEXT_P, TEXT_H = "{%s}p" % (ODF % "text"), "{%s}h" % (ODF % "text") + + +def mixed_elements(rng_path): + """Expanded names of the schema's elements whose content model permits character data.""" + prefixes = dict(re.findall(r'xmlns:(\w+)="([^"]+)"', open(rng_path, encoding="utf-8").read(4000))) + defines = {} + for d in ET.parse(rng_path).getroot().iter(RNG + "define"): + defines.setdefault(d.get("name"), []).append(d) + memo = {} + + def has_text(node, seen): + tag = node.tag + if tag in (RNG + "text", RNG + "mixed"): + return True + if tag in (RNG + "element", RNG + "attribute", RNG + "data", RNG + "value"): + return False + if tag == RNG + "ref": + n = node.get("name") + if n in seen: + return False + return any(has_text(c, seen | {n}) for d in defines.get(n, []) for c in d) + return any(has_text(c, seen) for c in node) + out = set() + for el in ET.parse(rng_path).getroot().iter(RNG + "element"): + name = el.get("name") + if name and ":" in name: + pre, local = name.split(":", 1) + if any(has_text(c, frozenset()) for c in el): + out.add("{%s}%s" % (prefixes[pre], local)) + return out + + +def strip_foreign(text, mixed): + out, scopes, frames, state = [], [{"xml": "http://www.w3.org/XML/1998/namespace"}], [], {"drop": 0, "pending": {}} + p = expat.ParserCreate() + p.ordered_attributes = True + + def expand(name, scope, is_attr): + """Expanded name, or None when the prefix is unbound (kept, so that the validator reports it).""" + if ":" in name: + pre, local = name.split(":", 1) + return "{%s}%s" % (scope[pre], local) if pre in scope else None + uri = "" if is_attr else scope.get("", "") + return "{%s}%s" % (uri, name) if uri else name + + def ns_of(expanded): + return expanded[1:].split("}", 1)[0] if expanded and expanded.startswith("{") else "" + + def start(name, attrs): + if state["drop"]: + state["drop"] += 1 + return + decl = {} + for i in range(0, len(attrs), 2): + if attrs[i] == "xmlns" or attrs[i].startswith("xmlns:"): + decl[attrs[i][6:]] = attrs[i + 1] + scope = dict(scopes[-1]) + scope.update(decl) + exp = expand(name, scope, False) + in_t4 = any(ns_of(f[0]) in T4 for f in frames if f[1]) + if exp is not None and ns_of(exp) not in T123 | T4 and not in_t4: + if unwrap(frames): + scopes.append(scope) + frames.append((exp, False)) + state["pending"].update(decl) + else: + state["drop"] = 1 + return + kept = [] + for i in range(0, len(attrs), 2): + k, v = attrs[i], attrs[i + 1] + ke = expand(k, scope, True) + if k == "xmlns" or k.startswith("xmlns:") or ":" not in k or ke is None or ns_of(ke) in T123 | T4: + kept.append((k, v)) + have = {k for k, _ in kept} + for pre, uri in state["pending"].items(): + k = "xmlns:" + pre if pre else "xmlns" + if k not in have: + kept.insert(0, (k, uri)) + state["pending"] = {} + out.append("<" + name + "".join(" %s=%s" % (k, quoteattr(v, {"\n": " ", "\t": "	", "\r": " "})) for k, v in kept) + ">") + scopes.append(scope) + frames.append((exp, True)) + + def end(name): + if state["drop"]: + state["drop"] -= 1 + return + scopes.pop() + if frames.pop()[1]: + out.append("</" + name + ">") + + def data(s): + if not state["drop"]: + out.append(escape(s)) + + def unwrap(fr): + """Foreign element in a paragraph, every ancestor up to it permitting character data?""" + for exp, kept in reversed(fr): + if not kept: + continue + if exp in (TEXT_P, TEXT_H): + return True + if exp not in mixed: + return False + return False + p.StartElementHandler, p.EndElementHandler, p.CharacterDataHandler = start, end, data + p.Parse(text.encode("utf-8") if isinstance(text, str) else text, True) + return '<?xml version="1.0" encoding="UTF-8"?>\n' + "".join(out) + "\n" diff --git a/test/odf-validate/make-controls.py b/test/odf-validate/make-controls.py index f29e54d065..47f2e3de73 100644 --- a/test/odf-validate/make-controls.py +++ b/test/odf-validate/make-controls.py @@ -55,3 +55,5 @@ mk("badid2", "1.2", '<text:p xml:id="a b">x</text:p>') mk("badns", "1.2", "<text:p><zz:span/></text:p>") # Part 3 2.2.1 F: signature files are held to the same rules (validate.py does not look at them) mk("badsig", "1.2", "<text:p>hi</text:p>", {"META-INF/documentsignatures.xml": '<a><b xml:id="x"/><b xml:id="x"/></a>'}) +# Part 1 2.2.2 B.1: valid as an extended document only (foreign attribute, foreign element in a paragraph, foreign element elsewhere) +mk("extforeign", "1.2", '<text:p xmlns:foo="urn:foo" foo:x="1">a<foo:y>b</foo:y>c</text:p><foo:w xmlns:foo="urn:foo">z<text:p>q</text:p></foo:w>') diff --git a/test/odf-validate/report.py b/test/odf-validate/report.py index 8a3fb3ccaf..9fdce2431c 100644 --- a/test/odf-validate/report.py +++ b/test/odf-validate/report.py @@ -19,7 +19,7 @@ # #************************************************************** -# usage: report.py <val.json> <kinds.json> [12|14] -- groups errors by normalized message +# usage: report.py <val.json> <kinds.json> [12|14|12x] -- groups errors by normalized message import sys, re, json, collections @@ -39,6 +39,6 @@ for f, line, col, msg in d["errors"][ver]: res = {k: {"errors": v["errors"], "packages": sorted(v["packages"])} for k, v in kinds.items()} json.dump(res, open(out, "w"), indent=1, sort_keys=True) tot = sum(v["errors"] for v in res.values()) -print(f"ODF {ver[0]}.{ver[1]}: {len(res)} kinds, {tot} errors, {len({p for v in res.values() for p in v['packages']})} packages with errors") +print(f"ODF {ver[0]}.{ver[1]}{' extended, foreign content removed' if ver.endswith('x') else ''}: {len(res)} kinds, {tot} errors, {len({p for v in res.values() for p in v['packages']})} packages with errors") for k, v in sorted(res.items(), key=lambda kv: -kv[1]["errors"]): print(f" {v['errors']:5d} {len(v['packages']):4d} {k[:120]}") diff --git a/test/odf-validate/selftest.py b/test/odf-validate/selftest.py index e63bcc77ca..f18dc80b22 100644 --- a/test/odf-validate/selftest.py +++ b/test/odf-validate/selftest.py @@ -92,6 +92,36 @@ for n, (st, attr, val, msg) in enumerate(cases): for c in bad_cases[:10]: print("CASE", *c) checks["formulacheck: all %d cases in formula-cases.tsv give exactly the expected findings" % len(cases)] = not bad_cases and len(cases) > 100 +checks.update({ + "extended: extforeign.odt invalid as written, valid once foreign content is removed": bool(errs("12", "extforeign.odt")) and not errs("12x", "extforeign.odt"), + "extended: good.odt, goodid.odt clean": not errs("12x", "good.odt") and not errs("12x", "goodid.odt"), + "extended: bad.odt (unknown element in an ODF namespace) still flagged": any('"text:bogus"' in m for m in errs("12x", "bad.odt")), + "extended: wrongver.odt (attribute in an ODF namespace) still flagged": any("office:version" in m for m in errs("12x", "wrongver.odt")), + "extended: badns.odt (unbound prefix) still flagged": any("not bound" in m for m in errs("12x", "badns.odt")), +}) +fspec = importlib.util.spec_from_file_location("foreign", os.path.join(D, "foreign.py")) +fg = importlib.util.module_from_spec(fspec) +fspec.loader.exec_module(fg) +MIXED = fg.mixed_elements(os.path.join(D, "schema", "OpenDocument-v1.2-os-schema.rng")) +HDR = ('<office:text xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" ' + 'xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:foo="urn:foo" xmlns:dc="http://purl.org/dc/elements/1.1/" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xf="http://www.w3.org/2002/xforms"') +FOREIGN_CASES = [ + ("foreign attribute removed", '<text:p foo:x="1" text:style-name="a">t</text:p>', '<text:p text:style-name="a">t</text:p>'), + ("foreign element outside a paragraph dropped with its content", '<foo:x>stuff<text:p>q</text:p></foo:x><text:p>t</text:p>', '<text:p>t</text:p>'), + ("foreign element in a paragraph: tags removed, content kept", '<text:p>a<foo:x>b<text:span>c</text:span></foo:x>d</text:p>', '<text:p>a<text:span>c</text:span>bd</text:p>'.replace("<text:span>c</text:span>bd", "b<text:span>c</text:span>d")), + ("foreign element in a span in a paragraph: tags removed", '<text:p><text:span>a<foo:x>b</foo:x></text:span></text:p>', '<text:p><text:span>ab</text:span></text:p>'), + ("foreign element below a frame (no character data): dropped", '<text:p><draw:frame><foo:x>b</foo:x></draw:frame></text:p>', '<text:p><draw:frame></draw:frame></text:p>'), + ("namespace declared on an unwrapped element is kept for its children", '<text:p><foo:x xmlns:t2="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><t2:span>a</t2:span></foo:x></text:p>', + '<text:p><t2:span xmlns:t2="urn:oasis:names:tc:opendocument:xmlns:text:1.0">a</t2:span></text:p>'), + ("elements and attributes of table 4 namespaces kept", '<text:p xlink:href="u"><dc:title>t</dc:title></text:p>', '<text:p xlink:href="u"><dc:title>t</dc:title></text:p>'), + ("content below a table 4 element kept (wildcard content)", '<xf:model><foo:data><bar/></foo:data></xf:model>', '<xf:model><foo:data><bar></bar></foo:data></xf:model>'), + ("text is escaped again", '<text:p>a & b < c</text:p>', '<text:p>a & b < c</text:p>'), +] +for name, src, want in FOREIGN_CASES: + got = fg.strip_foreign(HDR + ">" + src + "</office:text>", MIXED).split("\n", 1)[1].strip() + inner = got[got.index(">") + 1:-len("</office:text>")] if got.startswith("<office:text") else got + checks["foreign.py: " + name] = inner == want for k, ok in checks.items(): print(("PASS " if ok else "FAIL ") + k) sys.exit(0 if all(checks.values()) else 1) diff --git a/test/odf-validate/validate.py b/test/odf-validate/validate.py index f905957793..d4bb275156 100644 --- a/test/odf-validate/validate.py +++ b/test/odf-validate/validate.py @@ -20,13 +20,19 @@ #************************************************************** # usage: validate.py <outdir> <val.json> -# Validates every package in <outdir> against ODF 1.2 as written and ODF 1.4 with the version rewritten. -import sys, os, re, zipfile, subprocess, json, shutil +# Validates every package in <outdir> against ODF 1.2 as written, against ODF 1.4 with the version rewritten ("14"), +# and against ODF 1.2 after removing foreign elements and attributes ("12x", Part 1 2.2.2 B.1; manifest left as written). +import sys, os, re, zipfile, subprocess, json, shutil, importlib.util D = os.path.dirname(os.path.abspath(__file__)) JING = ["java", "-jar", os.environ.get("ODFV_JING", "/Applications/XMLauthor/lib/jing.jar"), "-i"] SCH = {"12": (D + "/schema/OpenDocument-v1.2-os-schema.rng", D + "/schema/OpenDocument-v1.2-os-manifest-schema.rng"), "14": (D + "/schema/OpenDocument-v1.4-schema.rng", D + "/schema/OpenDocument-v1.4-manifest-schema.rng")} +SCH["12x"] = SCH["12"] +VERSIONS = ("12", "14", "12x") +_spec = importlib.util.spec_from_file_location("foreign", D + "/foreign.py") +foreign = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(foreign) STREAMS = {"content.xml", "styles.xml", "meta.xml", "settings.xml"} # ODF 1.2 Part 1 2.2.1 B.4: a content.xml rooted at MathML is validated against MathML, not ODF ERR = re.compile(r"^(.*?):(\d+):(\d+): (error|fatal|warning): (.*)$") @@ -43,7 +49,8 @@ def main(): if not work.startswith(os.path.join(D, "runs") + os.sep): sys.exit("validate.py: <val.json> must live under " + os.path.join(D, "runs")) shutil.rmtree(work, ignore_errors=True) - files = {"12": ([], []), "14": ([], [])} + files = {v: ([], []) for v in VERSIONS} + mixed = foreign.mixed_elements(SCH["12"][0]) skipped, bad_zip = [], [] pkgs = sorted(p for p in os.listdir(outdir) if not p.startswith(".")) for pkg in pkgs: @@ -58,17 +65,19 @@ def main(): text = z.read(name).decode("utf-8") if not is_mani and name.endswith("content.xml") and root_is_mathml(text): skipped.append(pkg + "/" + name); continue - for v in ("12", "14"): + for v in VERSIONS: t = text if v == "14": attr = "manifest:version" if is_mani else "office:version" t = re.sub(attr + '="1.2"', attr + '="1.4"', t, count=1) + elif v == "12x" and not is_mani: + t = foreign.strip_foreign(t, mixed) p = os.path.join(work, v, pkg, name) os.makedirs(os.path.dirname(p), exist_ok=True) open(p, "w", encoding="utf-8").write(t) files[v][1 if is_mani else 0].append(p) errors = {} - for v in ("12", "14"): + for v in VERSIONS: errs = [] for schema, fl in ((SCH[v][0], files[v][0]), (SCH[v][1], files[v][1])): while fl: @@ -87,8 +96,8 @@ def main(): errors[v] = errs json.dump({"packages": pkgs, "bad_zip": bad_zip, "mathml_skipped": skipped, "nfiles": len(files["12"][0]) + len(files["12"][1]), "errors": errors}, open(valjson, "w")) - for v in ("12", "14"): - print(f"ODF {v[0]}.{v[1]}: {len(errors[v])} errors in {len({e[0].split('/')[0] for e in errors[v]})} of {len(pkgs)} packages") + for v in VERSIONS: + print(f"ODF {v[0]}.{v[1]}{' extended, foreign content removed' if v == '12x' else ''}: {len(errors[v])} errors in {len({e[0].split('/')[0] for e in errors[v]})} of {len(pkgs)} packages") print(f"files validated: {len(files['12'][0]) + len(files['12'][1])}, MathML skipped: {len(skipped)}, bad zips: {bad_zip}") unparsed = [e for v in errors for e in errors[v] if e[0] == "?"] if unparsed:
