kuzysign 0.1.0__py3-none-any.whl

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.
kuzysign/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from __future__ import annotations
2
+
3
+ __version__ = "0.1.0"
kuzysign/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ from .cli import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ raise SystemExit(main())
kuzysign/cli.py ADDED
@@ -0,0 +1,502 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import getpass
5
+ import json
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .keys import (
12
+ DEFAULT_KEYS_ROOT,
13
+ generate_profile_key,
14
+ key_exists,
15
+ key_info,
16
+ key_paths,
17
+ known_certificate_paths,
18
+ )
19
+ from .layout import default_keys_root, default_local_profiles_file, default_registry_file, default_settings_file
20
+ from .pdf import sign_pdf, verify_pdf
21
+ from .profiles import (
22
+ DEFAULT_LOCAL_PROFILES_FILE,
23
+ DEFAULT_REGISTRY_FILE,
24
+ Profile,
25
+ load_local_profiles,
26
+ load_profiles,
27
+ profile_from_parts,
28
+ profile_json,
29
+ upsert_local_profile,
30
+ )
31
+ from .settings import ClientSettings, load_client_settings, save_client_settings
32
+ from .version import package_version
33
+
34
+ DEFAULT_SETTINGS_FILE = default_settings_file()
35
+
36
+
37
+ def print_json(payload: object) -> None:
38
+ print(json.dumps(payload, indent=2, sort_keys=True))
39
+
40
+
41
+ def env_flag_enabled(name: str) -> bool:
42
+ value = os.environ.get(name, "").strip().lower()
43
+ return value in {"1", "true", "yes", "on"}
44
+
45
+
46
+ def load_runtime_profiles() -> dict[str, Profile]:
47
+ return load_profiles(DEFAULT_REGISTRY_FILE, DEFAULT_LOCAL_PROFILES_FILE)
48
+
49
+
50
+ def load_runtime_settings() -> ClientSettings:
51
+ return load_client_settings(DEFAULT_SETTINGS_FILE)
52
+
53
+
54
+ def save_runtime_settings(settings: ClientSettings) -> None:
55
+ save_client_settings(DEFAULT_SETTINGS_FILE, settings)
56
+
57
+
58
+ def current_selection_enabled(settings: ClientSettings | None = None) -> bool:
59
+ active_settings = settings or load_runtime_settings()
60
+ return active_settings.current_selection_enabled and not env_flag_enabled("KUZYSIGN_DISABLE_CURRENT_SELECTION")
61
+
62
+
63
+ def strict_current_profile_enabled(settings: ClientSettings | None = None) -> bool:
64
+ active_settings = settings or load_runtime_settings()
65
+ if not current_selection_enabled(active_settings):
66
+ return False
67
+ return active_settings.strict_current_profile or env_flag_enabled("KUZYSIGN_STRICT_CURRENT_PROFILE")
68
+
69
+
70
+ def require_current_selection_enabled(settings: ClientSettings, *, action: str) -> None:
71
+ if current_selection_enabled(settings):
72
+ return
73
+ raise SystemExit(
74
+ f"Current profile selection is disabled; cannot {action}. "
75
+ "Pass --profile explicitly, or run `kuzysign settings current-selection --on`."
76
+ )
77
+
78
+
79
+ def enforce_current_profile(profile_slug: str, settings: ClientSettings | None = None) -> None:
80
+ active_settings = settings or load_runtime_settings()
81
+ if not strict_current_profile_enabled(active_settings):
82
+ return
83
+ if not active_settings.current_profile:
84
+ raise SystemExit(
85
+ "Strict current-profile mode is enabled, but no current profile is selected. "
86
+ "Run `kuzysign profile use --profile <slug>` first."
87
+ )
88
+ if profile_slug != active_settings.current_profile:
89
+ raise SystemExit(
90
+ f"Strict current-profile mode is enabled for '{active_settings.current_profile}'. "
91
+ f"Refusing profile '{profile_slug}'."
92
+ )
93
+
94
+
95
+ def resolve_profile_slug(requested: str | None) -> str:
96
+ slug = str(requested or "").strip().lower()
97
+ if slug:
98
+ return slug
99
+ settings = load_runtime_settings()
100
+ if current_selection_enabled(settings) and settings.current_profile:
101
+ return settings.current_profile
102
+ raise SystemExit("No profile selected. Pass --profile explicitly.")
103
+
104
+
105
+ def profile_from_slug(slug: str) -> Profile:
106
+ normalized_slug = str(slug or "").strip().lower()
107
+ profiles = load_runtime_profiles()
108
+ try:
109
+ return profiles[normalized_slug]
110
+ except KeyError as exc:
111
+ supported = ", ".join(sorted(profiles)) if profiles else "(none configured)"
112
+ raise SystemExit(f"Unknown profile '{slug}'. Supported: {supported}") from exc
113
+
114
+
115
+ def resolve_profile(requested: str | None) -> Profile:
116
+ profile = profile_from_slug(resolve_profile_slug(requested))
117
+ enforce_current_profile(profile.slug)
118
+ return profile
119
+
120
+
121
+ def profile_payload(profile: Profile, settings: ClientSettings | None = None) -> dict[str, Any]:
122
+ active_settings = settings or load_runtime_settings()
123
+ paths = key_paths(profile.slug, DEFAULT_KEYS_ROOT)
124
+ payload: dict[str, Any] = profile_json(profile)
125
+ payload["current"] = current_selection_enabled(active_settings) and profile.slug == active_settings.current_profile
126
+ payload["strict_current_profile"] = strict_current_profile_enabled(active_settings)
127
+ payload["key_exists"] = key_exists(paths)
128
+ return payload
129
+
130
+
131
+ def settings_json(settings: ClientSettings) -> dict[str, object]:
132
+ return {
133
+ "current_selection_enabled": settings.current_selection_enabled,
134
+ "current_selection_effective": current_selection_enabled(settings),
135
+ "current_selection_env_disabled": env_flag_enabled("KUZYSIGN_DISABLE_CURRENT_SELECTION"),
136
+ "current_profile": settings.current_profile,
137
+ "strict_current_profile": settings.strict_current_profile,
138
+ "strict_current_profile_effective": strict_current_profile_enabled(settings),
139
+ "settings_file": str(DEFAULT_SETTINGS_FILE),
140
+ }
141
+
142
+
143
+ def require_cli_option(args: argparse.Namespace, attr: str, option: str) -> str:
144
+ value = getattr(args, attr, None)
145
+ if value is None or str(value).strip() == "":
146
+ raise SystemExit(f"Missing required option: {option}.")
147
+ return str(value)
148
+
149
+
150
+ def add_passphrase_input_args(parser: argparse.ArgumentParser) -> None:
151
+ parser.add_argument("--passphrase", help="Private key passphrase.")
152
+ parser.add_argument("--passphrase-file", help="Read the private key passphrase from this file.")
153
+ parser.add_argument("--passphrase-stdin", action="store_true", help="Read the private key passphrase from standard input.")
154
+ parser.add_argument("--passphrase-prompt", action="store_true", help="Prompt for the private key passphrase without echo.")
155
+
156
+
157
+ def resolve_passphrase_input(args: argparse.Namespace) -> str | None:
158
+ sources = [
159
+ ("--passphrase", getattr(args, "passphrase", None) is not None),
160
+ ("--passphrase-file", bool(getattr(args, "passphrase_file", None))),
161
+ ("--passphrase-stdin", bool(getattr(args, "passphrase_stdin", False))),
162
+ ("--passphrase-prompt", bool(getattr(args, "passphrase_prompt", False))),
163
+ ]
164
+ active = [name for name, enabled in sources if enabled]
165
+ if len(active) > 1:
166
+ raise SystemExit(f"Passphrase input options are mutually exclusive: {', '.join(active)}.")
167
+ if getattr(args, "passphrase", None) is not None:
168
+ return str(args.passphrase)
169
+ if getattr(args, "passphrase_file", None):
170
+ return Path(args.passphrase_file).expanduser().read_text(encoding="utf-8").rstrip("\r\n")
171
+ if getattr(args, "passphrase_stdin", False):
172
+ return sys.stdin.read().rstrip("\r\n")
173
+ if getattr(args, "passphrase_prompt", False):
174
+ return getpass.getpass("Private key passphrase: ")
175
+ return None
176
+
177
+
178
+ def command_settings_show(args: argparse.Namespace) -> int:
179
+ print_json(settings_json(load_runtime_settings()))
180
+ return 0
181
+
182
+
183
+ def command_settings_current_selection(args: argparse.Namespace) -> int:
184
+ settings = load_runtime_settings()
185
+ if args.on:
186
+ updated = ClientSettings(
187
+ current_profile=settings.current_profile,
188
+ strict_current_profile=settings.strict_current_profile,
189
+ current_selection_enabled=True,
190
+ )
191
+ else:
192
+ updated = ClientSettings(current_selection_enabled=False)
193
+ save_runtime_settings(updated)
194
+ print_json({"status": "ok", **settings_json(updated)})
195
+ return 0
196
+
197
+
198
+ def command_profile_list(args: argparse.Namespace) -> int:
199
+ settings = load_runtime_settings()
200
+ local_profiles = load_local_profiles(DEFAULT_LOCAL_PROFILES_FILE)
201
+ payload = []
202
+ for profile in load_runtime_profiles().values():
203
+ item = profile_payload(profile, settings)
204
+ if profile.slug in local_profiles:
205
+ item["source"] = "local"
206
+ else:
207
+ item["source"] = "registry"
208
+ payload.append(item)
209
+ print_json(payload)
210
+ return 0
211
+
212
+
213
+ def command_profile_create(args: argparse.Namespace) -> int:
214
+ profile = profile_from_parts(
215
+ slug=require_cli_option(args, "profile", "--profile"),
216
+ display_name=getattr(args, "display_name", None),
217
+ email=getattr(args, "email", None),
218
+ )
219
+ if profile.slug in load_runtime_profiles():
220
+ raise SystemExit(
221
+ f"Profile '{profile.slug}' already exists. "
222
+ "Use `kuzysign profile modify` to update it locally."
223
+ )
224
+ settings = load_runtime_settings()
225
+ if (
226
+ strict_current_profile_enabled(settings)
227
+ and settings.current_profile
228
+ and settings.current_profile != profile.slug
229
+ ):
230
+ raise SystemExit(
231
+ f"Strict current-profile mode is enabled for '{settings.current_profile}'. "
232
+ f"Refusing profile '{profile.slug}'."
233
+ )
234
+ upsert_local_profile(DEFAULT_LOCAL_PROFILES_FILE, profile)
235
+ current_profile = settings.current_profile
236
+ if args.set_current:
237
+ require_current_selection_enabled(settings, action="set the current profile")
238
+ if current_selection_enabled(settings) and (args.set_current or not current_profile):
239
+ current_profile = profile.slug
240
+ save_runtime_settings(
241
+ ClientSettings(
242
+ current_profile=current_profile,
243
+ strict_current_profile=settings.strict_current_profile,
244
+ current_selection_enabled=settings.current_selection_enabled,
245
+ )
246
+ )
247
+ payload = profile_payload(profile, settings)
248
+ payload["current"] = current_selection_enabled(settings) and profile.slug == current_profile
249
+ payload["profiles_file"] = str(DEFAULT_LOCAL_PROFILES_FILE)
250
+ print_json(payload)
251
+ return 0
252
+
253
+
254
+ def command_profile_modify(args: argparse.Namespace) -> int:
255
+ if getattr(args, "display_name", None) is None and getattr(args, "email", None) is None:
256
+ raise SystemExit("Pass at least one of --display-name or --email.")
257
+ profile = resolve_profile(require_cli_option(args, "profile", "--profile"))
258
+ updated = profile_from_parts(
259
+ slug=profile.slug,
260
+ display_name=args.display_name if getattr(args, "display_name", None) is not None else profile.display_name,
261
+ email=args.email if getattr(args, "email", None) is not None else profile.email,
262
+ )
263
+ upsert_local_profile(DEFAULT_LOCAL_PROFILES_FILE, updated)
264
+ payload = profile_payload(updated)
265
+ payload["profiles_file"] = str(DEFAULT_LOCAL_PROFILES_FILE)
266
+ print_json(payload)
267
+ return 0
268
+
269
+
270
+ def command_profile_show(args: argparse.Namespace) -> int:
271
+ print_json(profile_payload(resolve_profile(getattr(args, "profile", None))))
272
+ return 0
273
+
274
+
275
+ def command_profile_use(args: argparse.Namespace) -> int:
276
+ profile = profile_from_slug(require_cli_option(args, "profile", "--profile"))
277
+ settings = load_runtime_settings()
278
+ require_current_selection_enabled(settings, action="set the current profile")
279
+ if strict_current_profile_enabled(settings) and settings.current_profile and settings.current_profile != profile.slug:
280
+ raise SystemExit(
281
+ f"Strict current-profile mode is enabled for '{settings.current_profile}'. "
282
+ "Disable it before switching profiles."
283
+ )
284
+ updated = ClientSettings(
285
+ current_profile=profile.slug,
286
+ strict_current_profile=settings.strict_current_profile,
287
+ current_selection_enabled=settings.current_selection_enabled,
288
+ )
289
+ save_runtime_settings(updated)
290
+ print_json({"status": "ok", "current_profile": profile.slug})
291
+ return 0
292
+
293
+
294
+ def command_profile_strict(args: argparse.Namespace) -> int:
295
+ settings = load_runtime_settings()
296
+ if args.on:
297
+ require_current_selection_enabled(settings, action="enable strict current-profile mode")
298
+ requested_profile = getattr(args, "profile", None)
299
+ current_profile = settings.current_profile
300
+ if requested_profile:
301
+ profile = profile_from_slug(requested_profile)
302
+ current_profile = profile.slug
303
+ if args.on and not current_profile:
304
+ raise SystemExit("Cannot enable strict current-profile mode before selecting a current profile.")
305
+ updated = ClientSettings(
306
+ current_profile=current_profile,
307
+ strict_current_profile=bool(args.on),
308
+ current_selection_enabled=settings.current_selection_enabled,
309
+ )
310
+ save_runtime_settings(updated)
311
+ print_json({"status": "ok", **settings_json(updated)})
312
+ return 0
313
+
314
+
315
+ def command_key_init(args: argparse.Namespace) -> int:
316
+ profile = resolve_profile(getattr(args, "profile", None))
317
+ paths = key_paths(profile.slug, DEFAULT_KEYS_ROOT)
318
+ metadata = generate_profile_key(
319
+ profile,
320
+ paths,
321
+ replace=bool(args.replace),
322
+ passphrase=resolve_passphrase_input(args),
323
+ days=int(args.days),
324
+ )
325
+ print_json({"status": "created", **metadata})
326
+ return 0
327
+
328
+
329
+ def command_key_show(args: argparse.Namespace) -> int:
330
+ profile = resolve_profile(getattr(args, "profile", None))
331
+ print_json(key_info(key_paths(profile.slug, DEFAULT_KEYS_ROOT)))
332
+ return 0
333
+
334
+
335
+ def command_key_export_public(args: argparse.Namespace) -> int:
336
+ profile = resolve_profile(getattr(args, "profile", None))
337
+ paths = key_paths(profile.slug, DEFAULT_KEYS_ROOT)
338
+ if not paths.certificate.is_file():
339
+ raise SystemExit(f"No certificate for profile '{profile.slug}'. Run `kuzysign key init` first.")
340
+ if args.out:
341
+ target = Path(args.out).expanduser()
342
+ target.parent.mkdir(parents=True, exist_ok=True)
343
+ target.write_bytes(paths.certificate.read_bytes())
344
+ os.chmod(target, 0o644)
345
+ print_json({"status": "exported", "profile": profile.slug, "certificate": str(target)})
346
+ else:
347
+ sys.stdout.write(paths.certificate.read_text(encoding="utf-8"))
348
+ return 0
349
+
350
+
351
+ def command_paths(args: argparse.Namespace) -> int:
352
+ profile = resolve_profile(getattr(args, "profile", None))
353
+ paths = key_paths(profile.slug, DEFAULT_KEYS_ROOT)
354
+ print_json(
355
+ {
356
+ "profile": profile.slug,
357
+ "registry_file": str(DEFAULT_REGISTRY_FILE),
358
+ "profiles_file": str(DEFAULT_LOCAL_PROFILES_FILE),
359
+ "settings_file": str(DEFAULT_SETTINGS_FILE),
360
+ "keys_root": str(DEFAULT_KEYS_ROOT),
361
+ "profile_dir": str(paths.profile_dir),
362
+ "private_key": str(paths.private_key),
363
+ "certificate": str(paths.certificate),
364
+ "metadata": str(paths.metadata),
365
+ }
366
+ )
367
+ return 0
368
+
369
+
370
+ def command_sign(args: argparse.Namespace) -> int:
371
+ profile = resolve_profile(getattr(args, "profile", None))
372
+ paths = key_paths(profile.slug, DEFAULT_KEYS_ROOT)
373
+ result = sign_pdf(
374
+ Path(args.pdf),
375
+ Path(args.out) if args.out else None,
376
+ profile=profile,
377
+ key_paths=paths,
378
+ reason=args.reason,
379
+ location=args.location,
380
+ field_name=args.field,
381
+ passphrase=resolve_passphrase_input(args),
382
+ )
383
+ print_json(result)
384
+ return 0
385
+
386
+
387
+ def command_verify(args: argparse.Namespace) -> int:
388
+ trust_certs = (
389
+ [Path(path).expanduser() for path in args.trust_cert]
390
+ if args.trust_cert
391
+ else known_certificate_paths(DEFAULT_KEYS_ROOT)
392
+ )
393
+ print_json(verify_pdf(Path(args.pdf), trust_certs=trust_certs))
394
+ return 0
395
+
396
+
397
+ def build_parser() -> argparse.ArgumentParser:
398
+ parser = argparse.ArgumentParser(
399
+ prog="kuzysign",
400
+ description="Local PDF signature rail for Kuzys agent acceptance.",
401
+ )
402
+ parser.add_argument("--version", action="version", version=f"%(prog)s {package_version()}")
403
+ parser.add_argument("--profile", default=argparse.SUPPRESS, help="Signing profile.")
404
+ subparsers = parser.add_subparsers(dest="command", required=True)
405
+
406
+ def add_profile_arg(cmd: argparse.ArgumentParser) -> None:
407
+ cmd.add_argument("--profile", default=argparse.SUPPRESS, help="Signing profile.")
408
+
409
+ settings_cmd = subparsers.add_parser("settings", help="Inspect or update kuzysign client settings.")
410
+ settings_sub = settings_cmd.add_subparsers(dest="settings_command", required=True)
411
+
412
+ settings_show = settings_sub.add_parser("show", help="Show current client settings.")
413
+ settings_show.set_defaults(func=command_settings_show)
414
+
415
+ settings_current = settings_sub.add_parser("current-selection", help="Enable or disable current profile fallback.")
416
+ settings_current_group = settings_current.add_mutually_exclusive_group(required=True)
417
+ settings_current_group.add_argument("--on", action="store_true", help="Enable current profile fallback.")
418
+ settings_current_group.add_argument("--off", action="store_true", help="Disable current profile fallback.")
419
+ settings_current.set_defaults(func=command_settings_current_selection)
420
+
421
+ profile_cmd = subparsers.add_parser("profile", help="Inspect or select signing profiles.")
422
+ profile_sub = profile_cmd.add_subparsers(dest="profile_command", required=True)
423
+
424
+ profile_list = profile_sub.add_parser("list", help="List known signing profiles.")
425
+ profile_list.set_defaults(func=command_profile_list)
426
+
427
+ profile_create = profile_sub.add_parser("create", help="Create a local signing profile.")
428
+ profile_create.add_argument("--profile", default=argparse.SUPPRESS)
429
+ profile_create.add_argument("--display-name", required=True)
430
+ profile_create.add_argument("--email", help="Optional profile email address.")
431
+ profile_create.add_argument("--set-current", action="store_true", help="Also make this the current profile.")
432
+ profile_create.set_defaults(func=command_profile_create)
433
+
434
+ profile_modify = profile_sub.add_parser("modify", help="Modify or override a signing profile locally.")
435
+ profile_modify.add_argument("--profile", default=argparse.SUPPRESS)
436
+ profile_modify.add_argument("--display-name")
437
+ profile_modify.add_argument("--email")
438
+ profile_modify.set_defaults(func=command_profile_modify)
439
+
440
+ profile_show = profile_sub.add_parser("show", help="Show one profile or the current profile.")
441
+ profile_show.add_argument("--profile", default=argparse.SUPPRESS)
442
+ profile_show.set_defaults(func=command_profile_show)
443
+
444
+ profile_use = profile_sub.add_parser("use", help="Set the current signing profile.")
445
+ profile_use.add_argument("--profile", default=argparse.SUPPRESS)
446
+ profile_use.set_defaults(func=command_profile_use)
447
+
448
+ profile_strict = profile_sub.add_parser("strict", help="Enable or disable strict current-profile mode.")
449
+ profile_strict.add_argument("--profile", default=argparse.SUPPRESS, help="Set this profile as current before applying the mode.")
450
+ strict_group = profile_strict.add_mutually_exclusive_group(required=True)
451
+ strict_group.add_argument("--on", action="store_true", help="Enable strict current-profile mode.")
452
+ strict_group.add_argument("--off", action="store_true", help="Disable strict current-profile mode.")
453
+ profile_strict.set_defaults(func=command_profile_strict)
454
+
455
+ key_cmd = subparsers.add_parser("key", help="Manage local profile signing keys.")
456
+ key_sub = key_cmd.add_subparsers(dest="key_command", required=True)
457
+
458
+ key_init = key_sub.add_parser("init", help="Create or rotate a profile signing key.")
459
+ add_profile_arg(key_init)
460
+ key_init.add_argument("--replace", action="store_true", help="Replace an existing key.")
461
+ key_init.add_argument("--days", type=int, default=3650, help="Certificate validity in days.")
462
+ add_passphrase_input_args(key_init)
463
+ key_init.set_defaults(func=command_key_init)
464
+
465
+ key_show = key_sub.add_parser("show", help="Show key metadata for a profile.")
466
+ add_profile_arg(key_show)
467
+ key_show.set_defaults(func=command_key_show)
468
+
469
+ key_export_public = key_sub.add_parser("export-public", help="Print or write the profile public certificate.")
470
+ add_profile_arg(key_export_public)
471
+ key_export_public.add_argument("--out", help="Write the certificate to this path instead of stdout.")
472
+ key_export_public.set_defaults(func=command_key_export_public)
473
+
474
+ paths = subparsers.add_parser("paths", help="Show profile-related filesystem paths.")
475
+ add_profile_arg(paths)
476
+ paths.set_defaults(func=command_paths)
477
+
478
+ sign = subparsers.add_parser("sign", help="Sign a PDF with a local Kuzys profile key.")
479
+ add_profile_arg(sign)
480
+ sign.add_argument("pdf", help="Input PDF path.")
481
+ sign.add_argument("--out", help="Output PDF path. Defaults to *.signed-by-<profile>.pdf.")
482
+ sign.add_argument("--reason", default="Kuzys local acceptance signature (not QES)")
483
+ sign.add_argument("--location", default="Raven/Kuzys local signing")
484
+ sign.add_argument("--field", help="PDF signature field name. Defaults to a generated Kuzysign field.")
485
+ add_passphrase_input_args(sign)
486
+ sign.set_defaults(func=command_sign)
487
+
488
+ verify = subparsers.add_parser("verify", help="Verify embedded PDF signatures against local profile certificates.")
489
+ verify.add_argument("pdf", help="Signed PDF path.")
490
+ verify.add_argument("--trust-cert", action="append", default=[], help="Additional trusted certificate path.")
491
+ verify.set_defaults(func=command_verify)
492
+
493
+ return parser
494
+
495
+
496
+ def main(argv: list[str] | None = None) -> int:
497
+ parser = build_parser()
498
+ args = parser.parse_args(argv)
499
+ try:
500
+ return int(args.func(args))
501
+ except (FileExistsError, FileNotFoundError, ValueError) as exc:
502
+ raise SystemExit(str(exc)) from exc