Skip to content

Commit 907b9d0

Browse files
lseongjooclaude
andcommitted
Keep manual fixtures out of the user's data with a fixture-only home (#31)
NSHomeDirectory() ignores HOME, so fixtures that set HOME still reached the user's Application Support (drafts.sqlite, agent-approvals.json), and helpers built without TTS_AGENT_FIXTURE_KEYS wrote the user's agent-client-keys. - -D TTS_FIXTURE_HOME: only fixture builds take their home from TTS_TEST_HOME, keep sockets relative to the fixture root, use the fixture identity com.codebasic.tts.fixture.receiver, keep helper keys under that home and register no system integration. The product reads no path from the environment. - Tests/Fixtures/fixture_support.py: shared flags, environment and one sign() that refuses product identifiers; ad hoc unless a certificate leaf is pinned. - Fixtures build with the flag instead of patching TTSRuntime.swift, and add Logging.swift where the server needs it. Agent: Claude Code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f4e2554 commit 907b9d0

11 files changed

Lines changed: 184 additions & 118 deletions

‎Helpers/AgentCatalogMCP.swift‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,9 @@ struct ClientKey {
695695
#if TTS_AGENT_FIXTURE_KEYS
696696
// Integration fixtures use their own synthetic key directory.
697697
return ProcessInfo.processInfo.environment["TTS_AGENT_FIXTURE_KEY_DIR"].map { URL(fileURLWithPath: $0, isDirectory: true) }
698+
#elseif TTS_FIXTURE_HOME
699+
// Fixture builds keep keys under the fixture's home, never the user's.
700+
return TTSRuntime.applicationSupport().appendingPathComponent("agent-client-keys", isDirectory: true)
698701
#else
699702
guard let entry = getpwuid(getuid()), let home = entry.pointee.pw_dir else { return nil }
700703
return TTSRuntime.applicationSupport(home: URL(fileURLWithPath: String(cString: home), isDirectory: true))

‎Sources/Core/TTSRuntime.swift‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,12 @@ import Foundation
33

44
/// Compiled into both ends of the local MCP connection.
55
enum TTSRuntime {
6+
#if TTS_FIXTURE_HOME
7+
// Integration fixtures only: never the installed app's identity.
8+
static let productionAppID = "com.codebasic.tts.fixture.receiver"
9+
#else
610
static let productionAppID = "com.seongjoo.SelectedTextTTS"
11+
#endif
712
// Three builds, each with its own identity, data folder and sockets:
813
// product — the installed app.
914
// preview — agent workspace only; synthesis, accounts and system hooks are off.
@@ -30,9 +35,23 @@ enum TTSRuntime {
3035
#endif
3136
static let helperID = appID + ".agent-helper"
3237
/// Services and global hotkeys are per-user singletons, so only the product claims them.
38+
#if TTS_FIXTURE_HOME
39+
static let registersSystemIntegration = false
40+
#else
3341
static let registersSystemIntegration = !isPreview && !isReview
42+
#endif
43+
44+
#if TTS_FIXTURE_HOME
45+
/// Fixture builds keep every per-user file under the fixture's own home.
46+
/// `NSHomeDirectory()` ignores `HOME`, so the fixture passes it explicitly.
47+
/// Only fixture builds read this variable; the product never reads a path
48+
/// from the environment.
49+
static let home = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TTS_TEST_HOME"]!, isDirectory: true)
50+
#else
51+
static let home = URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
52+
#endif
3453

35-
static func applicationSupport(home: URL = URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) -> URL {
54+
static func applicationSupport(home: URL = TTSRuntime.home) -> URL {
3655
home.appendingPathComponent("Library/Application Support", isDirectory: true)
3756
.appendingPathComponent(displayName, isDirectory: true)
3857
}
@@ -41,6 +60,12 @@ enum TTSRuntime {
4160

4261
static func socketDirectory(uid: uid_t) -> String {
4362
let prefix = isPreview ? "codebasic-tts-preview-mcp" : isReview ? "codebasic-tts-review-mcp" : "codebasic-tts-mcp"
63+
#if TTS_FIXTURE_HOME
64+
// Relative to the fixture's working directory: inside its root, and short
65+
// enough for sockaddr_un in a deeply nested checkout.
66+
return "\(prefix)-\(uid)"
67+
#else
4468
return "/private/tmp/\(prefix)-\(uid)"
69+
#endif
4570
}
4671
}

‎Tests/Fixtures/fixture_support.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""Shared build, environment and signing for the manual integration fixtures.
2+
3+
Every fixture compiles its app/server and helper with `-D TTS_FIXTURE_HOME`.
4+
That build takes its home from `TTS_TEST_HOME` (the product never reads a path
5+
from the environment) and keeps sockets relative to the fixture root, so nothing
6+
reaches the user's Application Support, agent keys or the installed app's
7+
/private/tmp socket directory. Fixture builds also carry a fixture identity, never
8+
the product bundle ID.
9+
"""
10+
11+
import os
12+
from pathlib import Path
13+
import subprocess
14+
15+
HERE = Path(__file__).resolve().parent
16+
REPO = HERE.parents[1]
17+
SOURCES = REPO / "Sources"
18+
BUILD = Path(os.environ.get("TTS_BUILD_DIR", REPO / "build")).resolve()
19+
20+
# Must match TTSRuntime.productionAppID under TTS_FIXTURE_HOME.
21+
APP_ID = "com.codebasic.tts.fixture.receiver"
22+
HELPER_ID = APP_ID + ".agent-helper"
23+
PREVIEW_APP_ID = APP_ID + ".preview"
24+
FLAGS = ["-D", "TTS_FIXTURE_HOME"]
25+
26+
# A certificate signature is needed only where the code under test pins a
27+
# certificate leaf (agent peer checks, registered agent hosts, the instruction
28+
# adapter's signer pin). Ad-hoc signing cannot produce a leaf. Everything else
29+
# is signed ad hoc. Override with CODESIGN_IDENTITY.
30+
CERT_IDENTITY = os.environ.get("CODESIGN_IDENTITY", "Codebasic TTS Local")
31+
32+
33+
def sdk():
34+
return subprocess.check_output(["/usr/bin/xcrun", "--sdk", "macosx26.5", "--show-sdk-path"], text=True).strip()
35+
36+
37+
def home(root):
38+
"""The fixture's own home; created on first use."""
39+
path = Path(root) / "home"
40+
path.mkdir(mode=0o700, exist_ok=True)
41+
return path
42+
43+
44+
def env(root, **extra):
45+
"""Environment for fixture processes: home and temp stay under `root`."""
46+
fixture_home = home(root)
47+
return {"PATH": "/usr/bin:/bin", "HOME": str(fixture_home), "TTS_TEST_HOME": str(fixture_home),
48+
"TMPDIR": str(root), **extra}
49+
50+
51+
def compile_env(root, cache):
52+
return {**env(root), "SDKROOT": sdk(), "CLANG_MODULE_CACHE_PATH": str(cache)}
53+
54+
55+
def sign(path, identifier, certificate=False, runtime=True, entitlements=None):
56+
"""Sign `path` with a fixture identifier: ad hoc, or with CERT_IDENTITY."""
57+
assert not identifier.startswith("com.seongjoo.SelectedTextTTS"), identifier
58+
arguments = ["/usr/bin/codesign", "--force", "--timestamp=none"]
59+
if runtime:
60+
arguments += ["--options", "runtime"]
61+
arguments += ["--sign", CERT_IDENTITY if certificate else "-", "--identifier", identifier]
62+
if entitlements:
63+
arguments += ["--entitlements", str(entitlements)]
64+
subprocess.run([*arguments, str(path)], check=True, timeout=60, stderr=subprocess.DEVNULL)
65+
subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(path)], check=True, timeout=30)

‎Tests/Fixtures/run_agent_app_connections.py‎

Lines changed: 17 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -20,43 +20,25 @@
2020
import tempfile
2121
import time
2222

23-
from run_persistent_pairing import BUILD, HERE, IDENTITY, REPO, SOURCES, Server, Session
24-
25-
26-
APP_ID = "com.codebasic.tts.fixture.receiver"
23+
from run_persistent_pairing import BUILD, HERE, REPO, SOURCES, Server, Session
24+
import fixture_support as fs
25+
from fixture_support import APP_ID
2726

2827

2928
def run(*arguments, env=None):
3029
subprocess.run(arguments, env=env, check=True, timeout=300)
3130

3231

33-
def sign(path, identifier, identity=IDENTITY):
34-
run("/usr/bin/codesign", "--force", "--options", "runtime", "--timestamp=none", "--sign", identity,
35-
"--identifier", identifier, path)
36-
run("/usr/bin/codesign", "--verify", "--strict", path)
32+
def sign(path, identifier, certificate=True):
33+
# Peer checks and registered hosts pin a certificate leaf; the rest stays ad hoc.
34+
fs.sign(path, identifier, certificate=certificate)
3735

3836

3937
def build(root):
40-
# Recompile only the test fixture with a socket location relative to its cwd.
41-
# The relative path also stays below macOS's sockaddr_un path limit.
42-
runtime = root / "TTSRuntime.swift"
43-
original = (SOURCES / "Core/TTSRuntime.swift").read_text()
44-
location = r'"/private/tmp/\(prefix)-\(uid)"'
45-
assert original.count(location) == 1
46-
product_id = '"com.seongjoo.SelectedTextTTS"'
47-
assert original.count(product_id) == 1
48-
runtime.write_text(original.replace(location, r'"\(prefix)"').replace(product_id, f'"{APP_ID}"'))
49-
sdk = subprocess.check_output(
50-
["/usr/bin/xcrun", "--sdk", "macosx26.5", "--show-sdk-path"], text=True
51-
).strip()
52-
env = {
53-
"PATH": "/usr/bin:/bin",
54-
"HOME": str(root),
55-
"TMPDIR": str(root),
56-
"SDKROOT": sdk,
57-
"CLANG_MODULE_CACHE_PATH": str(BUILD / "module-cache"),
58-
}
59-
common = [runtime, SOURCES / "App/AgentPeerSigning.swift", SOURCES / "Core/AgentCatalog.swift"]
38+
# `-D TTS_FIXTURE_HOME` gives the fixture identity, a home under the root and
39+
# sockets relative to its cwd (also below macOS's sockaddr_un path limit).
40+
env = fs.compile_env(root, BUILD / "module-cache")
41+
common = [SOURCES / "Core/TTSRuntime.swift", SOURCES / "App/AgentPeerSigning.swift", SOURCES / "Core/AgentCatalog.swift"]
6042
receiver = [
6143
SOURCES / "App/LocalInstructionSocket.swift",
6244
SOURCES / "App/AgentSessionController.swift",
@@ -76,7 +58,7 @@ def build(root):
7658
different_source.write_text(helper_text.replace(version, '"version":"2.0-fixture-other"'))
7759

7860
def swift(output, files, *flags):
79-
run("/usr/bin/swiftc", "-framework", "Security", *flags, *common, *files, "-o", root / output, env=env)
61+
run("/usr/bin/swiftc", *fs.FLAGS, "-framework", "Security", *flags, *common, *files, "-o", root / output, env=env)
8062

8163
swift("server", receiver, "-lsqlite3")
8264
sign(root / "server", APP_ID)
@@ -87,7 +69,7 @@ def swift(output, files, *flags):
8769
swift("other-helper", [different_source], "-D", "TTS_AGENT_FIXTURE_KEYS")
8870
sign(root / "other-helper", helper_id)
8971
shutil.copy2(helper, root / "adhoc-helper")
90-
sign(root / "adhoc-helper", helper_id, "-")
72+
sign(root / "adhoc-helper", helper_id, certificate=False)
9173

9274
return build_hosts(root, env)
9375

@@ -113,7 +95,7 @@ def build_hosts(root, env):
11395
plistlib.dump(info, plist)
11496
# A certificate-signed app is identified by its signature; an ad-hoc signed
11597
# one cannot be told apart from other apps, so its approval lasts one run.
116-
sign(bundle, identifier, IDENTITY if registered else "-")
98+
sign(bundle, identifier, certificate=registered)
11799
hosts[name] = binary
118100
return hosts
119101

@@ -151,14 +133,14 @@ def verify(root, hosts):
151133
trust = root / "agent-clients.json"
152134
keys = root / "test-keys"
153135
keys.mkdir(mode=0o700)
154-
env = {"PATH": "/usr/bin:/bin", "HOME": str(root), "TMPDIR": str(root)}
136+
env = fs.env(root)
155137
same_name = "same-agent-name"
156138
sample_a = {"display": "A의 표시 원고\n문장 둘 e\u0301", "speech": "가의 발음용 원고", "title": "A 제목"}
157139
sample_b = {"display": "B의 표시 원고\n문장 둘 🎧", "speech": "나의 발음용 원고", "title": "B 제목"}
158140

159141
with ExitStack() as resources:
160142
def app():
161-
server = Server(root, env, "codebasic-tts-mcp", trust, database=database)
143+
server = Server(root, env, "codebasic-tts-mcp-" + str(os.getuid()), trust, database=database)
162144
resources.callback(server.end)
163145
assert server("pair") == "ok" and server("configure") == "ok"
164146
return server
@@ -355,11 +337,11 @@ def verify_auto_connect(root, hosts):
355337
trust = root / "auto-agent-clients.json"
356338
keys = root / "auto-keys"
357339
keys.mkdir(mode=0o700)
358-
env = {"PATH": "/usr/bin:/bin", "HOME": str(root), "TMPDIR": str(root)}
340+
env = fs.env(root)
359341

360342
with ExitStack() as resources:
361343
def app(trust_file=trust):
362-
server = Server(root, env, "codebasic-tts-mcp", trust_file, database=database)
344+
server = Server(root, env, "codebasic-tts-mcp-" + str(os.getuid()), trust_file, database=database)
363345
resources.callback(server.end)
364346
assert server("pair") == "ok" and server("configure") == "ok"
365347
return server

‎Tests/Fixtures/run_draft_titles.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#!/usr/bin/env python3
22
"""Draft titles, the submission guide and the stored draft list, end to end: the real
33
signed helper, the app's real session controller and its SQLite draft store, synthetic
4-
Korean drafts only. Built and run under build/; client keys use one-off keychain slots
5-
that are deleted at the end. Nothing is synthesized or played and no provider is called.
4+
Korean drafts only. Built and run under a temporary root in build/, client keys
5+
included (`-D TTS_FIXTURE_HOME`). Nothing is synthesized or played and no provider is called.
66
"""
77
import json
88
import os
@@ -14,6 +14,7 @@
1414

1515
HERE = Path(__file__).resolve().parent
1616
sys.path.insert(0, str(HERE))
17+
import fixture_support as fs # noqa: E402
1718
from run_persistent_pairing import BUILD, Server, Session, build, digest, ok, passed # noqa: E402
1819

1920
FAMILY = "👨‍👩‍👧‍👦"
@@ -26,8 +27,8 @@ def main():
2627
root = Path(temp)
2728
build(root)
2829
ipc = "codebasic-tts-mcp-" + str(os.getuid())
29-
server_env = {"PATH": "/usr/bin:/bin", "HOME": str(root), "TMPDIR": str(root)}
30-
client_env = {"PATH": "/usr/bin:/bin", "HOME": os.environ["HOME"]}
30+
server_env = fs.env(root)
31+
client_env = fs.env(root)
3132
helper = str(root / "helper")
3233

3334
def app():

‎Tests/Fixtures/run_local_draft_candidate.py‎

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
#!/usr/bin/env python3
2-
"""Native signed CLI + app-side gate, offscreen/synthetic; all files in build/."""
2+
"""Native signed CLI + app-side gate, offscreen/synthetic; all files in build/.
3+
4+
Built with `-D TTS_FIXTURE_HOME` (fixture identity, home and sockets under the root).
5+
"""
36
import argparse
47
import json
58
import os
@@ -9,14 +12,15 @@
912
import socket
1013
import shutil
1114
import subprocess
15+
import sys
1216
import tempfile
1317
import time
1418

1519
HERE = Path(__file__).resolve().parent
1620
REPO = HERE.parents[1]
17-
BUILD = Path(os.environ.get("TTS_BUILD_DIR", REPO / "build")).resolve()
18-
SOURCES = REPO / "Sources"
19-
APP_ID = "com.seongjoo.SelectedTextTTS"
21+
sys.path.insert(0, str(HERE))
22+
import fixture_support as fs # noqa: E402
23+
from fixture_support import APP_ID, BUILD, SOURCES # noqa: E402
2024
FIXTURE_SELECTOR = "66666666-6666-4666-8666-666666666666"
2125

2226

@@ -83,17 +87,11 @@ def main(preview):
8387
with tempfile.TemporaryDirectory(prefix="v", dir=BUILD) as temp:
8488
root = Path(temp)
8589
helper_src = REPO / "Helpers/AgentCatalogMCP.swift"
86-
runtime = root / "TTSRuntime.swift"
87-
original = (SOURCES / "Core/TTSRuntime.swift").read_text()
88-
path = r'"/private/tmp/\(prefix)-\(uid)"'
89-
assert original.count(path) == 1
90-
runtime.write_text(original.replace(path, r'"\(prefix)-\(uid)"'))
91-
sdk = subprocess.check_output(["/usr/bin/xcrun","--sdk","macosx26.5","--show-sdk-path"], text=True).strip()
92-
env = {"PATH":"/usr/bin:/bin", "HOME":str(root), "TMPDIR":str(root)}
93-
compile_env = {**env, "SDKROOT":sdk, "CLANG_MODULE_CACHE_PATH":str(BUILD/"module-cache")}
94-
common = [runtime, SOURCES/"App/AgentPeerSigning.swift", SOURCES/"Core/AgentCatalog.swift"]
90+
env = fs.env(root)
91+
compile_env = fs.compile_env(root, BUILD / "module-cache")
92+
common = [SOURCES/"Core/TTSRuntime.swift", SOURCES/"App/AgentPeerSigning.swift", SOURCES/"Core/AgentCatalog.swift"]
9593
server_src = [SOURCES/"App/LocalInstructionSocket.swift", SOURCES/"App/AgentSessionController.swift",
96-
SOURCES/"Core/AgentTrustStore.swift",
94+
SOURCES/"Core/Logging.swift", SOURCES/"Core/AgentTrustStore.swift",
9795
SOURCES/"Core/AgentDeliveryProofs.swift", SOURCES/"Core/ExplanationDraftWorkspace.swift", SOURCES/"Core/DraftStore.swift",
9896
SOURCES/"Core/AgentInstructionEditing.swift",
9997
HERE / "LocalExplanationDraftSocketProbe.swift"]
@@ -102,13 +100,13 @@ def main(preview):
102100

103101
def compile_signed(name, identifier, files, preview_build):
104102
binary = root / name
105-
flags = ["-D", "TTS_LOCAL_PREVIEW"] if preview_build else []
103+
flags = [*fs.FLAGS, *(["-D", "TTS_LOCAL_PREVIEW"] if preview_build else [])]
104+
if binary.name.endswith("server"):
105+
flags.append("-lsqlite3")
106106
subprocess.run(["/usr/bin/swiftc",*flags,"-framework","Security",*map(str,common+files),"-o",str(binary)],
107-
check=True, timeout=120, env=compile_env)
108-
subprocess.run(["/usr/bin/codesign","--force","--options","runtime","--timestamp=none",
109-
"--sign",os.environ.get("CODESIGN_IDENTITY","Codebasic TTS Local"),
110-
"--identifier",identifier,str(binary)], check=True, timeout=15)
111-
subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(binary)], check=True, timeout=15)
107+
check=True, timeout=300, env=compile_env)
108+
# The peer check pins a certificate leaf, so these need a certificate.
109+
fs.sign(binary, identifier, certificate=True)
112110

113111
for name, identifier, files in (("helper",app_id+".agent-helper",[helper_src]),
114112
("server",app_id,server_src),
@@ -119,20 +117,15 @@ def compile_signed(name, identifier, files, preview_build):
119117
compile_signed("product-server", APP_ID, server_src, False)
120118
compile_signed("wrong-id", APP_ID+".agent-helper", [helper_src], True)
121119
shutil.copy2(root / "server", root / "unhardened")
122-
subprocess.run(["/usr/bin/codesign","--force","--timestamp=none",
123-
"--sign",os.environ.get("CODESIGN_IDENTITY","Codebasic TTS Local"),
124-
"--identifier",app_id,str(root / "unhardened")], check=True, timeout=15)
120+
fs.sign(root / "unhardened", app_id, certificate=True, runtime=False)
125121
# Known zero-capability value; explicitly does not enable a network client.
126122
marker = {"com.apple.security.network.client": False}
127123
entitlements = root / "TestEntitlements.plist"
128124
entitlements.write_bytes(plistlib.dumps(marker))
129125
for base, identifier in (("helper", app_id+".agent-helper"), ("server", app_id)):
130126
entitled = root / ("entitled-" + base)
131127
shutil.copy2(root / base, entitled)
132-
subprocess.run(["/usr/bin/codesign","--force","--timestamp=none","--options","runtime",
133-
"--sign",os.environ.get("CODESIGN_IDENTITY","Codebasic TTS Local"),
134-
"--identifier",identifier,"--entitlements",str(entitlements),str(entitled)], check=True, timeout=15)
135-
subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(entitled)], check=True, timeout=15)
128+
fs.sign(entitled, identifier, certificate=True, entitlements=entitlements)
136129
embedded = subprocess.check_output(["/usr/bin/codesign","--display","--xml","--entitlements","-",str(entitled)],
137130
stderr=subprocess.DEVNULL, timeout=12)
138131
assert plistlib.loads(embedded) == marker

0 commit comments

Comments
 (0)