datasecops-cli 0.7.0b5__tar.gz → 0.7.0b7__tar.gz

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 (91) hide show
  1. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/CHANGELOG.md +21 -1
  2. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/PKG-INFO +3 -3
  3. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/README.md +2 -2
  4. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/docs/dcm.md +6 -0
  5. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/docs/getting-started.md +4 -0
  6. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/pyproject.toml +1 -1
  7. datasecops_cli-0.7.0b7/src/datasecops_cli/__init__.py +1 -0
  8. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/main.py +37 -7
  9. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/dbt_project_generator.py +191 -27
  10. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/download_service.py +8 -3
  11. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/snowflake_service.py +6 -1
  12. datasecops_cli-0.7.0b7/tests/test_dbt_project_generator_profiles.py +342 -0
  13. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_main.py +57 -2
  14. datasecops_cli-0.7.0b5/src/datasecops_cli/__init__.py +0 -1
  15. datasecops_cli-0.7.0b5/tests/test_dbt_project_generator_profiles.py +0 -150
  16. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/.github/workflows/auto-tag.yml +0 -0
  17. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/.github/workflows/publish-cli.yml +0 -0
  18. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/.github/workflows/test.yml +0 -0
  19. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/.gitignore +0 -0
  20. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/AGENTS.md +0 -0
  21. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/DEVELOPMENT.md +0 -0
  22. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/LICENSE +0 -0
  23. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/docs/git-operations.md +0 -0
  24. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/docs/legacy.md +0 -0
  25. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/docs/legacy_plan_of_action.md +0 -0
  26. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/docs/mcp-server.md +0 -0
  27. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/mcp-servers.json +0 -0
  28. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/scripts/vendor_model.py +0 -0
  29. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/setup.ps1 +0 -0
  30. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/setup.sh +0 -0
  31. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/config.py +0 -0
  32. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/menus/__init__.py +0 -0
  33. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/menus/configuration.py +0 -0
  34. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/menus/dcm_operations.py +0 -0
  35. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/menus/development.py +0 -0
  36. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/menus/downloads.py +0 -0
  37. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/menus/git_operations.py +0 -0
  38. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/models/__init__.py +0 -0
  39. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/models/git_helpers.py +0 -0
  40. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/models/project_config.py +0 -0
  41. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/__init__.py +0 -0
  42. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/bootstrap_service.py +0 -0
  43. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/dbt_runner.py +0 -0
  44. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/dcm_orchestrator.py +0 -0
  45. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/dcm_pipelines.py +0 -0
  46. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/dcm_registry.py +0 -0
  47. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/dcm_service.py +0 -0
  48. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/directory_scaffolder.py +0 -0
  49. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/git_service.py +0 -0
  50. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/linting_service.py +0 -0
  51. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/model_commands.py +0 -0
  52. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/pipeline_env.py +0 -0
  53. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/skill_service.py +0 -0
  54. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/services/upstream_service.py +0 -0
  55. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/utilities/__init__.py +0 -0
  56. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/utilities/display.py +0 -0
  57. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/utilities/file_utils.py +0 -0
  58. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/utilities/mcp.py +0 -0
  59. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_cli/utilities/yaml_utils.py +0 -0
  60. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_mcp/__init__.py +0 -0
  61. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_mcp/__main__.py +0 -0
  62. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_mcp/connection.py +0 -0
  63. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_mcp/server.py +0 -0
  64. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/__init__.py +0 -0
  65. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/convert.py +0 -0
  66. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/diagram.py +0 -0
  67. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/expand.py +0 -0
  68. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/extract.py +0 -0
  69. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/render.py +0 -0
  70. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/schema.py +0 -0
  71. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/scope.py +0 -0
  72. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/scripts.py +0 -0
  73. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/starter.py +0 -0
  74. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/templates/macros/role.sql +0 -0
  75. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/templates/macros/role_guard.sql +0 -0
  76. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/templates/macros/warehouse.sql +0 -0
  77. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/src/datasecops_model/validate.py +0 -0
  78. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/__init__.py +0 -0
  79. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_config.py +0 -0
  80. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_dbt_runner.py +0 -0
  81. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_dcm_model.py +0 -0
  82. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_dcm_orchestrator.py +0 -0
  83. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_dcm_service.py +0 -0
  84. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_download_service.py +0 -0
  85. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_file_utils.py +0 -0
  86. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_linting_service.py +0 -0
  87. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_model_commands.py +0 -0
  88. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_models.py +0 -0
  89. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_pipeline_env.py +0 -0
  90. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_version.py +0 -0
  91. {datasecops_cli-0.7.0b5 → datasecops_cli-0.7.0b7}/tests/test_yaml_utils.py +0 -0
@@ -4,7 +4,27 @@ All notable changes to the DataSecOps CLI are documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
- ## [0.7.0b5] - 2026-10-26
7
+ ### Fixed
8
+
9
+ - **`profiles.yml` writes could still widen file permissions or miss a symlinked file** — the atomic-replace temp file is now created with restrictive (`0600`) permissions and, if `profiles.yml` already existed, its mode is reapplied before the swap, instead of inheriting the process umask (typically `0644`) and exposing credentials. The profiles path itself (not just its parent directory) is now resolved before deriving the lock and temp-file paths, so a symlinked `profiles.yml` is replaced at its real location instead of only the link.
10
+
11
+ ## [0.7.0b7] - 2026-10-26
12
+
13
+ ### Added
14
+
15
+ - **The main menu's `dcm` option now configures DCM** — previously it only appeared once `dcm_enabled` was set by hand in `.datasecops.yml`, with no CLI path to set it. It now always appears; selecting it before DCM is enabled prompts for `dcm_enabled` and the other `dcm_*` settings (model file, project root, legacy security/platform dirs, default target) and writes them to `.datasecops.yml`, then selecting it again opens DCM Infrastructure Operations directly.
16
+
17
+ ### Fixed
18
+
19
+ - **`datasecops bootstrap`/`setup` crashed writing `profiles.yml`** — `get_connection_params()` returned raw `tomlkit` value objects from `connections.toml`; dumping those into `profiles.yml` wrote a `!!python/object/apply:tomlkit.items.String` tag that `yaml.safe_load()` can't read back, crashing the *next* run (and any other profile sharing that file) with a `ConstructorError`. Values are now unwrapped to plain Python types before use, and `write_profiles_yml()` repairs a file already corrupted by this bug via a restricted loader that only reconstructs the known legacy tomlkit tags (never arbitrary objects, unlike `yaml.unsafe_load`), instead of crashing on it. A tomlkit `Integer`/`Float`/`Bool` surviving repair unconverted (still tagged on the next write), and a per-type argument-position bug in that same repair loader, are also fixed.
20
+ - **`profiles.yml` writes could race, corrupt on interruption, or mangle binary values** — the read-modify-write is now held under an OS-level lock (`fcntl.flock`/`msvcrt.locking`, released automatically if the holding process dies, so no stale-lock heuristic is needed) instead of proceeding unlocked if contended; it raises instead of silently skipping the lock. The write itself goes through a temp file + atomic replace so a crash or I/O error mid-write can't leave a half-written file. The profiles directory is resolved (symlinks included) before deriving the lock path, so two paths that alias the same directory can't bypass each other's lock. A pre-existing binary (`!!binary`) value is no longer corrupted into its text `b'...'` representation if the file also needs repairing.
21
+ - **README overstated the Python requirement** — said "Python 3.11 or later" while `pyproject.toml` (`>=3.10`) and the rest of the docs said 3.10; nothing in the codebase actually needs 3.11, so the README is corrected to match.
22
+
23
+ ### Docs
24
+
25
+ - **Unblock `setup.ps1` before running it** — getting-started.md now runs `Unblock-File .\setup.ps1` first: Windows marks a downloaded script as coming from the internet, and the `RemoteSigned` execution policy then refuses it as "not digitally signed".
26
+
27
+ ## [0.7.0b6] - 2026-10-26
8
28
 
9
29
  ### Added
10
30
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datasecops-cli
3
- Version: 0.7.0b5
3
+ Version: 0.7.0b7
4
4
  Summary: DataSecOps Framework CLI for Snowflake Native App
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -20,11 +20,11 @@ Description-Content-Type: text/markdown
20
20
 
21
21
  # DataSecOps CLI
22
22
 
23
- A command-line interface for the [Data Engineers DataSecOps Native App](https://app.snowflake.com/marketplace) on Snowflake. Streamlines dbt development, source control workflows, and framework configuration management for teams using the DataSecOps Framework.
23
+ A command-line interface for the [Monitorial Orbit Native App](https://app.snowflake.com/marketplace) on Snowflake. Streamlines dbt development, source control workflows, and framework configuration management for teams using the DataSecOps Framework.
24
24
 
25
25
  ## What is this?
26
26
 
27
- The DataSecOps CLI is the local developer companion to the **Data Engineers DataSecOps Native App** — a Snowflake Native App that provides governance, configuration management, and standardised development workflows for data teams.
27
+ The DataSecOps CLI is the local developer companion to the **Monitorial Orbit Native App** — a Snowflake Native App that provides governance, configuration management, and standardised development workflows for data teams.
28
28
 
29
29
  This CLI connects to the native app and gives developers:
30
30
 
@@ -1,10 +1,10 @@
1
1
  # DataSecOps CLI
2
2
 
3
- A command-line interface for the [Data Engineers DataSecOps Native App](https://app.snowflake.com/marketplace) on Snowflake. Streamlines dbt development, source control workflows, and framework configuration management for teams using the DataSecOps Framework.
3
+ A command-line interface for the [Monitorial Orbit Native App](https://app.snowflake.com/marketplace) on Snowflake. Streamlines dbt development, source control workflows, and framework configuration management for teams using the DataSecOps Framework.
4
4
 
5
5
  ## What is this?
6
6
 
7
- The DataSecOps CLI is the local developer companion to the **Data Engineers DataSecOps Native App** — a Snowflake Native App that provides governance, configuration management, and standardised development workflows for data teams.
7
+ The DataSecOps CLI is the local developer companion to the **Monitorial Orbit Native App** — a Snowflake Native App that provides governance, configuration management, and standardised development workflows for data teams.
8
8
 
9
9
  This CLI connects to the native app and gives developers:
10
10
 
@@ -64,6 +64,12 @@ The usual way is the native app:
64
64
  object, owner, *CI deploys as*) and **Pipelines**. Apply, then Save.
65
65
  4. **View generated files**, then **Push to branch** and open the pull request.
66
66
 
67
+ The CLI's interactive main menu only shows **DCM Infrastructure Operations** once `dcm_enabled`
68
+ is set in `.datasecops.yml`. Choosing **dcm** from the main menu before that walks you through
69
+ setting `dcm_enabled` and the other `dcm_*` settings (model file, project root, legacy
70
+ security/platform dirs, default target) and writes them to `.datasecops.yml` — no manual edit
71
+ needed. Selecting **dcm** again then opens DCM Infrastructure Operations directly.
72
+
67
73
  From the CLI:
68
74
 
69
75
  ```bash
@@ -46,9 +46,13 @@ Navigate to your dbt project root and run the setup script:
46
46
  **Windows (PowerShell):**
47
47
 
48
48
  ```powershell
49
+ Unblock-File .\setup.ps1
49
50
  .\setup.ps1
50
51
  ```
51
52
 
53
+ A downloaded script is marked as coming from the internet, and the `RemoteSigned` execution policy then
54
+ refuses it as "not digitally signed"; `Unblock-File` clears that mark.
55
+
52
56
  **Linux / macOS:**
53
57
 
54
58
  ```bash
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "datasecops-cli"
7
- version = "0.7.0b5"
7
+ version = "0.7.0b7"
8
8
  description = "DataSecOps Framework CLI for Snowflake Native App"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1 @@
1
+ __version__ = "0.7.0b7"
@@ -26,7 +26,8 @@ from datasecops_cli.menus.configuration import ConfigurationMenu
26
26
  from datasecops_cli.menus.dcm_operations import DcmOperationsMenu
27
27
  from datasecops_cli.utilities.display import (
28
28
  clear, section_header, display_action_header, menu_option, get_input_number,
29
- info_line, warning_line, error_line, success_line, complete_action
29
+ info_line, warning_line, error_line, success_line, complete_action,
30
+ get_input_string_or_default
30
31
  )
31
32
  from datasecops_cli.utilities.yaml_utils import write_datasecops_config
32
33
 
@@ -1254,12 +1255,20 @@ def _main_menu(config: Config, dbt_runner: DbtRunner, git_service: GitService,
1254
1255
  skill_targets=skill_targets, run_deps=run_deps,
1255
1256
  scaffold_dcm=scaffold_dcm)
1256
1257
 
1257
- elif option == 7 and dcm_service and config.datasecops.dcm_enabled:
1258
- dcm_menu = DcmOperationsMenu(
1259
- dcm_service, sf_service, profile_name,
1260
- datasecops_config=config.datasecops, config=config,
1261
- )
1262
- dcm_menu.show()
1258
+ elif option == 7:
1259
+ if not config.datasecops.dcm_enabled:
1260
+ _configure_dcm(config)
1261
+ try:
1262
+ dcm_service = DcmService(sf_service, dcm_registry.dcm_root(config), config.datasecops.connection_name)
1263
+ except ValueError as e:
1264
+ error_line(str(e))
1265
+ dcm_service = None
1266
+ if dcm_service and config.datasecops.dcm_enabled:
1267
+ dcm_menu = DcmOperationsMenu(
1268
+ dcm_service, sf_service, profile_name,
1269
+ datasecops_config=config.datasecops, config=config,
1270
+ )
1271
+ dcm_menu.show()
1263
1272
 
1264
1273
  elif option == 8 and has_outdated:
1265
1274
  _update_upstream_packages(config, dbt_runner, upstream_statuses)
@@ -1276,6 +1285,25 @@ def _main_menu(config: Config, dbt_runner: DbtRunner, git_service: GitService,
1276
1285
  info_line("Exiting DataSecOps Framework CLI")
1277
1286
 
1278
1287
 
1288
+ def _configure_dcm(config: Config) -> None:
1289
+ """Prompt for the dcm_* settings, enable DCM and persist to .datasecops.yml."""
1290
+ ds = config.datasecops
1291
+ section_header("Configure DCM")
1292
+ info_line("DCM is not yet enabled for this project. Enter the settings below "
1293
+ "(press Enter to keep the default).")
1294
+ info_line("")
1295
+
1296
+ ds.dcm_model_path = get_input_string_or_default("DCM model file", ds.dcm_model_path)
1297
+ ds.dcm_root = get_input_string_or_default("DCM project root (project dirs are relative to this)", ds.dcm_root)
1298
+ ds.dcm_security_dir = get_input_string_or_default("Legacy security project dir", ds.dcm_security_dir)
1299
+ ds.dcm_platform_dir = get_input_string_or_default("Legacy platform project dir", ds.dcm_platform_dir)
1300
+ ds.dcm_default_target = get_input_string_or_default("Default DCM target (blank for none)", ds.dcm_default_target)
1301
+ ds.dcm_enabled = True
1302
+
1303
+ write_datasecops_config(config.project_dir, ds.model_dump(exclude={"VALID_ENGINES"}))
1304
+ success_line("DCM enabled - .datasecops.yml updated.")
1305
+
1306
+
1279
1307
  def _show_main_menu(profile_name: str, git_service: GitService = None,
1280
1308
  upstream_statuses: list = None, dcm_enabled: bool = False):
1281
1309
  clear()
@@ -1290,6 +1318,8 @@ def _show_main_menu(profile_name: str, git_service: GitService = None,
1290
1318
  menu_option(6, "bootstrap - Set up a new dbt project with all framework config")
1291
1319
  if dcm_enabled:
1292
1320
  menu_option(7, "dcm - DCM Infrastructure Operations")
1321
+ else:
1322
+ menu_option(7, "dcm - Configure & enable DCM")
1293
1323
  if upstream_statuses and any(s.needs_update for s in upstream_statuses):
1294
1324
  menu_option(8, "update pkgs - Update upstream packages to latest versions")
1295
1325
  menu_option(0, "exit - Exit")
@@ -1,9 +1,19 @@
1
1
  """Generate dbt_project.yml matching the DataSecOps Framework skill specification."""
2
2
 
3
+ import contextlib
4
+ import os
3
5
  import re
6
+ import stat
7
+ import sys
8
+ import time
4
9
  import yaml
5
10
  from typing import Any
6
11
 
12
+ if sys.platform == "win32":
13
+ import msvcrt
14
+ else:
15
+ import fcntl
16
+
7
17
  from datasecops_cli.models.project_config import ProjectProfile, ProjectSettings
8
18
 
9
19
 
@@ -243,6 +253,135 @@ def generate_local_dev_target(
243
253
  return output
244
254
 
245
255
 
256
+ def _to_plain(value: Any) -> Any:
257
+ """Recursively strip non-standard object types (e.g. tomlkit's str/int/float/bool
258
+ subclasses) down to plain dict/list/str/int/float/bool/None, so the result is always
259
+ safe to `yaml.safe_load()` back after a `yaml.dump()` round-trip.
260
+
261
+ Each primitive is coerced with its own constructor (`bool(value)`, `int(value)`, etc.)
262
+ rather than returned as-is: `isinstance(value, int)` is true for a `tomlkit.items.Integer`
263
+ too, but the object itself is still that subclass, which `yaml.dump()` would still tag as
264
+ a Python object. `bool` is checked before `int`/`float` since `bool` is itself an `int`
265
+ subclass in Python. `bytes` (from a safe `!!binary` value, unrelated to tomlkit) is passed
266
+ through as-is rather than stringified, so an existing binary value in an untouched profile
267
+ isn't corrupted into its `b'...'` text representation. Any other (e.g. tomlkit's compound
268
+ Array/InlineTable/DateTime) type is unwrapped via its own `.unwrap()` if available,
269
+ falling back to a plain string.
270
+ """
271
+ if isinstance(value, dict):
272
+ return {k: _to_plain(v) for k, v in value.items()}
273
+ if isinstance(value, list):
274
+ return [_to_plain(v) for v in value]
275
+ if value is None:
276
+ return None
277
+ if isinstance(value, bool):
278
+ return bool(value)
279
+ if isinstance(value, int):
280
+ return int(value)
281
+ if isinstance(value, float):
282
+ return float(value)
283
+ if isinstance(value, bytes):
284
+ return bytes(value)
285
+ if isinstance(value, str):
286
+ return str(value)
287
+ if hasattr(value, "unwrap"):
288
+ return _to_plain(value.unwrap())
289
+ return str(value)
290
+
291
+
292
+ class _LegacyTomlkitSafeLoader(yaml.SafeLoader):
293
+ """A `SafeLoader` that additionally repairs the one known legacy corruption - a
294
+ `tomlkit.items.String` (or `.Integer`/`.Float`/`.Bool`) value dumped straight into
295
+ profiles.yml by an older CLI bug (fixed in `get_connection_params`) - without executing
296
+ any object constructor. Every other tag (including the nested `StringType`/`Trivia`
297
+ tags tomlkit's own `!!python/object/apply:tomlkit.items.String` sequence carries) is
298
+ still rejected exactly like `yaml.SafeLoader`, so this never introduces `yaml.unsafe_load`'s
299
+ arbitrary-code-execution risk: the extra constructors below only pick a single already-plain
300
+ scalar out of the YAML node by position, they never call into tomlkit (or any other) code.
301
+ """
302
+
303
+
304
+ def _construct_legacy_tomlkit_value(value_index: int):
305
+ """Build a constructor that picks tomlkit's plain value out of its apply-sequence by
306
+ position, for the given tomlkit item type's `__new__(cls, ...)` argument order:
307
+ `String(t, value, original, trivia)` -> value is arg 1; `Integer(value, trivia, raw)`,
308
+ `Float(value, trivia, raw)` and `Bool(value, trivia)` -> value is arg 0. The rest of each
309
+ sequence (StringType/Trivia tags) is tomlkit-internal bookkeeping we deliberately never
310
+ construct. `construct_object` (not `construct_scalar`) is used so the value's own tag
311
+ (str/int/float/bool, auto-resolved by the safe resolver) still picks the right
312
+ already-safe constructor, instead of collapsing everything to a string.
313
+ """
314
+ def _construct(loader: yaml.SafeLoader, node: yaml.Node) -> Any:
315
+ if not isinstance(node, yaml.SequenceNode) or len(node.value) <= value_index:
316
+ raise yaml.constructor.ConstructorError(
317
+ None, None, "unexpected legacy tomlkit value structure", node.start_mark)
318
+ return loader.construct_object(node.value[value_index], deep=True)
319
+ return _construct
320
+
321
+
322
+ _LEGACY_TOMLKIT_VALUE_INDEX = {"String": 1, "Integer": 0, "Float": 0, "Bool": 0}
323
+ for _tomlkit_type, _value_index in _LEGACY_TOMLKIT_VALUE_INDEX.items():
324
+ _LegacyTomlkitSafeLoader.add_constructor(
325
+ f"tag:yaml.org,2002:python/object/apply:tomlkit.items.{_tomlkit_type}",
326
+ _construct_legacy_tomlkit_value(_value_index),
327
+ )
328
+
329
+
330
+ def _load_profiles_yml_text(text: str) -> dict[str, Any]:
331
+ """Load an existing profiles.yml, tolerating a file corrupted by an older CLI bug that
332
+ wrote `!!python/object/apply` tags (tomlkit values dumped without being unwrapped first -
333
+ fixed in `get_connection_params`). `yaml.safe_load()` can't read those tags back; falling
334
+ back to `_LegacyTomlkitSafeLoader` repairs only that specific, known corruption - never
335
+ executing arbitrary code like `yaml.unsafe_load()` would - and the result is sanitized to
336
+ plain types so future writes round-trip through `safe_load` again."""
337
+ try:
338
+ return yaml.safe_load(text) or {}
339
+ except yaml.YAMLError:
340
+ return _to_plain(yaml.load(text, Loader=_LegacyTomlkitSafeLoader) or {})
341
+
342
+
343
+ @contextlib.contextmanager
344
+ def _locked_profiles_file(profiles_path, timeout: float = 10.0):
345
+ """OS-level advisory lock for profiles.yml's read-modify-write, so two concurrent
346
+ `setup`/`bootstrap` runs against the same file (e.g. two profiles sharing it, or two
347
+ terminals) don't read the same version and have the later write silently discard the
348
+ earlier one.
349
+
350
+ Holds `fcntl.flock` (POSIX) / `msvcrt.locking` (Windows) on a sibling `<profiles.yml>.lock`
351
+ file for the duration of the context - stdlib only, no extra dependency. Unlike a
352
+ marker-file-existence lock, this needs no "is it stale?" heuristic at all: the OS releases
353
+ the lock automatically if the holding process dies or its file descriptor is closed, so
354
+ there's no window for one waiter to mistake another's live lock for an abandoned one and
355
+ delete it out from under it. Raises `TimeoutError` rather than silently proceeding without
356
+ the lock if it can't be acquired in time.
357
+ """
358
+ lock_path = profiles_path.with_name(profiles_path.name + ".lock")
359
+ lock_file = open(lock_path, "a+")
360
+ try:
361
+ deadline = time.time() + timeout
362
+ while True:
363
+ try:
364
+ if sys.platform == "win32":
365
+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_NBLCK, 1)
366
+ else:
367
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
368
+ break
369
+ except OSError:
370
+ if time.time() >= deadline:
371
+ raise TimeoutError(f"timed out waiting for lock on {lock_path}") from None
372
+ time.sleep(0.05)
373
+ try:
374
+ yield
375
+ finally:
376
+ if sys.platform == "win32":
377
+ lock_file.seek(0)
378
+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
379
+ else:
380
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
381
+ finally:
382
+ lock_file.close()
383
+
384
+
246
385
  def write_profiles_yml(
247
386
  profiles_dir,
248
387
  profile_name: str,
@@ -265,35 +404,60 @@ def write_profiles_yml(
265
404
  """
266
405
  from pathlib import Path
267
406
 
407
+ # Resolved (symlinks included) so two paths that alias the same directory - e.g. a
408
+ # symlink and its target - always derive the same profiles.yml *and* the same lock
409
+ # file, instead of a concurrent writer through the other alias bypassing the lock.
410
+ # profiles.yml itself is resolved too: if it's a symlink, os.replace() must swap out
411
+ # its target, not the link, or the real file (and any writer reaching it directly)
412
+ # would be left out of sync.
268
413
  profiles_dir = Path(profiles_dir).expanduser()
269
- profiles_path = profiles_dir / "profiles.yml"
270
-
271
- existing_profiles: dict[str, Any] = {}
272
- if profiles_path.exists():
273
- existing_profiles = yaml.safe_load(profiles_path.read_text(encoding="utf-8")) or {}
274
-
275
- local_dev_output = generate_local_dev_target(profile, project_settings, connection_params, sandpit_name)
276
-
277
- if profile_name in existing_profiles:
278
- entry = existing_profiles[profile_name]
279
- entry.setdefault("outputs", {})
280
- entry["outputs"]["local-dev"] = local_dev_output
281
- # Always force the default target to local-dev: a bare `dbt run` with no --target
282
- # must use the developer's own identity, never a deployment target that happened
283
- # to be marked as the file's default (e.g. by a previous run or manual edit).
284
- entry["target"] = "local-dev"
285
- status = "updated"
286
- else:
287
- existing_profiles[profile_name] = {
288
- "target": "local-dev",
289
- "outputs": {"local-dev": local_dev_output},
290
- }
291
- status = "added"
292
-
293
414
  profiles_dir.mkdir(parents=True, exist_ok=True)
294
- profiles_path.write_text(
295
- yaml.dump(existing_profiles, default_flow_style=False, sort_keys=False), encoding="utf-8")
296
- return status
415
+ profiles_dir = profiles_dir.resolve()
416
+ profiles_path = (profiles_dir / "profiles.yml").resolve()
417
+
418
+ with _locked_profiles_file(profiles_path):
419
+ existing_profiles: dict[str, Any] = {}
420
+ if profiles_path.exists():
421
+ existing_profiles = _load_profiles_yml_text(profiles_path.read_text(encoding="utf-8"))
422
+
423
+ local_dev_output = generate_local_dev_target(profile, project_settings, connection_params, sandpit_name)
424
+
425
+ if profile_name in existing_profiles:
426
+ entry = existing_profiles[profile_name]
427
+ entry.setdefault("outputs", {})
428
+ entry["outputs"]["local-dev"] = local_dev_output
429
+ # Always force the default target to local-dev: a bare `dbt run` with no --target
430
+ # must use the developer's own identity, never a deployment target that happened
431
+ # to be marked as the file's default (e.g. by a previous run or manual edit).
432
+ entry["target"] = "local-dev"
433
+ status = "updated"
434
+ else:
435
+ existing_profiles[profile_name] = {
436
+ "target": "local-dev",
437
+ "outputs": {"local-dev": local_dev_output},
438
+ }
439
+ status = "added"
440
+
441
+ # Written to a temp file in the same directory and atomically swapped into place,
442
+ # so a crash or I/O error mid-write can never leave profiles.yml half-written, and a
443
+ # concurrent reader (e.g. dbt itself) never observes a partially-written file.
444
+ # Created with restrictive (0600) permissions and, if profiles.yml already existed,
445
+ # its mode is reapplied before the swap - otherwise the temp file would inherit the
446
+ # umask (typically 0644) and widen access to the credentials it contains.
447
+ new_content = yaml.dump(existing_profiles, default_flow_style=False, sort_keys=False)
448
+ existing_mode = stat.S_IMODE(profiles_path.stat().st_mode) if profiles_path.exists() else None
449
+ tmp_path = profiles_path.with_name(f".{profiles_path.name}.{os.getpid()}.tmp")
450
+ fd = os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
451
+ try:
452
+ with os.fdopen(fd, "w", encoding="utf-8") as tmp_file:
453
+ tmp_file.write(new_content)
454
+ except BaseException:
455
+ tmp_path.unlink(missing_ok=True)
456
+ raise
457
+ if existing_mode is not None:
458
+ os.chmod(tmp_path, existing_mode)
459
+ os.replace(tmp_path, profiles_path)
460
+ return status
297
461
 
298
462
 
299
463
  def generate_packages_yml(
@@ -331,9 +331,14 @@ class DownloadService:
331
331
  # sandpit database - deployment targets belong to the native app's CI pipeline.
332
332
  connection_params = get_connection_params(self.sf.config.connection_name)
333
333
  profiles_dir = Path(project_settings.profile_dir).expanduser()
334
- status = write_profiles_yml(
335
- profiles_dir, profile.profile_name, profile, project_settings,
336
- connection_params, self.sf.config.sandpit_name)
334
+ try:
335
+ status = write_profiles_yml(
336
+ profiles_dir, profile.profile_name, profile, project_settings,
337
+ connection_params, self.sf.config.sandpit_name)
338
+ except TimeoutError as e:
339
+ error_line(f"Could not write profiles.yml: {e}")
340
+ error_line("Another datasecops process may be writing the same profiles.yml - try again")
341
+ return False
337
342
  success_line(f"profiles.yml {status} in {profiles_dir}")
338
343
 
339
344
  # Generate .gitignore
@@ -21,13 +21,18 @@ def get_connection_params(connection_name: str) -> dict[str, Any]:
21
21
  """Raw connection parameters for a named Snowflake CLI connection, read directly
22
22
  from ~/.snowflake/connections.toml (no connection is established).
23
23
 
24
+ Values are unwrapped to plain Python types: the connector's TOML parser (tomlkit)
25
+ returns its own str/int/bool subclasses, which `yaml.dump()` serializes with a
26
+ `!!python/object/apply` tag that `yaml.safe_load()` can't read back.
27
+
24
28
  Returns an empty dict if the connection name isn't found or the config can't be read.
25
29
  """
26
30
  try:
27
31
  from snowflake.connector.config_manager import CONFIG_MANAGER
28
32
  CONFIG_MANAGER.read_config()
29
33
  connections = CONFIG_MANAGER["connections"]
30
- return dict(connections.get(connection_name, {}))
34
+ raw = connections.get(connection_name, {})
35
+ return {k: (v.unwrap() if hasattr(v, "unwrap") else v) for k, v in dict(raw).items()}
31
36
  except Exception:
32
37
  return {}
33
38