ferrum-migration 1.0.1__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.
@@ -0,0 +1,23 @@
1
+ """ferrum-migration: offline, best-effort, fail-closed migration into Ferrum Edge config.
2
+
3
+ The tool reads one local configuration file (or export) from another gateway,
4
+ proxy or mesh and writes Ferrum Edge file-mode resources, a ``ferrum.conf``
5
+ profile and a migration report. It never performs network I/O, never follows
6
+ includes outside the given input and never starts or deploys anything.
7
+ """
8
+
9
+ #: The package version, and its only source: pyproject.toml reads it as a dynamic
10
+ #: version, ``ferrum-migrate --version`` prints it, and reports record it as
11
+ #: ``tool_version``. A plain ``X.Y.Z`` literal; the release workflow requires the
12
+ #: pushed ``vX.Y.Z`` tag to equal it.
13
+ __version__ = "1.0.1"
14
+
15
+ #: Ferrum Edge commit whose config structs, plugin validators and settings
16
+ #: inventory the mappings were verified against.
17
+ FERRUM_EDGE_REFERENCE_COMMIT = "a2974b9f1594de32fec3722612f899946486a8ab"
18
+
19
+ #: Schema version of ``migration-report.json`` (and ``ferrum-migrate check --json``).
20
+ #: Additive changes stay within schema version ``"1"``; breaking layout changes bump it.
21
+ REPORT_SCHEMA_VERSION = "1"
22
+
23
+ __all__ = ["__version__", "FERRUM_EDGE_REFERENCE_COMMIT", "REPORT_SCHEMA_VERSION"]
@@ -0,0 +1,8 @@
1
+ """Allow ``python -m ferrum_migration``."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__": # pragma: no cover - exercised through the CLI tests
8
+ sys.exit(main())
@@ -0,0 +1,284 @@
1
+ """Command-line interface: ``ferrum-migrate`` / ``python -m ferrum_migration``.
2
+
3
+ Exit codes:
4
+
5
+ * 0 - migrated; no error-level caveats (warnings allowed unless ``--strict``)
6
+ * 1 - internal error (no output written)
7
+ * 2 - usage error
8
+ * 3 - input rejected (syntax, limits, unsupported shape; no output written)
9
+ * 4 - output written, but it contains items that require review (error-level
10
+ caveats: refused or fail-closed routes, unmigrated credentials...), or
11
+ warnings with ``--strict``
12
+ * 5 - output could not be written safely
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+ import sys
21
+ from typing import Sequence
22
+
23
+ import yaml
24
+
25
+ from . import FERRUM_EDGE_REFERENCE_COMMIT, __version__
26
+ from .envprofile import RUN_MODES, next_steps, render
27
+ from .errors import InputError, OutputError
28
+ from .ferrum import EmitOptions, emit
29
+ from .limits import ABSOLUTE_MAX_INPUT_BYTES, Limits
30
+ from .report import Report
31
+ from .safe_load import read_input
32
+ from .sources import DESCRIPTIONS, SOURCES
33
+ from .sources.common import SourceContext
34
+ from .sources.traefik import CONTROLS_ASSERTION_FLAG
35
+ from .writer import write_output_files
36
+
37
+ EXIT_OK = 0
38
+ EXIT_INTERNAL = 1
39
+ EXIT_USAGE = 2
40
+ EXIT_INPUT = 3
41
+ EXIT_REVIEW = 4
42
+ EXIT_OUTPUT = 5
43
+
44
+ RESOURCES_YAML = "resources.yaml"
45
+ RESOURCES_JSON = "resources.json"
46
+
47
+
48
+ def build_parser() -> argparse.ArgumentParser:
49
+ parser = argparse.ArgumentParser(
50
+ prog="ferrum-migrate",
51
+ description="Offline, best-effort, fail-closed migration of gateway/proxy/mesh configuration into "
52
+ "Ferrum Edge file-mode resources, a ferrum.conf profile and a migration report.",
53
+ )
54
+ parser.add_argument("--version", action="version",
55
+ version=f"ferrum-migration {__version__} (Ferrum Edge reference {FERRUM_EDGE_REFERENCE_COMMIT[:12]})")
56
+ sub = parser.add_subparsers(dest="command", required=True)
57
+ for name, help_text in (("convert", "translate a config and write output files"),
58
+ ("check", "translate a config and print the report without writing files")):
59
+ command = sub.add_parser(name, help=help_text)
60
+ command.add_argument("input", help="path to one source config file, or '-' for stdin")
61
+ command.add_argument("--from", dest="platform", required=True, choices=sorted(SOURCES),
62
+ help="source platform")
63
+ command.add_argument("--input-format", choices=("auto", "yaml", "json", "toml", "nginx"), default="auto")
64
+ command.add_argument("--run-mode", choices=RUN_MODES, default="file",
65
+ help="Ferrum operating mode the ferrum.conf profile targets (default: file)")
66
+ command.add_argument("--tls-only", action="store_true",
67
+ help="disable Ferrum's plaintext listener so HTTPS-only source routes can be migrated")
68
+ command.add_argument(K8S_SD_FLAG, dest="kubernetes_service_discovery", action="store_true",
69
+ help="Istio only. Resolve destinations that are in-cluster Kubernetes Services through "
70
+ "Ferrum's Kubernetes service discovery (EndpointSlices, one target per ready pod, "
71
+ "as Istio's gateway does) instead of the Service DNS name. Needs the Service "
72
+ "objects in the input to select the port, and Ferrum running in the cluster with "
73
+ "permission to list EndpointSlices.")
74
+ command.add_argument(CONTROLS_ASSERTION_FLAG, dest="traefik_controls_asserted", action="store_true",
75
+ help="Traefik only. Your scoped statement, made after verifying the Traefik deployment, "
76
+ "that the input includes every effective routing, TLS and access control that "
77
+ "applies to the converted routers (static, dynamic or from another provider), or "
78
+ "that no additional control applies. Verify at least: static entryPoints (TLS, "
79
+ "middlewares, redirections, forwarded headers, PROXY protocol, address; routers "
80
+ "naming no entryPoints share the entryPoint of the others), TLS options defined "
81
+ "outside the input (including a 'default' from another provider), SNI option "
82
+ "conflicts, and competing routers of other providers. The tool does not verify it. "
83
+ "Without it, Traefik routes that would forward traffic are refused; unresolved or "
84
+ "unreproducible controls in the input (such as enabled sniStrict) are refused "
85
+ "either way")
86
+ # Removed option, kept only to refuse it explicitly: insecure backend TLS is never emitted.
87
+ command.add_argument("--allow-insecure-backend-tls", action="store_true", help=argparse.SUPPRESS)
88
+ command.add_argument("--strict", action="store_true", help="exit 4 on warnings too")
89
+ command.add_argument("--max-input-bytes", type=int, default=Limits().max_input_bytes)
90
+ if name == "convert":
91
+ command.add_argument("--out", required=True, help="output directory (created with mode 0700)")
92
+ command.add_argument("--force", action="store_true", help="replace existing output files")
93
+ command.add_argument("--include-secrets", action="store_true",
94
+ help="write migratable plaintext credentials (Kong key-auth keys) into the "
95
+ "resources file; the file is written 0600 and must stay private")
96
+ command.add_argument("--resources-format", choices=("yaml", "json"), default="yaml")
97
+ else:
98
+ command.add_argument("--json", action="store_true", help="print the report as JSON")
99
+ sub.add_parser("platforms", help="list supported source platforms")
100
+ return parser
101
+
102
+
103
+ def _detect_format(path: str, platform: str, requested: str) -> str:
104
+ if platform == "nginx":
105
+ if requested not in ("auto", "nginx"):
106
+ raise InputError("NGINX input must use nginx configuration syntax")
107
+ return "nginx"
108
+ if requested == "nginx":
109
+ raise InputError("nginx syntax is only valid with --from nginx")
110
+ if requested != "auto":
111
+ return requested
112
+ lower = path.lower()
113
+ if lower.endswith(".json"):
114
+ return "json"
115
+ if lower.endswith(".toml"):
116
+ return "toml"
117
+ return "yaml"
118
+
119
+
120
+ #: Ferrum Edge v1.0.1 file-loader hard limits (`stable_file.rs::MAX_CONFIG_FILE_BYTES`,
121
+ #: `yaml_alias_budget.rs::MAX_YAML_EVENTS_PER_PASS`).
122
+ MAX_FERRUM_RESOURCES_BYTES = 64 * 1024 * 1024
123
+ MAX_FERRUM_YAML_EVENTS = 1_000_000
124
+
125
+
126
+ def _count_yaml_events(root: object) -> int:
127
+ """Exact YAML parser event count for a JSON/YAML-compatible Python object tree."""
128
+ events = 4 # StreamStart, DocumentStart, DocumentEnd, StreamEnd
129
+ stack = [root]
130
+ while stack:
131
+ item = stack.pop()
132
+ if isinstance(item, dict):
133
+ events += 2 # MappingStart, MappingEnd
134
+ for k, v in item.items():
135
+ stack.append(k)
136
+ stack.append(v)
137
+ elif isinstance(item, list):
138
+ events += 2 # SequenceStart, SequenceEnd
139
+ stack.extend(item)
140
+ else:
141
+ events += 1 # Scalar
142
+ return events
143
+
144
+
145
+ def _dump_resources(config: dict, fmt: str, platform: str) -> str:
146
+ if fmt == "json":
147
+ rendered = json.dumps(config, indent=2, ensure_ascii=False) + "\n"
148
+ else:
149
+ events = _count_yaml_events(config)
150
+ if events > MAX_FERRUM_YAML_EVENTS:
151
+ raise OutputError(f"generated YAML resources file has {events} events, exceeding Ferrum's "
152
+ f"{MAX_FERRUM_YAML_EVENTS}-event YAML limit; use --resources-format json or split the "
153
+ "input")
154
+ header = (f"# Ferrum Edge file-mode resources generated by ferrum-migration {__version__} from {platform} input.\n"
155
+ "# Review migration-report.md before use. Placeholders labelled ferrum-migration/status: refused\n"
156
+ "# answer HTTP 503 by design (fail closed).\n")
157
+ rendered = header + yaml.safe_dump(config, sort_keys=False, default_flow_style=False, allow_unicode=True,
158
+ width=4096)
159
+ size = len(rendered.encode("utf-8"))
160
+ if size > MAX_FERRUM_RESOURCES_BYTES:
161
+ raise OutputError(f"generated resources file is {size} bytes, exceeding Ferrum's "
162
+ f"{MAX_FERRUM_RESOURCES_BYTES}-byte limit; split the input or reduce distinct per-route "
163
+ "plugin overrides")
164
+ return rendered
165
+
166
+
167
+ INSECURE_TLS_REFUSAL = ("ferrum-migrate: --allow-insecure-backend-tls is not supported: backend TLS verification "
168
+ "is always enabled in generated output. Provide the backend CA via "
169
+ "backend_tls_server_ca_cert_path instead. Nothing was written.")
170
+
171
+
172
+ K8S_SD_FLAG = "--kubernetes-service-discovery"
173
+ K8S_SD_SCOPE = (f"ferrum-migrate: {K8S_SD_FLAG} applies only to --from istio. Nothing was written.")
174
+ CONTROLS_ASSERTION_SCOPE = (f"ferrum-migrate: {CONTROLS_ASSERTION_FLAG} applies only to --from traefik "
175
+ "(controls outside Traefik dynamic configuration); it changes nothing for other sources. "
176
+ "Nothing was written.")
177
+
178
+
179
+ def _run(args: argparse.Namespace, state: dict[str, bool] | None = None) -> int:
180
+ if args.allow_insecure_backend_tls:
181
+ print(INSECURE_TLS_REFUSAL, file=sys.stderr)
182
+ return EXIT_USAGE
183
+ if args.traefik_controls_asserted and args.platform != "traefik":
184
+ # Refused rather than ignored, so the statement is never mistaken for one about another source.
185
+ print(CONTROLS_ASSERTION_SCOPE, file=sys.stderr)
186
+ return EXIT_USAGE
187
+ if args.kubernetes_service_discovery and args.platform != "istio":
188
+ print(K8S_SD_SCOPE, file=sys.stderr)
189
+ return EXIT_USAGE
190
+ if args.max_input_bytes <= 0 or args.max_input_bytes > ABSOLUTE_MAX_INPUT_BYTES:
191
+ print(f"ferrum-migrate: --max-input-bytes must be between 1 and {ABSOLUTE_MAX_INPUT_BYTES}", file=sys.stderr)
192
+ return EXIT_USAGE
193
+ limits = Limits(max_input_bytes=args.max_input_bytes)
194
+ label = "stdin" if args.input == "-" else os.path.basename(args.input)
195
+ report = Report(args.platform, label)
196
+ include_secrets = getattr(args, "include_secrets", False)
197
+ fmt = _detect_format(args.input, args.platform, args.input_format)
198
+ text = read_input(args.input, limits)
199
+ context = SourceContext(report=report, limits=limits, include_secrets=include_secrets,
200
+ traefik_controls_asserted=args.traefik_controls_asserted,
201
+ kubernetes_service_discovery=args.kubernetes_service_discovery)
202
+ plan = SOURCES[args.platform].translate(text, fmt, context)
203
+ options = EmitOptions(include_secrets=include_secrets, tls_only=args.tls_only)
204
+ result = emit(plan, options, report)
205
+ resources_name = RESOURCES_JSON if getattr(args, "resources_format", "yaml") == "json" else RESOURCES_YAML
206
+ summary = dict(result.stats)
207
+ summary["run_mode"] = args.run_mode
208
+ steps = next_steps(args.run_mode, resources_name, result.tls_only, result.basic_auth_used, result.secrets_emitted)
209
+ exit_code = EXIT_REVIEW if report.has_errors or (args.strict and report.has_warnings) else EXIT_OK
210
+ # Rendered for `check` too, so a source value that cannot be written safely in ferrum.conf syntax is rejected
211
+ # (exit 3) by both commands, before anything is written.
212
+ profile = render(args.run_mode, args.platform, plan.settings, result.tls_only, result.basic_auth_used,
213
+ resources_name)
214
+
215
+ if args.command == "check":
216
+ if args.json:
217
+ print(json.dumps(report.to_json_obj(summary, steps), indent=2))
218
+ else:
219
+ _print_text(report, summary)
220
+ return exit_code
221
+
222
+ files: dict[str, str] = {}
223
+ if result.secrets_emitted:
224
+ # Publish .gitignore first so any mid-write failure never leaves plaintext credentials without an ignore guard.
225
+ files[".gitignore"] = "# Generated: this directory contains plaintext credentials.\n*\n"
226
+ files[resources_name] = _dump_resources(result.config, args.resources_format, args.platform)
227
+ files["ferrum.conf"] = profile
228
+ files["migration-report.json"] = json.dumps(report.to_json_obj(summary, steps), indent=2) + "\n"
229
+ files["migration-report.md"] = report.to_markdown(summary, steps)
230
+ # A resources file of the other format left by an earlier run would be stale and ambiguous: Ferrum's spec
231
+ # discovery prefers ./resources.yaml over ./resources.json. It is never replaced or deleted, not even with --force.
232
+ other_format = RESOURCES_YAML if resources_name == RESOURCES_JSON else RESOURCES_JSON
233
+ if state is not None:
234
+ state["write_started"] = True
235
+ directory, _written = write_output_files(args.out, files, args.force, forbidden=(other_format,),
236
+ require_private=include_secrets)
237
+ _print_text(report, summary, details=False)
238
+ print(f"Wrote {', '.join(sorted(name for name in files if not name.startswith('.')))} to {directory}")
239
+ if result.secrets_emitted:
240
+ print(f"WARNING: {resources_name} contains {result.secrets_emitted} plaintext credential(s); it was written "
241
+ "with mode 0600. Keep it private and never commit it.", file=sys.stderr)
242
+ return exit_code
243
+
244
+
245
+ def _print_text(report: Report, summary: dict, details: bool = True) -> None:
246
+ print(f"ferrum-migration {__version__}: {report.platform} -> Ferrum Edge")
247
+ for key in ("source_routes", "migrated_routes", "refused_routes", "fail_closed_placeholders", "proxies",
248
+ "upstreams", "consumers", "plugin_configs"):
249
+ if key in summary:
250
+ print(f" {key}: {summary[key]}")
251
+ print(f" caveats: {report.count('error')} error, {report.count('warning')} warning, {report.count('info')} info")
252
+ if details:
253
+ for item in report.ordered():
254
+ line = f" [{item.severity}] {item.code} ({item.ref}): {item.message}"
255
+ if item.action:
256
+ line += f" Action: {item.action}"
257
+ print(line)
258
+
259
+
260
+ def main(argv: Sequence[str] | None = None) -> int:
261
+ parser = build_parser()
262
+ try:
263
+ args = parser.parse_args(argv)
264
+ except SystemExit as exc:
265
+ return int(exc.code) if isinstance(exc.code, int) else EXIT_USAGE
266
+ if args.command == "platforms":
267
+ for name in sorted(SOURCES):
268
+ print(f"{name:8s} {DESCRIPTIONS[name]}")
269
+ return EXIT_OK
270
+ state = {"write_started": False}
271
+ try:
272
+ return _run(args, state)
273
+ except InputError as exc:
274
+ print(f"ferrum-migrate: input rejected: {exc}", file=sys.stderr)
275
+ return EXIT_INPUT
276
+ except OutputError as exc:
277
+ print(f"ferrum-migrate: output error: {exc}", file=sys.stderr)
278
+ return EXIT_OUTPUT
279
+ except KeyboardInterrupt:
280
+ return 130
281
+ except Exception as exc: # pragma: no cover - defensive; never echo exception text (may contain input)
282
+ detail = "output may be incomplete" if state["write_started"] else "no output was written"
283
+ print(f"ferrum-migrate: internal error ({type(exc).__name__}); {detail}", file=sys.stderr)
284
+ return EXIT_INTERNAL
@@ -0,0 +1,289 @@
1
+ """Render a ``ferrum.conf`` (``KEY=value``) profile for the intended run mode.
2
+
3
+ Only settings present in Ferrum Edge's public settings inventory
4
+ (``src/config/public_env_inventory.rs`` at the reference commit) are emitted.
5
+ Secrets are never written: secret-bearing settings appear as comments that tell
6
+ the operator to export the matching ``*_FILE`` variable in the environment
7
+ (Ferrum resolves ``_FILE`` suffixes from the environment only, never from
8
+ ``ferrum.conf``). Values the tool cannot know are left as ``# REQUIRED`` comments
9
+ so the file stays valid until the operator fills them in.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from . import FERRUM_EDGE_REFERENCE_COMMIT, __version__
15
+ from .errors import InputError
16
+ from .model import SettingsHints
17
+
18
+ RUN_MODES = ("file", "database", "cp", "dp")
19
+
20
+ #: Subset of Ferrum's public settings inventory that this tool may mention.
21
+ KNOWN_SETTINGS = frozenset({
22
+ "FERRUM_MODE", "FERRUM_FILE_CONFIG_PATH", "FERRUM_LOG_LEVEL", "FERRUM_NAMESPACE",
23
+ "FERRUM_PROXY_HTTP_PORT", "FERRUM_PROXY_HTTPS_PORT", "FERRUM_PROXY_BIND_ADDRESS",
24
+ "FERRUM_ADMIN_BIND_ADDRESS", "FERRUM_ADMIN_HTTP_PORT", "FERRUM_ADMIN_JWT_SECRET",
25
+ "FERRUM_FRONTEND_TLS_CERT_PATH", "FERRUM_FRONTEND_TLS_KEY_PATH",
26
+ "FERRUM_FRONTEND_TLS_CLIENT_CA_BUNDLE_PATH", "FERRUM_MAX_REQUEST_BODY_SIZE_BYTES",
27
+ "FERRUM_TRUSTED_PROXIES", "FERRUM_REAL_IP_HEADER", "FERRUM_BASIC_AUTH_HMAC_SECRET",
28
+ "FERRUM_DB_TYPE", "FERRUM_DB_URL", "FERRUM_CP_GRPC_LISTEN_ADDR", "FERRUM_CP_DP_GRPC_JWT_SECRET",
29
+ "FERRUM_DP_CP_GRPC_URLS", "FERRUM_ENABLE_HTTP3", "FERRUM_FRONTEND_PROXY_PROTOCOL_HTTP",
30
+ "FERRUM_FRONTEND_PROXY_PROTOCOL_HTTPS", "FERRUM_FRONTEND_PROXY_PROTOCOL_TRUSTED_CIDRS",
31
+ "FERRUM_K8S_CONTROLLER_ENABLED", "FERRUM_K8S_WATCH_ISTIO_CRDS",
32
+ })
33
+
34
+
35
+ def conf_value(key: str, value: object) -> str:
36
+ """Render ``value`` so Ferrum's ``ferrum.conf`` parser reads back exactly the same string.
37
+
38
+ Ferrum (``src/config/conf_file.rs``) splits lines on newlines, trims each line and value, treats a value
39
+ starting with ``"`` or ``'`` as quoted up to the next identical quote (no escapes), and otherwise ends an
40
+ unquoted value at the first `` #``. Values that need it are quoted; values that cannot round-trip (empty,
41
+ non-printable or line-breaking characters, or both quote characters when quoting is required) raise
42
+ :class:`InputError` before anything is written. The message never contains the value.
43
+ """
44
+ text = str(value)
45
+ if not text or not all(ch.isprintable() for ch in text):
46
+ raise InputError(f"a source-derived value for {key} cannot be written safely in ferrum.conf syntax "
47
+ "(empty, or it contains control, line-breaking or other non-printable characters)")
48
+ if text == text.strip() and text[0] not in "\"'" and " #" not in text:
49
+ return text
50
+ for quote in ('"', "'"):
51
+ if quote not in text:
52
+ return f"{quote}{text}{quote}"
53
+ raise InputError(f"a source-derived value for {key} cannot be written safely in ferrum.conf syntax (it needs "
54
+ "quoting but contains both quote characters)")
55
+
56
+
57
+ class _Lines:
58
+ def __init__(self) -> None:
59
+ self.lines: list[str] = []
60
+
61
+ def comment(self, text: str) -> None:
62
+ self.lines.append(f"# {text}" if text else "#")
63
+
64
+ def put(self, key: str, value: object, note: str | None = None) -> None:
65
+ assert key in KNOWN_SETTINGS, key
66
+ rendered = conf_value(key, value) # fail closed: never write a setting Ferrum would read differently
67
+ if note:
68
+ self.comment(note)
69
+ self.lines.append(f"{key}={rendered}")
70
+
71
+ def suggest(self, key: str, value: object, note: str) -> None:
72
+ assert key in KNOWN_SETTINGS, key
73
+ self.comment(note)
74
+ try:
75
+ rendered = conf_value(key, value)
76
+ except InputError:
77
+ # Only a commented suggestion: omit the value rather than break out of the comment line.
78
+ self.comment(f"{key}: the source value cannot be written safely in ferrum.conf syntax; set it manually.")
79
+ return
80
+ self.lines.append(f"# {key}={rendered}")
81
+
82
+ def blank(self) -> None:
83
+ self.lines.append("")
84
+
85
+
86
+ def render(run_mode: str, platform: str, settings: SettingsHints, tls_only: bool, basic_auth_used: bool,
87
+ resources_name: str) -> str:
88
+ if run_mode not in RUN_MODES:
89
+ raise ValueError(run_mode)
90
+ out = _Lines()
91
+ out.comment(f"Generated by ferrum-migration {__version__} from {platform} input for FERRUM_MODE={run_mode}.")
92
+ out.comment(f"Settings names verified against Ferrum Edge {FERRUM_EDGE_REFERENCE_COMMIT[:12]}.")
93
+ out.comment("This file contains no secrets. Export secret settings as *_FILE variables in the process")
94
+ out.comment("environment (Ferrum does not resolve *_FILE suffixes from ferrum.conf). Review before use.")
95
+ out.blank()
96
+ out.put("FERRUM_MODE", run_mode)
97
+ out.put("FERRUM_LOG_LEVEL", "info")
98
+ out.put("FERRUM_ADMIN_BIND_ADDRESS", "127.0.0.1", "Keep the admin API on loopback; see Ferrum docs before exposing it.")
99
+ if run_mode == "file":
100
+ out.suggest("FERRUM_FILE_CONFIG_PATH", resources_name,
101
+ f"Pass --spec {resources_name} (see the report's next steps) or set an absolute path here. "
102
+ "Without either, `ferrum-edge run` discovers ./resources.yaml before ./resources.json.")
103
+ out.blank()
104
+
105
+ # The emitter records which listeners every live route may be served on; a caller without a plan falls back to
106
+ # the TLS-only flag. The rendered settings are checked against it below (assert_listener_invariant).
107
+ protocols = settings.frontend_protocols or ("https" if tls_only else "both")
108
+ if protocols not in LISTENER_MODES or tls_only != (protocols == "https"):
109
+ raise AssertionError("profile listener mode disagrees with the emitter's frontend decision")
110
+ if run_mode == "cp" and protocols != "both":
111
+ out.comment("Listeners: this control plane serves no proxy traffic. Every data plane that loads these")
112
+ out.comment("resources must open only the listener(s) below, or it serves routes on a protocol the source")
113
+ out.comment("never served them on:")
114
+ if protocols == "http":
115
+ out.lines.append("# FERRUM_PROXY_HTTPS_PORT=0 and no FERRUM_FRONTEND_TLS_* settings (plaintext only)")
116
+ else:
117
+ out.lines.append("# FERRUM_PROXY_HTTP_PORT=0 (HTTPS only)")
118
+ out.blank()
119
+ if run_mode != "cp":
120
+ out.comment("Listeners")
121
+ if protocols == "https":
122
+ out.put("FERRUM_PROXY_HTTP_PORT", 0, "Source routes require HTTPS: the plaintext listener is disabled.")
123
+ elif settings.main_http_port:
124
+ out.put("FERRUM_PROXY_HTTP_PORT", settings.main_http_port,
125
+ "Plaintext port from the source (ports below 1024 need CAP_NET_BIND_SERVICE).")
126
+ if protocols == "http":
127
+ out.put("FERRUM_PROXY_HTTPS_PORT", 0,
128
+ "Migrated routes were served over plaintext in the source: the HTTPS listener is disabled "
129
+ "explicitly, because Ferrum would open it on its default port whenever frontend TLS material is "
130
+ "configured and serve these routes there. Do not configure FERRUM_FRONTEND_TLS_* for this "
131
+ "profile (environment variables override this file).")
132
+ elif settings.main_https_port:
133
+ out.put("FERRUM_PROXY_HTTPS_PORT", settings.main_https_port, "TLS port from the source.")
134
+ if settings.bind_address:
135
+ out.put("FERRUM_PROXY_BIND_ADDRESS", settings.bind_address,
136
+ "The source only listened on this address; keep Ferrum on it too.")
137
+ needs_cert = protocols != "http" and (protocols == "https" or settings.frontend_tls_expected
138
+ or bool(settings.main_https_port))
139
+ pairs = sorted(set(settings.frontend_cert_pairs))
140
+ if needs_cert:
141
+ if len(pairs) == 1:
142
+ out.put("FERRUM_FRONTEND_TLS_CERT_PATH", pairs[0][0], "Certificate path referenced by the source.")
143
+ out.put("FERRUM_FRONTEND_TLS_KEY_PATH", pairs[0][1], "Private key path referenced by the source "
144
+ "(the tool never reads key files).")
145
+ else:
146
+ if len(pairs) > 1:
147
+ out.comment(f"The source used {len(pairs)} certificates; Ferrum file mode serves one default "
148
+ "frontend certificate. Choose one (or a SAN certificate covering all hosts).")
149
+ out.comment("REQUIRED for HTTPS: write the certificate and key to files and set:")
150
+ out.lines.append("# FERRUM_FRONTEND_TLS_CERT_PATH=/etc/ferrum/tls/fullchain.pem")
151
+ out.lines.append("# FERRUM_FRONTEND_TLS_KEY_PATH=/etc/ferrum/tls/privkey.pem")
152
+ # HTTPS disabled: no frontend TLS at all (the emitter configured no client CA and refused HTTPS-only routes).
153
+ cas = sorted(set(settings.client_ca_paths)) if protocols != "http" else []
154
+ ca_conflict = settings.client_ca_scope_conflict and protocols != "http"
155
+ if len(cas) == 1 and not ca_conflict:
156
+ out.put("FERRUM_FRONTEND_TLS_CLIENT_CA_BUNDLE_PATH", cas[0],
157
+ "Every migrated route that required client certificates (mTLS) used this one CA bundle; Ferrum "
158
+ "applies it to the whole HTTPS listener.")
159
+ elif cas or ca_conflict:
160
+ # Never suggest merging bundles: that would let clients trusted by one source scope reach another.
161
+ out.comment("REVIEW REQUIRED (frontend-client-ca-scope): the source required client certificates from")
162
+ out.comment("several CA bundles on separate servers/listeners. One shared Ferrum listener cannot keep")
163
+ out.comment("those trust scopes apart, so no client CA bundle is configured here and the affected routes")
164
+ out.comment("were refused. Do NOT concatenate the bundles. Use a separately configured Ferrum frontend")
165
+ out.comment("per trust boundary, each with its own FERRUM_FRONTEND_TLS_CLIENT_CA_BUNDLE_PATH, and review")
166
+ out.comment("and validate each one. See migration-report.md.")
167
+ if settings.max_request_body_bytes:
168
+ out.put("FERRUM_MAX_REQUEST_BODY_SIZE_BYTES", settings.max_request_body_bytes,
169
+ "Largest request body any source route accepted; smaller per-route limits use request_size_limiting.")
170
+ if settings.http3 and protocols != "http":
171
+ out.suggest("FERRUM_ENABLE_HTTP3", "true", "The source enabled HTTP/3 (QUIC).")
172
+ if settings.trusted_proxies:
173
+ out.suggest("FERRUM_TRUSTED_PROXIES", ",".join(settings.trusted_proxies),
174
+ "SUGGESTED: the source trusted these proxies (IP addresses or CIDRs, comma-separated) for "
175
+ "client-IP resolution.")
176
+ if settings.real_ip_header:
177
+ out.suggest("FERRUM_REAL_IP_HEADER", settings.real_ip_header,
178
+ "SUGGESTED: the source read the client IP from this header.")
179
+ if settings.proxy_protocol and settings.proxy_protocol_version:
180
+ # Ferrum accepts off|v1|v2|auto per listener and, once enabled, requires the header from
181
+ # FERRUM_FRONTEND_PROXY_PROTOCOL_TRUSTED_CIDRS peers. Sources whose header was optional, or whose
182
+ # listeners disagree on the version, are reported instead of suggested.
183
+ version = settings.proxy_protocol_version
184
+ note = (f"SUGGESTED: the source required PROXY protocol ({'v1 or v2' if version == 'auto' else version}). "
185
+ "Enable it only on the listeners that receive it, and set the load balancers' CIDRs below.")
186
+ if protocols != "https":
187
+ out.suggest("FERRUM_FRONTEND_PROXY_PROTOCOL_HTTP", version, note)
188
+ if protocols != "http":
189
+ out.suggest("FERRUM_FRONTEND_PROXY_PROTOCOL_HTTPS", version, note)
190
+ if settings.proxy_protocol_trusted:
191
+ out.suggest("FERRUM_FRONTEND_PROXY_PROTOCOL_TRUSTED_CIDRS", ",".join(settings.proxy_protocol_trusted),
192
+ "SUGGESTED: the source accepted PROXY headers from these addresses.")
193
+ else:
194
+ out.lines.append("# FERRUM_FRONTEND_PROXY_PROTOCOL_TRUSTED_CIDRS=<load balancer CIDRs, comma-separated>")
195
+ out.blank()
196
+
197
+ if basic_auth_used and run_mode != "cp":
198
+ out.comment("REQUIRED by basic_auth: a unique random secret of at least 32 bytes, exported as")
199
+ out.comment("FERRUM_BASIC_AUTH_HMAC_SECRET_FILE=/run/secrets/ferrum_basic_auth_hmac in the environment.")
200
+ out.blank()
201
+
202
+ if run_mode in ("database", "cp"):
203
+ out.comment("Database")
204
+ out.put("FERRUM_DB_TYPE", "sqlite", "Change to postgres, mysql or mongodb as needed.")
205
+ out.comment("REQUIRED: export FERRUM_DB_URL (or FERRUM_DB_URL_FILE when it embeds credentials), e.g.")
206
+ out.lines.append("# FERRUM_DB_URL=sqlite://ferrum.db?mode=rwc")
207
+ out.comment("REQUIRED: export FERRUM_ADMIN_JWT_SECRET_FILE (secret of at least 32 characters).")
208
+ out.blank()
209
+ if run_mode == "cp":
210
+ out.put("FERRUM_CP_GRPC_LISTEN_ADDR", "127.0.0.1:50051", "Loopback by default; use TLS before binding wider.")
211
+ out.comment("REQUIRED: export FERRUM_CP_DP_GRPC_JWT_SECRET_FILE (secret of at least 32 characters).")
212
+ out.blank()
213
+ if run_mode == "dp":
214
+ out.comment("REQUIRED: point the data plane at its control plane(s), e.g.")
215
+ out.lines.append("# FERRUM_DP_CP_GRPC_URLS=https://cp.example.internal:50051")
216
+ out.comment("REQUIRED: export FERRUM_ADMIN_JWT_SECRET_FILE and FERRUM_CP_DP_GRPC_JWT_SECRET_FILE.")
217
+ out.comment("Resources are loaded into the control plane, not into the data plane.")
218
+ out.blank()
219
+ if platform == "istio":
220
+ out.comment("This profile serves an ingress projection of Gateway-bound routes only (no mesh, no workload")
221
+ out.comment("mTLS). Ferrum documents separate Istio CRD support (FERRUM_K8S_CONTROLLER_ENABLED,")
222
+ out.comment("FERRUM_K8S_WATCH_ISTIO_CRDS; see Ferrum docs/mesh.md); ferrum-migration does not exercise it.")
223
+ profile = "\n".join(out.lines).rstrip("\n") + "\n"
224
+ assert_listener_invariant(profile, protocols, run_mode)
225
+ return profile
226
+
227
+
228
+ #: Frontend modes the emitter decides (see ferrum._decide_frontend).
229
+ LISTENER_MODES = ("http", "https", "both")
230
+
231
+
232
+ def assert_listener_invariant(profile: str, protocols: str, run_mode: str) -> None:
233
+ """Hard invariant on the RENDERED profile: it opens exactly the listeners the emitter decided on.
234
+
235
+ Ferrum opens its plaintext listener unless ``FERRUM_PROXY_HTTP_PORT=0`` and its HTTPS listener (default port)
236
+ whenever frontend TLS material is configured unless ``FERRUM_PROXY_HTTPS_PORT=0``, so absent settings prove
237
+ nothing. ``http``: HTTPS explicitly disabled and no active ``FERRUM_FRONTEND_TLS_*``/HTTP/3 setting; ``https``:
238
+ plaintext explicitly disabled; ``both``: neither disabled. A control plane renders no proxy listeners. A
239
+ violation is a tool bug: it raises, and the CLI writes nothing.
240
+ """
241
+ if protocols not in LISTENER_MODES:
242
+ raise AssertionError("unknown frontend listener mode")
243
+ if run_mode == "cp":
244
+ return
245
+ values: dict[str, str] = {}
246
+ for line in profile.splitlines():
247
+ text = line.strip()
248
+ if not text or text.startswith("#") or "=" not in text:
249
+ continue
250
+ key, _, value = text.partition("=")
251
+ values[key.strip()] = value.strip()
252
+ http_off = values.get("FERRUM_PROXY_HTTP_PORT") == "0"
253
+ https_off = values.get("FERRUM_PROXY_HTTPS_PORT") == "0"
254
+ tls_active = any(key.startswith("FERRUM_FRONTEND_TLS_") or key == "FERRUM_ENABLE_HTTP3" for key in values)
255
+ if protocols == "http":
256
+ valid = https_off and not http_off and not tls_active
257
+ elif protocols == "https":
258
+ valid = http_off and not https_off
259
+ else:
260
+ valid = not http_off and not https_off
261
+ if not valid:
262
+ raise AssertionError("rendered listener settings do not match the emitter's frontend decision")
263
+
264
+
265
+ def next_steps(run_mode: str, resources_name: str, tls_only: bool, basic_auth_used: bool,
266
+ secrets_emitted: int) -> list[str]:
267
+ steps = ["Read every error and warning in this report; errors mark refused or fail-closed items."]
268
+ if run_mode == "file":
269
+ steps.append(f"Validate offline: `ferrum-edge validate --settings ferrum.conf --spec {resources_name}`.")
270
+ steps.append(f"Try it: `ferrum-edge run --settings ferrum.conf --spec {resources_name}`.")
271
+ else:
272
+ steps.append(f"Validate the resources in file mode first: `ferrum-edge validate -m file -c {resources_name}`.")
273
+ steps.append("Import them through Ferrum's Admin API yourself. First convert them to JSON and drop the "
274
+ "file-mode-only top-level `resource_counts` key, which the Admin API does not accept. Then "
275
+ "choose: `POST /batch` is an additive, all-or-nothing import next to the existing configuration "
276
+ "(it fails as a whole on conflicts and has a 1 MiB request limit, so split large imports). "
277
+ "`POST /restore?confirm=true` REPLACES the namespace's entire configuration, so take "
278
+ "`GET /backup` first. See Ferrum docs/admin_batch_api.md and docs/admin_backup_restore.md.")
279
+ steps.append("This tool performs no network I/O, never connects to a live database, and has not "
280
+ "runtime-tested either import path.")
281
+ if tls_only:
282
+ steps.append("Provide the frontend certificate and key paths in ferrum.conf (HTTPS only).")
283
+ if basic_auth_used:
284
+ steps.append("Export FERRUM_BASIC_AUTH_HMAC_SECRET_FILE and create Basic-auth credentials in Ferrum's "
285
+ "hmac_sha256 format; source password hashes cannot be converted.")
286
+ if secrets_emitted:
287
+ steps.append(f"{resources_name} contains {secrets_emitted} plaintext credential(s): keep it private "
288
+ "(mode 0600) and never commit it.")
289
+ return steps
@@ -0,0 +1,20 @@
1
+ """Exception types whose messages are safe to print.
2
+
3
+ Every message passed to these exceptions is composed by this package from
4
+ positions, counts and schema names only. Input values (which may carry
5
+ credentials) must never be interpolated into them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class MigrationError(Exception):
12
+ """Base class for errors that terminate a migration run."""
13
+
14
+
15
+ class InputError(MigrationError):
16
+ """The input was rejected (syntax, limits, unsupported shape)."""
17
+
18
+
19
+ class OutputError(MigrationError):
20
+ """Output could not be written safely."""