kuhy_credit: fix red-team findings, Flutter harness

Held Enter no longer opens the site (Tk, web), Godot exports
rebuild after _init, strict SVG parser, relative --dir.

Todo: 3a5477b9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-20 16:07:08 +01:00
parent 50473d2d26
commit 826f9946e8
21 changed files with 231 additions and 47 deletions

View File

@ -74,9 +74,11 @@ class Page:
)
time.sleep(0.15)
def key(self, key: str, code: str, vk: int, text: str = "") -> None:
def key(self, key: str, code: str, vk: int, text: str = "", *, repeat: bool = False) -> None:
"""Press and release one key; ``text`` makes Enter/Space activate."""
extra = {"text": text} if text else {}
extra: dict[str, object] = {"text": text} if text else {}
if repeat:
extra["autoRepeat"] = True
self.s.call(
"Input.dispatchKeyEvent",
type="keyDown" if text else "rawKeyDown",

View File

@ -63,6 +63,8 @@ def run(page: Page, port: int, theme: str, shots: Path | None) -> None:
page.key("Tab", "Tab", 9)
page.key("Enter", "Enter", 13, "\r")
assert is_open(page), "Tab + Enter did not open the panel"
page.key("Enter", "Enter", 13, "\r", repeat=True)
assert page.opened() == [CREDIT["url"]], "holding Enter opened the site"
assert page.opened() == [CREDIT["url"]], "a close path opened the site"
foreign = page.foreign_requests()
assert not foreign, f"network requests off loopback: {foreign}"

View File

@ -19,8 +19,7 @@ class CreditDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
final dark =
MediaQuery.platformBrightnessOf(context) == Brightness.dark;
final dark = MediaQuery.platformBrightnessOf(context) == Brightness.dark;
return WidgetsApp(
color: Color(dark ? kDarkBg : kLightBg),
pageRouteBuilder: <T>(settings, builder) => PageRouteBuilder<T>(
@ -32,10 +31,7 @@ class CreditDemo extends StatelessWidget {
child: const SafeArea(
child: Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: EdgeInsets.all(16),
child: KuhyCredit(),
),
child: Padding(padding: EdgeInsets.all(16), child: KuhyCredit()),
),
),
),

View File

@ -103,8 +103,7 @@ class _KuhyCreditState extends State<KuhyCredit> {
@override
Widget build(BuildContext context) {
final dark =
MediaQuery.platformBrightnessOf(context) == Brightness.dark;
final dark = MediaQuery.platformBrightnessOf(context) == Brightness.dark;
final above = !widget.below;
final end = !widget.alignStart;
final logo = Semantics(

View File

@ -20,29 +20,29 @@ Future<List<Uri>> _pump(
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
await tester.pumpWidget(
WidgetsApp(
color: const Color(kDarkBg),
pageRouteBuilder: _route,
home: Stack(
children: [
const Positioned(
left: 0,
top: 0,
child: SizedBox(width: 40, height: 40),
),
Align(
alignment: at,
child: Padding(
padding: const EdgeInsets.all(16),
child: KuhyCredit(
below: below,
alignStart: alignStart,
launcher: (uri) async => opened.add(uri),
),
color: const Color(kDarkBg),
pageRouteBuilder: _route,
home: Stack(
children: [
const Positioned(
left: 0,
top: 0,
child: SizedBox(width: 40, height: 40),
),
Align(
alignment: at,
child: Padding(
padding: const EdgeInsets.all(16),
child: KuhyCredit(
below: below,
alignStart: alignStart,
launcher: (uri) async => opened.add(uri),
),
),
],
),
),
],
),
),
);
return opened;
}
@ -196,10 +196,10 @@ void main() {
final fake = _FakeLauncher();
UrlLauncherPlatform.instance = fake;
await tester.pumpWidget(
const WidgetsApp(
color: Color(kDarkBg),
WidgetsApp(
color: const Color(kDarkBg),
pageRouteBuilder: _route,
home: Center(child: KuhyCredit()),
home: const Center(child: KuhyCredit()),
),
);
await tester.tap(_logo);

View File

@ -91,6 +91,7 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--check", action="store_true", help="fail on drift, write nothing")
parser.add_argument("--dir", type=Path, default=CREDIT_DIR, help="the kuhy_credit dir")
args = parser.parse_args(argv)
args.dir = args.dir.resolve()
if not args.check:
write(args.dir)
print(f"wrote {len(STACKS)} stacks")

View File

@ -15,7 +15,8 @@ import xml.etree.ElementTree as ET
from dataclasses import dataclass
_NS = "{http://www.w3.org/2000/svg}"
_TOKEN = re.compile(r"[A-Za-z]|-?\d+(?:\.\d+)?")
_TOKEN = re.compile(r"[A-Za-z]|-?(?:\d+(?:\.\d*)?|\.\d+)")
_SEPARATORS = re.compile(r"[\s,]*")
@dataclass(frozen=True)
@ -37,6 +38,9 @@ class Logo:
def _subpaths(d: str) -> list[list[float]]:
"""Split path data into point lists, one per M ... Z subpath."""
if _SEPARATORS.fullmatch(_TOKEN.sub(" ", d)) is None:
msg = f"unparsed characters in path data: {_TOKEN.sub('', d)!r}"
raise ValueError(msg)
out: list[list[float]] = []
current: list[float] = []
for tok in _TOKEN.findall(d):
@ -50,6 +54,9 @@ def _subpaths(d: str) -> list[list[float]]:
raise ValueError(msg)
else:
current.append(float(tok))
if current:
msg = "path data ends without Z: an open subpath would be dropped"
raise ValueError(msg)
return out
@ -70,6 +77,9 @@ def _check_disjoint(polys: list[list[float]]) -> None:
def parse_logo(text: str) -> Logo:
"""Parse the SVG text into a :class:`Logo`."""
root = ET.fromstring(text) # noqa: S314 - our own checked-in art
if any("transform" in el.attrib for el in root.iter()):
msg = "transform attributes are unsupported: bake them into the path data"
raise ValueError(msg)
size = int(float(root.attrib["viewBox"].split()[2]))
field = next((r for r in root.iter(f"{_NS}rect") if r.get("id") == "field"), None)
field = field if field is not None else root.find("rect[@id='field']")

View File

@ -0,0 +1 @@
uid://u31d1bclwg4t

View File

@ -9,7 +9,8 @@ extends Control
const CreditData = preload("credit_data.gd")
@export var logo_size := 48
@export var logo_size := 48:
set = _set_logo_size
@export var placement_below := false
@export var align_start := false
@export var light := false:
@ -26,11 +27,8 @@ var label: Label
func _init() -> void:
opener = _shell_open
logo = TextureButton.new()
logo.texture_normal = _logo_texture(logo_size)
logo.ignore_texture_size = true
logo.stretch_mode = TextureButton.STRETCH_KEEP_ASPECT_CENTERED
logo.custom_minimum_size = Vector2(logo_size, logo_size)
logo.size = logo.custom_minimum_size
logo.focus_mode = Control.FOCUS_ALL
logo.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
logo.accessibility_name = CreditData.TEXT
@ -46,7 +44,6 @@ func _init() -> void:
row.add_theme_constant_override("separation", CreditData.SPACE_SM)
row.mouse_filter = Control.MOUSE_FILTER_IGNORE
panel_logo = TextureRect.new()
panel_logo.texture = logo.texture_normal
panel_logo.mouse_filter = Control.MOUSE_FILTER_IGNORE
label = Label.new()
label.text = CreditData.TEXT
@ -56,8 +53,7 @@ func _init() -> void:
row.add_child(label)
panel.add_child(row)
add_child(panel)
custom_minimum_size = logo.custom_minimum_size
size = custom_minimum_size
_set_logo_size(logo_size)
_apply_theme()
@ -98,7 +94,7 @@ func _toggle() -> void:
func _on_panel_input(event: InputEvent) -> void:
var clicked := (
var clicked: bool = (
event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT
)
if clicked or event.is_action_pressed("ui_accept"):
@ -107,6 +103,20 @@ func _on_panel_input(event: InputEvent) -> void:
opener.call(CreditData.URL)
## Scene/inspector values arrive after _init, so the size rebuilds here.
func _set_logo_size(value: int) -> void:
logo_size = value
close()
var texture := _logo_texture(value)
var edge := Vector2(value, value)
logo.texture_normal = texture
logo.custom_minimum_size = edge
logo.size = edge
panel_logo.texture = texture
custom_minimum_size = edge
size = edge
func _set_light(value: bool) -> void:
light = value
_apply_theme()

View File

@ -0,0 +1 @@
uid://oi22ee8n1yy3

View File

@ -0,0 +1 @@
uid://yyyduq0pwbr1

View File

@ -75,7 +75,8 @@ main() {
trap cleanup EXIT
export XDG_DATA_HOME="$TMP/xdg"
# GUT's own class_names need a class cache before a script run.
godot_run --headless --path "$HERE" --import >/dev/null 2>&1 || true
local imported
imported="$(godot_run --headless --path "$HERE" --import 2>&1)" || true
local out code=0 start="$SECONDS"
out="$(godot_run --headless --audio-driver Dummy \
--path "$HERE" -s addons/gut/gut_cmdln.gd -gexit "$@" 2>&1)" || code=$?
@ -86,7 +87,7 @@ main() {
pending="$(total_of "Risky/Pending" "$out")"
if [[ "$code" -eq 124 || "$code" -eq 137 || "$code" -eq 143 ]]; then
why="timed out or killed after ${RUN_TIMEOUT}s (exit $code)"
elif grep -qE 'SCRIPT ERROR|Failing Tests' <<<"$out" || ((failing > 0)); then
elif grep -qE 'SCRIPT ERROR|Failing Tests' <<<"$out$imported" || ((failing > 0)); then
why="failing tests or a script error"
elif ((code != 0)); then
why="exit code $code"

View File

@ -0,0 +1,26 @@
extends SceneTree
## Screenshot helper (not a test): renders the demo closed and open, saves PNGs.
## godot --path kuhy_credit/godot --rendering-driver opengl3 \
## -s res://tests/shot.gd -- <out_dir> [--light]
const Demo = preload("res://demo/demo.tscn")
func _initialize() -> void:
_run.call_deferred()
func _run() -> void:
var args := OS.get_cmdline_user_args()
var out: String = args[0]
var theme := "light" if args.has("--light") else "dark"
var demo: Control = Demo.instantiate()
root.add_child(demo)
for state in ["closed", "open"]:
if state == "open":
demo.credit.logo.pressed.emit()
for _i in 5:
await process_frame
var img := root.get_texture().get_image()
img.save_png(out.path_join("godot-%s-%s.png" % [theme, state]))
quit()

View File

@ -0,0 +1 @@
uid://do527xwgc25r5

View File

@ -125,6 +125,29 @@ func test_below_and_start_placement() -> void:
assert_almost_eq(p.position.x, l.position.x, 0.5)
func test_logo_size_set_after_init_resizes_and_anchors() -> void:
credit.logo_size = 96
assert_eq(credit.logo.size, Vector2(96, 96))
assert_eq(credit.size, Vector2(96, 96))
assert_eq(credit.logo.texture_normal.get_width(), 96)
await _click(credit.logo)
var p: Rect2 = credit.panel.get_global_rect()
assert_almost_eq(p.end.x, credit.logo.get_global_rect().end.x, 0.5)
func test_scene_values_apply_on_instantiate() -> void:
var packed := PackedScene.new()
var node: Control = Scene.instantiate()
node.logo_size = 64
node.placement_below = true
packed.pack(node)
node.free()
var fresh: Control = packed.instantiate()
add_child_autofree(fresh)
assert_eq(fresh.logo.size, Vector2(64, 64))
assert_true(fresh.placement_below)
func test_theme_colours_come_from_tokens() -> void:
var box: StyleBoxFlat = credit.panel.get_theme_stylebox("panel")
assert_eq(box.bg_color, CreditData.DARK.surface)

View File

@ -0,0 +1 @@
uid://l314u8vgev8d

View File

@ -97,9 +97,15 @@ class KuhyCredit(tk.Canvas):
self.bind("<Button-1>", self._toggle)
for widget in (self.panel, self.panel_logo, self.label):
widget.bind("<Button-1>", self._activate)
# A held key must not open the site: the press that opened the panel
# stays "held" until released, and X autorepeat (a release and a press
# with the same timestamp) does not count as a release.
self._held = False
self._released_at = -1
for key in _KEYS:
self.bind(key, self._toggle)
self.panel.bind(key, self._activate)
self.bind(key, self._key_toggle)
self.panel.bind(key, self._key_activate)
self.panel.bind(key.replace("<", "<KeyRelease-", 1), self._key_released)
self._top.bind("<Escape>", self._escape, add="+")
self._top.bind("<Button-1>", self._outside, add="+")
@ -129,6 +135,20 @@ class KuhyCredit(tk.Canvas):
else:
self.open()
def _key_toggle(self, event: tk.Event) -> None:
self._held = True
self._toggle(event)
def _key_released(self, event: tk.Event) -> None:
self._held = False
self._released_at = event.time
def _key_activate(self, event: tk.Event) -> None:
if self._held or event.time == self._released_at:
self._held = True
return
self._activate(event)
def _activate(self, _event: tk.Event | None = None) -> None:
self.close()
self._open_url(URL)

View File

@ -158,3 +158,36 @@ def test_gdscript_strings_follow_gdformat_quoting() -> None:
assert emit._gd_str('a"b') == "'a\"b'"
assert emit._gd_str("a'b\"") == '"a\'b\\""'
assert emit._gd_str("plain") == '"plain"'
@pytest.mark.parametrize(
("d", "match"),
[
("M.5 0L100 0L100 100Z", None),
("M0 0L100 0L100 100", "without Z"),
("M0 0L100 0;L5 5Z", "unparsed"),
],
)
def test_path_data_is_parsed_strictly(d: str, match: str | None) -> None:
doc = f'<svg viewBox="0 0 10 10"><rect id="field" fill="#000000"/><path fill="#FFFFFF" d="{d}"/></svg>'
if match is None:
assert svg.parse_logo(doc).shapes[0].points[:2] == (0.5, 0.0)
else:
with pytest.raises(ValueError, match=match):
svg.parse_logo(doc)
def test_transforms_are_rejected() -> None:
doc = (
'<svg viewBox="0 0 10 10"><rect id="field" fill="#000000"/>'
'<g transform="translate(5 5)"><path fill="#FFFFFF" d="M1 1L5 1L5 5Z"/></g></svg>'
)
with pytest.raises(ValueError, match="transform"):
svg.parse_logo(doc)
def test_relative_dir_resolves(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
monkeypatch.chdir(CREDIT_DIR)
assert generate.main(["--check", "--dir", "."]) == 0

View File

@ -89,7 +89,8 @@ def test_keyboard_opens_panel_then_url(root, opener, key: str) -> None:
root.update()
assert credit.is_open
assert root.focus_get() is credit.panel
credit.panel.event_generate(key)
credit.panel.event_generate(key.replace("<", "<KeyRelease-", 1), time=100)
credit.panel.event_generate(key, time=400)
root.update()
assert opener.urls == [URL]
@ -145,3 +146,37 @@ def test_escape_when_closed_keeps_focus_where_it_is(root, opener) -> None:
entry.event_generate("<Escape>")
root.update()
assert root.focus_get() is entry
def _key_at(widget: tk.Misc, kind: str, key: str, when: int) -> None:
widget.event_generate(f"<{kind}-{key}>", time=when)
widget.update()
@pytest.mark.parametrize(
"events",
[
[("KeyPress", 1000)], # repeat with no release between
[("KeyRelease", 1000), ("KeyPress", 1000)], # X autorepeat pair
],
)
def test_held_enter_never_opens_the_site(root, opener, events) -> None:
credit = _make(root, opener)
credit.focus_force()
root.update()
_key_at(credit, "KeyPress", "Return", 900)
assert credit.is_open
for kind, when in events:
_key_at(root.focus_get(), kind, "Return", when)
assert opener.urls == []
assert credit.is_open
def test_a_fresh_press_after_release_opens_the_site(root, opener) -> None:
credit = _make(root, opener)
credit.focus_force()
root.update()
_key_at(credit, "KeyPress", "Return", 900)
_key_at(root.focus_get(), "KeyRelease", "Return", 1000)
_key_at(root.focus_get(), "KeyPress", "Return", 1300)
assert opener.urls == [URL]

View File

@ -101,6 +101,11 @@ export class KuhyCredit extends HTMLElement {
this.#panel.querySelector("span").textContent = CREDIT_TEXT;
for (const svg of root.querySelectorAll("svg")) svg.setAttribute("aria-hidden", "true");
this.#logo.addEventListener("click", () => (this.open ? this.close() : this.#show()));
// Holding Enter on the logo opens the panel and focuses it; the key's
// autorepeat must not then activate the link and open the site.
this.#panel.addEventListener("keydown", (event) => {
if (event.repeat && (event.key === "Enter" || event.key === " ")) event.preventDefault();
});
this.#panel.addEventListener("click", (event) => {
event.preventDefault();
this.close();

View File

@ -65,6 +65,22 @@ describe("<kuhy-credit>", () => {
expect(open).not.toHaveBeenCalled();
});
it("ignores a held (repeating) Enter or Space on the panel", () => {
const { logo, panel } = parts();
click(logo);
for (const k of ["Enter", " "]) {
const held = new KeyboardEvent("keydown", { key: k, repeat: true, bubbles: true, cancelable: true });
panel.dispatchEvent(held);
expect(held.defaultPrevented).toBe(true);
}
const fresh = new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true });
panel.dispatchEvent(fresh);
expect(fresh.defaultPrevented).toBe(false);
const heldOther = new KeyboardEvent("keydown", { key: "a", repeat: true, bubbles: true, cancelable: true });
panel.dispatchEvent(heldOther);
expect(heldOther.defaultPrevented).toBe(false);
});
it("ignores other keys and Escape while closed", () => {
const { logo, panel } = parts();
key(document, "Escape");