maproom 0.2.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.
Files changed (199) hide show
  1. maproom/__init__.py +14 -0
  2. maproom/__main__.py +10 -0
  3. maproom/analyze/__init__.py +1 -0
  4. maproom/analyze/accel_families.py +45 -0
  5. maproom/analyze/account_azure_activity.py +260 -0
  6. maproom/analyze/account_azure_quota_requests.py +177 -0
  7. maproom/analyze/account_cloudtrail.py +316 -0
  8. maproom/analyze/account_quota_requests.py +180 -0
  9. maproom/analyze/analyze_v1_orchestration.py +1194 -0
  10. maproom/analyze/catalog.py +353 -0
  11. maproom/analyze/change_detection.py +652 -0
  12. maproom/analyze/context_client.py +99 -0
  13. maproom/analyze/context_lookup.py +142 -0
  14. maproom/analyze/cover_analyze.py +344 -0
  15. maproom/analyze/cover_client.py +65 -0
  16. maproom/analyze/cover_lookup.py +242 -0
  17. maproom/analyze/engine.py +644 -0
  18. maproom/analyze/fleetfit_endpoints.py +217 -0
  19. maproom/analyze/fleetfit_policy.py +66 -0
  20. maproom/analyze/instance_price_analyze.py +221 -0
  21. maproom/analyze/instance_price_client.py +108 -0
  22. maproom/analyze/instance_price_lookup.py +60 -0
  23. maproom/analyze/local_reads.py +484 -0
  24. maproom/analyze/lookup_http.py +280 -0
  25. maproom/analyze/metric_format.py +20 -0
  26. maproom/analyze/migration_method.py +130 -0
  27. maproom/analyze/move_list.py +93 -0
  28. maproom/analyze/operator_context.py +156 -0
  29. maproom/analyze/performance_rank.py +97 -0
  30. maproom/analyze/primary_recommendation.py +422 -0
  31. maproom/analyze/provider_comparison.py +401 -0
  32. maproom/analyze/quota_analyze.py +481 -0
  33. maproom/analyze/quota_client.py +75 -0
  34. maproom/analyze/quota_lookup.py +110 -0
  35. maproom/analyze/quota_outcome_steer.py +105 -0
  36. maproom/analyze/recommend_batch.py +199 -0
  37. maproom/analyze/recommend_client.py +362 -0
  38. maproom/analyze/recommend_share.py +118 -0
  39. maproom/analyze/recommendation.py +591 -0
  40. maproom/analyze/reservation_pack.py +883 -0
  41. maproom/analyze/reservation_read.py +461 -0
  42. maproom/analyze/safe_analyze.py +1134 -0
  43. maproom/analyze/safe_move.py +195 -0
  44. maproom/analyze/safe_moves.py +571 -0
  45. maproom/analyze/safe_moves_catalog.py +127 -0
  46. maproom/analyze/safe_moves_client.py +70 -0
  47. maproom/analyze/series_analyze.py +491 -0
  48. maproom/analyze/series_client.py +106 -0
  49. maproom/analyze/series_lookup.py +663 -0
  50. maproom/analyze/shape.py +254 -0
  51. maproom/analyze/size_analyze.py +883 -0
  52. maproom/analyze/size_client.py +81 -0
  53. maproom/analyze/size_keep.py +409 -0
  54. maproom/analyze/size_lookup.py +368 -0
  55. maproom/analyze/specs.py +325 -0
  56. maproom/analyze/spot_analyze.py +392 -0
  57. maproom/analyze/spot_client.py +74 -0
  58. maproom/analyze/spot_lookup.py +213 -0
  59. maproom/analyze/token_client.py +97 -0
  60. maproom/analyze/utilization.py +190 -0
  61. maproom/analyze/workload.py +104 -0
  62. maproom/analyze/workset.py +762 -0
  63. maproom/aws_region.py +78 -0
  64. maproom/cache/__init__.py +1 -0
  65. maproom/cache/catalog.py +372 -0
  66. maproom/cache/commands.py +215 -0
  67. maproom/cache/instances.py +460 -0
  68. maproom/cli.py +2084 -0
  69. maproom/cli_argv.py +329 -0
  70. maproom/cli_floors.py +89 -0
  71. maproom/cliio/__init__.py +1 -0
  72. maproom/cliio/registry.py +377 -0
  73. maproom/cliio/runner.py +489 -0
  74. maproom/consent/__init__.py +33 -0
  75. maproom/consent/gate.py +238 -0
  76. maproom/consent/policy.py +20 -0
  77. maproom/consent/prompt.py +61 -0
  78. maproom/consent/service_upload_gate.py +318 -0
  79. maproom/consent/service_upload_prompt.py +62 -0
  80. maproom/consent/stdin.py +45 -0
  81. maproom/consent/storage.py +24 -0
  82. maproom/consent/write_token.py +29 -0
  83. maproom/contracts/__init__.py +6 -0
  84. maproom/contracts/schema_diff.py +119 -0
  85. maproom/contracts/validate.py +113 -0
  86. maproom/data/__init__.py +1 -0
  87. maproom/data/clear.py +76 -0
  88. maproom/data/commands.py +14 -0
  89. maproom/doctor/__init__.py +1 -0
  90. maproom/doctor/aws_session.py +226 -0
  91. maproom/doctor/checks.py +701 -0
  92. maproom/doctor/context.py +32 -0
  93. maproom/doctor/display.py +96 -0
  94. maproom/doctor/inventory_display.py +377 -0
  95. maproom/doctor/runner.py +1467 -0
  96. maproom/errors.py +43 -0
  97. maproom/exitcodes.py +70 -0
  98. maproom/inventory/__init__.py +1 -0
  99. maproom/inventory/account_identity.py +79 -0
  100. maproom/inventory/accounts.py +155 -0
  101. maproom/inventory/command.py +961 -0
  102. maproom/inventory/messages.py +264 -0
  103. maproom/inventory/reservations_refresh.py +37 -0
  104. maproom/mock_environment/__init__.py +28 -0
  105. maproom/mock_environment/load.py +241 -0
  106. maproom/mock_environment/runner.py +387 -0
  107. maproom/output/__init__.py +1 -0
  108. maproom/output/json_envelope.py +241 -0
  109. maproom/output/redact.py +11 -0
  110. maproom/output/terminal.py +129 -0
  111. maproom/parsers.py +284 -0
  112. maproom/paths.py +105 -0
  113. maproom/plan/__init__.py +1 -0
  114. maproom/plan/accept.py +59 -0
  115. maproom/plan/analysis_context.py +78 -0
  116. maproom/plan/analyze_selection.py +279 -0
  117. maproom/plan/commands.py +586 -0
  118. maproom/plan/current.py +59 -0
  119. maproom/plan/errors.py +10 -0
  120. maproom/plan/export.py +36 -0
  121. maproom/plan/formatting.py +91 -0
  122. maproom/plan/ids.py +13 -0
  123. maproom/plan/migration_options.py +75 -0
  124. maproom/plan/model.py +265 -0
  125. maproom/plan/names.py +24 -0
  126. maproom/plan/store.py +193 -0
  127. maproom/plan/tty.py +34 -0
  128. maproom/pricing/__init__.py +5 -0
  129. maproom/pricing/prices.py +119 -0
  130. maproom/privacy/__init__.py +6 -0
  131. maproom/privacy/commands.py +159 -0
  132. maproom/privacy/delete_uploads.py +204 -0
  133. maproom/privacy/fleetfit_policy.py +125 -0
  134. maproom/privacy/fleetfit_statement.py +104 -0
  135. maproom/privacy/format.py +76 -0
  136. maproom/privacy/manifests.py +342 -0
  137. maproom/privacy/statement.py +58 -0
  138. maproom/quotas/__init__.py +21 -0
  139. maproom/quotas/aws.py +204 -0
  140. maproom/quotas/azure.py +75 -0
  141. maproom/quotas/commands.py +240 -0
  142. maproom/quotas/family_coverage.py +122 -0
  143. maproom/quotas/fetch.py +124 -0
  144. maproom/quotas/load.py +41 -0
  145. maproom/quotas/model.py +178 -0
  146. maproom/quotas/outcome_ledger.py +245 -0
  147. maproom/quotas/quota_request_sync.py +221 -0
  148. maproom/quotas/show.py +73 -0
  149. maproom/quotas/status.py +206 -0
  150. maproom/quotas/store.py +161 -0
  151. maproom/redaction.py +157 -0
  152. maproom/reference_data/__init__.py +1 -0
  153. maproom/reference_data/aws/aws_prices.csv +25562 -0
  154. maproom/reference_data/aws/capabilities.csv +1346 -0
  155. maproom/reference_data/aws/instance_types.csv +1346 -0
  156. maproom/reference_data/azure/azure_prices.csv +1 -0
  157. maproom/reference_data/azure/vm_types.csv +1 -0
  158. maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
  159. maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
  160. maproom/reference_data/manifest.json +174 -0
  161. maproom/reference_data/manifest.py +69 -0
  162. maproom/reservations/__init__.py +17 -0
  163. maproom/reservations/aws.py +76 -0
  164. maproom/reservations/azure.py +36 -0
  165. maproom/reservations/commands.py +149 -0
  166. maproom/reservations/load.py +41 -0
  167. maproom/reservations/model.py +316 -0
  168. maproom/reservations/show.py +64 -0
  169. maproom/reservations/status.py +181 -0
  170. maproom/reservations/store.py +391 -0
  171. maproom/resources.py +54 -0
  172. maproom/root_help.py +251 -0
  173. maproom/saving_plans/__init__.py +15 -0
  174. maproom/saving_plans/aws.py +73 -0
  175. maproom/saving_plans/commands.py +122 -0
  176. maproom/saving_plans/load.py +41 -0
  177. maproom/saving_plans/model.py +101 -0
  178. maproom/saving_plans/show.py +64 -0
  179. maproom/saving_plans/status.py +118 -0
  180. maproom/saving_plans/store.py +173 -0
  181. maproom/secret_egress_gate.py +108 -0
  182. maproom/service/install_id.py +60 -0
  183. maproom/settings/__init__.py +1 -0
  184. maproom/settings/defaults.py +73 -0
  185. maproom/settings/init.py +143 -0
  186. maproom/settings/model.py +105 -0
  187. maproom/settings/product_version_change.py +343 -0
  188. maproom/settings/product_versions.py +68 -0
  189. maproom/settings/set.py +347 -0
  190. maproom/settings/show.py +227 -0
  191. maproom/settings/write.py +273 -0
  192. maproom/snapshot_time.py +27 -0
  193. maproom-0.2.0.dist-info/METADATA +263 -0
  194. maproom-0.2.0.dist-info/RECORD +199 -0
  195. maproom-0.2.0.dist-info/WHEEL +5 -0
  196. maproom-0.2.0.dist-info/entry_points.txt +2 -0
  197. maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
  198. maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
  199. maproom-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,238 @@
1
+ """Shared cloud-read consent gate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timedelta, timezone
8
+ from pathlib import Path
9
+ from typing import Callable
10
+
11
+ from maproom.consent.policy import ManagedPolicyEvaluator, default_policy_evaluator
12
+ from maproom.consent.prompt import (
13
+ INVALID_CLOUD_READ_ANSWER,
14
+ NON_INTERACTIVE_PROVENANCE,
15
+ cloud_read_prompt,
16
+ snooze_block_message,
17
+ )
18
+ from maproom.settings.model import load_effective_settings
19
+ from maproom.consent.stdin import stdin_allows_prompt
20
+ from maproom.consent.storage import consent_storage_available
21
+ from maproom.paths import prepare_settings_write, settings_read_file
22
+ from maproom.settings.model import load_consent_state
23
+ from maproom.settings.write import (
24
+ SettingsWriteError,
25
+ persist_cloud_read_grant,
26
+ persist_cloud_read_snooze,
27
+ )
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class CloudReadGateOutcome:
32
+ allowed: bool
33
+ exit_code: int
34
+ reason_code: str | None = None
35
+ message: str | None = None
36
+
37
+
38
+ def _utc_now(now_utc: Callable[[], datetime] | None = None) -> datetime:
39
+ if now_utc is not None:
40
+ return now_utc()
41
+ return datetime.now(timezone.utc)
42
+
43
+
44
+ def _format_utc(ts: datetime) -> str:
45
+ return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
46
+
47
+
48
+ def _parse_utc(value: str) -> datetime | None:
49
+ try:
50
+ if value.endswith("Z"):
51
+ return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
52
+ return datetime.fromisoformat(value).astimezone(timezone.utc)
53
+ except ValueError:
54
+ return None
55
+
56
+
57
+ def _snooze_active(state: dict[str, object], now: datetime) -> tuple[bool, str | None]:
58
+ raw = state.get("cloud_read_consent_snoozed_until")
59
+ if not isinstance(raw, str) or not raw:
60
+ return False, None
61
+ expiry = _parse_utc(raw)
62
+ if expiry is None or expiry <= now:
63
+ return False, None
64
+ return True, raw
65
+
66
+
67
+ def _cloud_read_prompt_for_path(path: Path) -> str:
68
+ effective, _ = load_effective_settings(path)
69
+ return cloud_read_prompt(settings=effective)
70
+
71
+
72
+ def _non_tty_message() -> str:
73
+ return (
74
+ "Cloud read consent is required for provider calls. "
75
+ "Re-run with --consent-cloud-reads after reviewing the scope."
76
+ )
77
+
78
+
79
+ def _storage_unavailable_message(path: Path) -> str:
80
+ return f"error: consent storage unavailable at {path}"
81
+
82
+
83
+ def require_cloud_read_consent(
84
+ *,
85
+ consent_cloud_reads: bool = False,
86
+ policy_evaluator: ManagedPolicyEvaluator | None = None,
87
+ stdin_is_tty: bool | None = None,
88
+ prompt_reader: Callable[[], str] | None = None,
89
+ settings_path: Path | None = None,
90
+ now_utc: Callable[[], datetime] | None = None,
91
+ quiet: bool = False,
92
+ ) -> CloudReadGateOutcome:
93
+ read_path = settings_path or settings_read_file()
94
+
95
+ def write_path() -> Path:
96
+ if settings_path is not None:
97
+ return settings_path
98
+ return prepare_settings_write()
99
+
100
+ # quiet is JSON mode: never block on input() even when stdin is a TTY.
101
+ interactive = not quiet and stdin_allows_prompt(stdin_is_tty=stdin_is_tty)
102
+ read_prompt = prompt_reader or (lambda: input())
103
+ evaluator = policy_evaluator or default_policy_evaluator()
104
+ now = _utc_now(now_utc)
105
+
106
+ policy = evaluator.evaluate_cloud_read()
107
+ if policy == "allow":
108
+ return CloudReadGateOutcome(True, 0)
109
+ if policy == "deny":
110
+ return _denied(0, "consent_managed_deny", "Cloud read consent denied by managed policy")
111
+
112
+ state = load_consent_state(read_path)
113
+ if state.get("cloud_read_consent"):
114
+ return CloudReadGateOutcome(True, 0)
115
+
116
+ if consent_cloud_reads:
117
+ path = write_path()
118
+ if not consent_storage_available(settings_path=path):
119
+ return _denied(
120
+ 1,
121
+ "consent_storage_unavailable",
122
+ _storage_unavailable_message(path),
123
+ quiet=quiet,
124
+ stderr=True,
125
+ )
126
+ scope = _cloud_read_prompt_for_path(path)
127
+ approved_text = f"{scope}\n{NON_INTERACTIVE_PROVENANCE}"
128
+ err = persist_cloud_read_grant(
129
+ path,
130
+ approved_text=approved_text,
131
+ approved_at=_format_utc(now),
132
+ )
133
+ if err is not None:
134
+ return _denied(
135
+ 1,
136
+ "consent_persist_failed",
137
+ f"error: {err.message}",
138
+ quiet=quiet,
139
+ stderr=True,
140
+ )
141
+ return CloudReadGateOutcome(True, 0)
142
+
143
+ snoozed, expiry = _snooze_active(state, now)
144
+ if snoozed and expiry is not None:
145
+ message = snooze_block_message(expiry)
146
+ if not quiet:
147
+ print(message)
148
+ return _denied(0, "consent_snoozed", message)
149
+
150
+ if not interactive:
151
+ return _denied(
152
+ 0,
153
+ "consent_required",
154
+ _non_tty_message(),
155
+ quiet=quiet,
156
+ stderr=True,
157
+ )
158
+
159
+ path = write_path()
160
+ if not consent_storage_available(settings_path=path):
161
+ return _denied(
162
+ 1,
163
+ "consent_storage_unavailable",
164
+ _storage_unavailable_message(path),
165
+ quiet=quiet,
166
+ stderr=True,
167
+ )
168
+
169
+ scope = _cloud_read_prompt_for_path(read_path)
170
+ invalid_answers = 0
171
+ while True:
172
+ if not quiet:
173
+ print(scope)
174
+ try:
175
+ choice = read_prompt().strip().lower()
176
+ except EOFError:
177
+ return _denied(
178
+ 0,
179
+ "consent_required",
180
+ _non_tty_message(),
181
+ quiet=quiet,
182
+ stderr=True,
183
+ )
184
+ if choice == "y":
185
+ err = persist_cloud_read_grant(
186
+ path,
187
+ approved_text=scope,
188
+ approved_at=_format_utc(now),
189
+ )
190
+ if err is not None:
191
+ return _denied(
192
+ 1,
193
+ "consent_persist_failed",
194
+ f"error: {err.message}",
195
+ quiet=quiet,
196
+ stderr=True,
197
+ )
198
+ return CloudReadGateOutcome(True, 0)
199
+ if choice == "n":
200
+ until = _format_utc(now + timedelta(days=7))
201
+ err = persist_cloud_read_snooze(path, snoozed_until=until)
202
+ if err is not None:
203
+ return _denied(
204
+ 1,
205
+ "consent_persist_failed",
206
+ f"error: {err.message}",
207
+ quiet=quiet,
208
+ stderr=True,
209
+ )
210
+ return _denied(0, "consent_snoozed", snooze_block_message(until))
211
+ if choice == "":
212
+ return _denied(
213
+ 0,
214
+ "consent_declined",
215
+ "Cloud read consent declined for this run",
216
+ )
217
+ invalid_answers += 1
218
+ if invalid_answers >= 3:
219
+ return _denied(
220
+ 0,
221
+ "consent_declined",
222
+ "Cloud read consent declined for this run",
223
+ )
224
+ if not quiet:
225
+ print(INVALID_CLOUD_READ_ANSWER)
226
+
227
+
228
+ def _denied(
229
+ exit_code: int,
230
+ reason_code: str,
231
+ message: str,
232
+ *,
233
+ quiet: bool = True,
234
+ stderr: bool = False,
235
+ ) -> CloudReadGateOutcome:
236
+ if not quiet:
237
+ print(message, file=sys.stderr if stderr else None)
238
+ return CloudReadGateOutcome(False, exit_code, reason_code, message)
@@ -0,0 +1,20 @@
1
+ """Managed-policy hook for cloud-read consent (FB-2 minimal default)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, Protocol
6
+
7
+ PolicyDecision = Literal["allow", "deny", "prompt"]
8
+
9
+
10
+ class ManagedPolicyEvaluator(Protocol):
11
+ def evaluate_cloud_read(self) -> PolicyDecision: ...
12
+
13
+
14
+ class _DefaultPolicyEvaluator:
15
+ def evaluate_cloud_read(self) -> PolicyDecision:
16
+ return "prompt"
17
+
18
+
19
+ def default_policy_evaluator() -> ManagedPolicyEvaluator:
20
+ return _DefaultPolicyEvaluator()
@@ -0,0 +1,61 @@
1
+ """Stable cloud-read consent prompt text (USER_JOURNEY.md section 4.1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from maproom.settings.model import product_version as read_product_version
6
+ from maproom.settings.product_versions import clamp_product_version
7
+
8
+ _CLOUD_READ_SCOPE = (
9
+ "Maproom needs to make read-only AWS/Azure calls using your current CLI login to\n"
10
+ "inspect identity, instance details, utilization, reservations, and quotas.\n"
11
+ )
12
+
13
+ _QUOTA_WRITE_ACK_LINE = (
14
+ "Reads only: Maproom's one write (a quota request) is confirmed separately, every time.\n"
15
+ )
16
+
17
+ _CLOUD_READ_FOOTER = (
18
+ "Run maproom privacy before answering.\n"
19
+ "Allow cloud reads? [y = allow and save until revoked / Enter = not now / "
20
+ "n = don't ask for 7 days]"
21
+ )
22
+
23
+ QUOTA_MANAGEMENT_MIN_PRODUCT_VERSION = 6
24
+
25
+ CLOUD_READ_PROMPT = _CLOUD_READ_SCOPE + _QUOTA_WRITE_ACK_LINE + _CLOUD_READ_FOOTER
26
+
27
+ INVALID_CLOUD_READ_ANSWER = (
28
+ "Answer y to allow and save until revoked, n to snooze 7 days, "
29
+ "or press Enter to decline this run."
30
+ )
31
+
32
+ NON_INTERACTIVE_PROVENANCE = "granted via --consent-cloud-reads (non-interactive)"
33
+
34
+ CLOUD_READ_FLAG_GRANT_LINE = (
35
+ "Cloud reads granted for this run via --consent-cloud-reads."
36
+ )
37
+
38
+
39
+ def cloud_read_prompt(
40
+ *,
41
+ product_version: int | None = None,
42
+ settings: dict | None = None,
43
+ ) -> str:
44
+ """Return cloud-read consent copy for the operator's current recommendation level."""
45
+ if product_version is not None:
46
+ version = clamp_product_version(product_version)
47
+ elif settings is not None:
48
+ version = clamp_product_version(settings.get("product_version", 1))
49
+ else:
50
+ version = read_product_version()
51
+ body = _CLOUD_READ_SCOPE
52
+ if version >= QUOTA_MANAGEMENT_MIN_PRODUCT_VERSION:
53
+ body += _QUOTA_WRITE_ACK_LINE
54
+ return body + _CLOUD_READ_FOOTER
55
+
56
+
57
+ def snooze_block_message(expiry: str) -> str:
58
+ return (
59
+ f"Cloud read consent snoozed until {expiry}. "
60
+ "Grant with: maproom settings set cloud_read_consent true"
61
+ )
@@ -0,0 +1,318 @@
1
+ """Service-upload consent gate before recommendation service calls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from typing import Callable
11
+
12
+ from maproom.consent.stdin import stdin_allows_prompt
13
+ from maproom.consent.service_upload_prompt import (
14
+ SERVICE_UPLOAD_NON_INTERACTIVE_PROVENANCE,
15
+ service_upload_prompt,
16
+ )
17
+ from maproom.consent.storage import consent_storage_available
18
+ from maproom.paths import prepare_settings_write, settings_read_file
19
+ from maproom.analyze.fleetfit_policy import (
20
+ FLEETFIT_POLICY_ACCEPT_CMD,
21
+ persist_fleetfit_policy_grant,
22
+ stored_fleetfit_policy_id,
23
+ )
24
+ from maproom.settings.model import load_effective_settings, load_service_upload_state
25
+ from maproom.settings.write import (
26
+ SettingsWriteError,
27
+ persist_service_upload_decline,
28
+ persist_service_upload_grant,
29
+ )
30
+
31
+ FLEETFIT_POLICY_READ_CMD = "maproom privacy fleetfit"
32
+ FLEETFIT_POLICY_ACTION = (
33
+ f"Read the policy with {FLEETFIT_POLICY_READ_CMD}, "
34
+ f"or record acceptance with {FLEETFIT_POLICY_ACCEPT_CMD}."
35
+ )
36
+
37
+
38
+ def fleetfit_policy_accept_question(policy_id: str) -> str:
39
+ return (
40
+ f"Accept FleetFit policy {policy_id} so Maproom can send a closed summary "
41
+ "of this run and receive a recommendation?"
42
+ )
43
+
44
+
45
+ def fleetfit_missing_policy_message() -> str:
46
+ return (
47
+ "Service-upload consent is on, but no FleetFit handling policy is recorded. "
48
+ + FLEETFIT_POLICY_ACTION
49
+ )
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class ServiceUploadGateOutcome:
54
+ upload_allowed: bool
55
+ exit_code: int
56
+ reason_code: str | None = None
57
+ message: str | None = None
58
+
59
+
60
+ def _utc_now(now_utc: Callable[[], datetime] | None = None) -> datetime:
61
+ if now_utc is not None:
62
+ return now_utc()
63
+ return datetime.now(timezone.utc)
64
+
65
+
66
+ def _format_utc(ts: datetime) -> str:
67
+ return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
68
+
69
+
70
+ def _storage_unavailable_message(path: Path) -> str:
71
+ return f"error: consent storage unavailable at {path}"
72
+
73
+
74
+ def _fixture_requests_upload() -> bool:
75
+ keys = (
76
+ "MAPROOM_SPOT_FIXTURE",
77
+ "MAPROOM_SIZE_FIXTURE",
78
+ "MAPROOM_SERIES_FIXTURE",
79
+ "MAPROOM_RECOMMEND_FIXTURE",
80
+ "MAPROOM_COVER_FIXTURE",
81
+ "MAPROOM_SAFE_MOVES_FIXTURE",
82
+ "MAPROOM_QUOTA_FIXTURE",
83
+ )
84
+ return any(os.environ.get(key, "").strip() for key in keys)
85
+
86
+
87
+ def _maybe_grant_mock_fleetfit_policy(path: Path) -> None:
88
+ if not _fixture_requests_upload():
89
+ return
90
+ settings, _ = load_effective_settings(path)
91
+ if stored_fleetfit_policy_id(settings):
92
+ return
93
+ persist_fleetfit_policy_grant(
94
+ path,
95
+ policy_id="mock-handling",
96
+ policy_url="fixture://evaluator/mock-handling.json",
97
+ )
98
+
99
+
100
+ def _print_fleetfit_handling_policy(
101
+ policy: dict[str, object],
102
+ *,
103
+ settings: dict[str, object],
104
+ ) -> None:
105
+ from maproom.privacy.fleetfit_statement import format_fleetfit_tty
106
+
107
+ print(format_fleetfit_tty(policy, settings=settings), end="")
108
+
109
+
110
+ def _interactive_fleetfit_policy_prompt(
111
+ path: Path,
112
+ *,
113
+ settings: dict[str, object],
114
+ prompt_reader: Callable[[], str],
115
+ now: datetime,
116
+ ) -> bool:
117
+ from maproom.privacy.fleetfit_policy import FleetFitPolicyFetchError, fetch_current_handling_policy
118
+
119
+ print("Loading the FleetFit handling policy...", flush=True)
120
+ try:
121
+ policy = fetch_current_handling_policy(settings)
122
+ except FleetFitPolicyFetchError as exc:
123
+ print(f"Could not load the FleetFit handling policy: {exc}", file=sys.stderr)
124
+ return False
125
+ policy_id = policy.get("policy_id")
126
+ if not isinstance(policy_id, str) or not policy_id.strip():
127
+ print("Could not load the FleetFit handling policy.", file=sys.stderr)
128
+ return False
129
+ stored = stored_fleetfit_policy_id(settings)
130
+ if stored == policy_id.strip():
131
+ return True
132
+ _print_fleetfit_handling_policy(policy, settings=settings)
133
+ print()
134
+ print(fleetfit_policy_accept_question(policy_id))
135
+ print("y = yes, Enter = not now")
136
+ try:
137
+ answer = prompt_reader().strip().lower()
138
+ except EOFError:
139
+ return False
140
+ if answer not in {"y", "yes"}:
141
+ return False
142
+ err = persist_fleetfit_policy_grant(
143
+ path,
144
+ policy_id=policy_id.strip(),
145
+ policy_url=str(policy.get("document_url") or ""),
146
+ granted_at=_format_utc(now),
147
+ )
148
+ if err is not None:
149
+ print(f"error: {err.message}", file=sys.stderr)
150
+ return False
151
+ from maproom.analyze.workset import note_progress
152
+
153
+ note_progress("FleetFit policy accepted; continuing this analyze run.")
154
+ settings_after, _ = load_effective_settings(path)
155
+ return bool(stored_fleetfit_policy_id(settings_after))
156
+
157
+
158
+ def _fleetfit_policy_gate_outcome(
159
+ read_path: Path,
160
+ write_path: Callable[[], Path],
161
+ *,
162
+ interactive: bool,
163
+ quiet: bool,
164
+ prompt_reader: Callable[[], str],
165
+ now: datetime,
166
+ ) -> ServiceUploadGateOutcome:
167
+ settings, _ = load_effective_settings(read_path)
168
+ if stored_fleetfit_policy_id(settings):
169
+ return ServiceUploadGateOutcome(True, 0)
170
+ if not interactive or quiet:
171
+ if not quiet:
172
+ print(fleetfit_missing_policy_message(), file=sys.stderr)
173
+ return ServiceUploadGateOutcome(False, 0, "upload_missing_policy")
174
+ path = write_path()
175
+ if not consent_storage_available(settings_path=path):
176
+ message = _storage_unavailable_message(path)
177
+ print(message, file=sys.stderr)
178
+ return ServiceUploadGateOutcome(False, 1, "consent_storage_unavailable", message)
179
+ if _interactive_fleetfit_policy_prompt(
180
+ path,
181
+ settings=settings,
182
+ prompt_reader=prompt_reader,
183
+ now=now,
184
+ ):
185
+ return ServiceUploadGateOutcome(True, 0)
186
+ return ServiceUploadGateOutcome(False, 0, "upload_missing_policy")
187
+
188
+
189
+ def _non_tty_message() -> str:
190
+ return (
191
+ "Service-upload consent is required for personalized recommendations. "
192
+ "Re-run with --consent-fleetfit-recommendations after reviewing the scope, "
193
+ "or omit the flag to receive a local assessment."
194
+ )
195
+
196
+
197
+ def require_service_upload_consent(
198
+ *,
199
+ consent_fleetfit_recommendations: bool = False,
200
+ stdin_is_tty: bool | None = None,
201
+ prompt_reader: Callable[[], str] | None = None,
202
+ settings_path: Path | None = None,
203
+ now_utc: Callable[[], datetime] | None = None,
204
+ quiet: bool = False,
205
+ ) -> ServiceUploadGateOutcome:
206
+ """Decide whether analyze may call the recommendation service."""
207
+ read_path = settings_path or settings_read_file()
208
+
209
+ def write_path() -> Path:
210
+ if settings_path is not None:
211
+ return settings_path
212
+ return prepare_settings_write()
213
+
214
+ interactive = stdin_allows_prompt(stdin_is_tty=stdin_is_tty)
215
+ read_prompt = prompt_reader or (lambda: input())
216
+ now = _utc_now(now_utc)
217
+ state = load_service_upload_state(read_path)
218
+ settings, _ = load_effective_settings(read_path)
219
+
220
+ if state.get("service_upload_consent"):
221
+ return _fleetfit_policy_gate_outcome(
222
+ read_path,
223
+ write_path,
224
+ interactive=interactive,
225
+ quiet=quiet,
226
+ prompt_reader=read_prompt,
227
+ now=now,
228
+ )
229
+
230
+ if consent_fleetfit_recommendations:
231
+ path = write_path()
232
+ if not consent_storage_available(settings_path=path):
233
+ message = _storage_unavailable_message(path)
234
+ if not quiet:
235
+ print(message, file=sys.stderr)
236
+ return ServiceUploadGateOutcome(False, 1, "consent_storage_unavailable", message)
237
+ fleetfit_settings = dict(settings or {})
238
+ if int(fleetfit_settings.get("product_version", 1)) < 2:
239
+ fleetfit_settings["product_version"] = 2
240
+ prompt = service_upload_prompt(settings=fleetfit_settings)
241
+ if not quiet:
242
+ print(prompt)
243
+ approved_text = f"{prompt}\n{SERVICE_UPLOAD_NON_INTERACTIVE_PROVENANCE}"
244
+ err = persist_service_upload_grant(
245
+ path,
246
+ approved_text=approved_text,
247
+ approved_at=_format_utc(now),
248
+ )
249
+ if err is not None:
250
+ message = f"error: {err.message}"
251
+ if not quiet:
252
+ print(message, file=sys.stderr)
253
+ return ServiceUploadGateOutcome(False, 1, "consent_persist_failed", message)
254
+ _maybe_grant_mock_fleetfit_policy(path)
255
+ return _fleetfit_policy_gate_outcome(
256
+ path,
257
+ write_path,
258
+ interactive=interactive,
259
+ quiet=quiet,
260
+ prompt_reader=read_prompt,
261
+ now=now,
262
+ )
263
+
264
+ if state.get("service_upload_consent_declined_at"):
265
+ return ServiceUploadGateOutcome(False, 0, "upload_declined_stored")
266
+
267
+ if quiet:
268
+ return ServiceUploadGateOutcome(False, 0, "upload_required")
269
+
270
+ if not interactive:
271
+ if not quiet:
272
+ print(_non_tty_message(), file=sys.stderr)
273
+ return ServiceUploadGateOutcome(False, 0, "upload_required")
274
+
275
+ path = write_path()
276
+ if not consent_storage_available(settings_path=path):
277
+ message = _storage_unavailable_message(path)
278
+ if not quiet:
279
+ print(message, file=sys.stderr)
280
+ return ServiceUploadGateOutcome(False, 1, "consent_storage_unavailable", message)
281
+
282
+ prompt = service_upload_prompt(settings=settings)
283
+ if not quiet:
284
+ print(prompt)
285
+ try:
286
+ choice = read_prompt().strip().lower()
287
+ except EOFError:
288
+ if not quiet:
289
+ print(_non_tty_message(), file=sys.stderr)
290
+ return ServiceUploadGateOutcome(False, 0, "upload_required")
291
+ if choice == "y":
292
+ err = persist_service_upload_grant(
293
+ path,
294
+ approved_text=prompt,
295
+ approved_at=_format_utc(now),
296
+ )
297
+ if err is not None:
298
+ message = f"error: {err.message}"
299
+ if not quiet:
300
+ print(message, file=sys.stderr)
301
+ return ServiceUploadGateOutcome(False, 1, "consent_persist_failed", message)
302
+ _maybe_grant_mock_fleetfit_policy(path)
303
+ return _fleetfit_policy_gate_outcome(
304
+ path,
305
+ write_path,
306
+ interactive=interactive,
307
+ quiet=quiet,
308
+ prompt_reader=read_prompt,
309
+ now=now,
310
+ )
311
+
312
+ err = persist_service_upload_decline(path, declined_at=_format_utc(now))
313
+ if err is not None:
314
+ message = f"error: {err.message}"
315
+ if not quiet:
316
+ print(message, file=sys.stderr)
317
+ return ServiceUploadGateOutcome(False, 1, "consent_persist_failed", message)
318
+ return ServiceUploadGateOutcome(False, 0, "upload_declined")
@@ -0,0 +1,62 @@
1
+ """Service-upload consent prompt text (USER_JOURNEY.md section 4.1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ from maproom.analyze.instance_price_client import resolve_instance_price_url
8
+ from maproom.analyze.recommend_client import resolve_recommend_url
9
+ from maproom.settings.model import product_version
10
+
11
+ SERVICE_UPLOAD_NON_INTERACTIVE_PROVENANCE = (
12
+ "granted via --consent-fleetfit-recommendations (non-interactive)"
13
+ )
14
+
15
+ LOCAL_ASSESSMENT_WARNING = (
16
+ "local price-and-compatibility assessment: personalized service recommendations unavailable"
17
+ )
18
+
19
+ ENABLE_UPLOADS_HINT = "Enable uploads with: maproom settings set service_upload_consent true"
20
+
21
+
22
+ def instance_price_destination_display(settings: dict | None) -> str:
23
+ fixture = os.environ.get("MAPROOM_INSTANCE_PRICE_FIXTURE", "").strip()
24
+ if fixture:
25
+ return f"local instance-price fixture ({fixture})"
26
+ resolved = resolve_instance_price_url(settings)
27
+ return resolved or ""
28
+
29
+
30
+ def service_upload_prompt(
31
+ *,
32
+ service_url: str | None = None,
33
+ settings: dict | None = None,
34
+ ) -> str:
35
+ version = int(settings.get("product_version", product_version())) if settings else product_version()
36
+ if version <= 1:
37
+ url = service_url or instance_price_destination_display(settings)
38
+ return (
39
+ "Maproom will send instance type, region, and platform "
40
+ f"to {url}.\n"
41
+ "The request does not include instance names, resource IDs, or account ids. "
42
+ "Details: maproom privacy analyze\n"
43
+ "\n"
44
+ "Allow instance-price uploads?\n"
45
+ " [y = send the closed body and use returned prices in the report]\n"
46
+ " [N = stay local and use the shipped price file only]:"
47
+ )
48
+ url = service_url
49
+ if url is None and settings is not None:
50
+ url = resolve_recommend_url(settings)
51
+ if not url:
52
+ url = "<recommendation service URL not configured>"
53
+ return (
54
+ "In order to make recommendations, Maproom will send region, AZ, instance_type,\n"
55
+ f"counts, reservation families and utilization, and quota limits and usage to {url}.\n"
56
+ "The summary never contains: names, resource IDs, account/subscription IDs, tags, addresses. "
57
+ "Details: maproom privacy\n"
58
+ "\n"
59
+ "Allow recommendation-service uploads?\n"
60
+ " [y = send the anonymous summary and get personalized recommendations]\n"
61
+ " [N = stay local and get a price-and-compatibility assessment only]:"
62
+ )