From 9ccbb995e0994f77579881464b7be53f78ee3c81 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 11 Nov 2026 19:31:27 +0000 Subject: [PATCH 1/9] docs(openspec): plan the YAML 1.2 read of each config file Plans #4481. --- .../.openspec.yaml | 3 + .../design.md | 20 ++++++ .../proposal.md | 41 +++++++++++ .../specs/config-commands/spec.md | 72 +++++++++++++++++++ .../tasks.md | 21 ++++++ 5 files changed, 157 insertions(+) create mode 100644 openspec/changes/4481-read-each-config-file-as-yaml/.openspec.yaml create mode 100644 openspec/changes/4481-read-each-config-file-as-yaml/design.md create mode 100644 openspec/changes/4481-read-each-config-file-as-yaml/proposal.md create mode 100644 openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md create mode 100644 openspec/changes/4481-read-each-config-file-as-yaml/tasks.md diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/.openspec.yaml b/openspec/changes/4481-read-each-config-file-as-yaml/.openspec.yaml new file mode 100644 index 0000000000..9d55295e5d --- /dev/null +++ b/openspec/changes/4481-read-each-config-file-as-yaml/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-11-11 +skip_specs: false diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/design.md b/openspec/changes/4481-read-each-config-file-as-yaml/design.md new file mode 100644 index 0000000000..dbe226055b --- /dev/null +++ b/openspec/changes/4481-read-each-config-file-as-yaml/design.md @@ -0,0 +1,20 @@ +# Design + +## Decisions + +- **The reader changes, not the writer and not the types.** The writer `round_trip.edit` writes YAML 1.2 with ruamel.yaml. Each reader of a config file now reads YAML 1.2 with the same library, so each string that a save writes loads as the same string. This fixes all string settings, not only the two mode fields. +- **One reader, `parse_config_yaml`, in `config/yaml_errors.py`.** It calls `YAML(typ="safe", pure=True).load(text)`. `pure=True` keeps the Python parser of YAML 1.2 when ruamel.yaml.clib is installed. A new `YAML` object for each call keeps the reader free of shared state between threads. +- **The import of ruamel.yaml stays inside the functions.** `parse_config_yaml`, `load_yaml` and `yaml_load_errors` import ruamel.yaml when they run. A command that reads no config file, such as `devops config --help`, does not import the 29 modules of ruamel.yaml. `config/write_history.py` imports `round_trip`, which already imports ruamel.yaml. +- **`load_yaml` catches the errors of ruamel.yaml.** `yaml_load_errors()` gives the `YAMLError` of ruamel.yaml and the errors of a value that the loader cannot build (`ValueError`, `LookupError`, `AttributeError`, `RecursionError`). `load_yaml` catches them for each parse, the round trip included, so its `errors` parameter goes. The rule of #1468 stays: the error names the file, the type of the error, and its line and column, and quotes no text of the file. The text of the file stays in the frame of the parse, which is not in the traceback of the error. +- **The mode types stay as they are.** `JevMode`, `DecisionMode` and the refusal of a bool of #4438 do not change. A bare `true` is a bool in YAML 1.2, so the scenario "The old bool is refused" of `roadmap-intake-jev` stays true. +- **The ConfigMap render reads only its config as YAML 1.2.** Kubernetes reads the manifest of the template, and its parser reads YAML 1.1, so the render reads the manifest with PyYAML. The config in the manifest is a devops-cli config file, so the render reads it with `parse_config_yaml`. The render writes the config with PyYAML, which quotes each word that YAML 1.1 reads as a bool or a number, such as `'off'`. The YAML 1.2 reader of the Service reads the same string. +- **The SSH key prefix reads the project config file as YAML 1.2.** `crypto/ssh_keys.py` reads `ssh.key_prefix` from a project config file without the settings load. It reads the same files, so it uses the same reader. It catches the same errors as before: a YAML error, an `OSError` and a `UnicodeDecodeError`. +- **A duplicate key stops the load.** The safe loader of ruamel.yaml refuses a key that a mapping holds two times, as YAML 1.2 requires. PyYAML kept the last value with no message. The error names the file, the line and the column, so a person can remove the duplicate. + +## Rejected alternatives + +- **A `BeforeValidator` on `JevMode` and `DecisionMode` that maps a bool to a mode.** The closed plan pull request #4599 proposed it. It fixes 2 of about 100 string settings: `devops config set search.language no` still writes `no` and stops each later load. It also makes `jev: true` and `jev: yes` load as `on`, the live mode, against #4438 and ADR 0019. +- **Quote the values in `round_trip.edit`.** Quotes cover only a file that the writer writes. A file that a person types, and the config of a ConfigMap, stay exposed. +- **A PyYAML loader subclass with the booleans of YAML 1.2.** It patches PyYAML and keeps two YAML versions in one process. Each other YAML 1.1 form, such as `12:30` as 750, still changes type. The import cost of ruamel.yaml (29 modules, only for a command that reads a config file) does not justify it. +- **Import ruamel.yaml at the top of `yaml_errors.py`.** The settings module imports `yaml_errors`. So each start that imports the settings module, such as `devops config --help`, would import the 29 modules of ruamel.yaml, also when it reads no config file. `python -X importtime` shows that `devops config --help` imports `devops_cli.config.settings` and does not import `ruamel.yaml`. +- **Write the config of the ConfigMap with ruamel.yaml too.** A prototype on the repository template wrote a different text: it folds the long telemetry URL at 80 columns and writes `jev: off` bare. The PyYAML writer quotes each word that YAML 1.1 reads as a bool or a number, so the YAML 1.2 reader reads the same value for each setting of the template. diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/proposal.md b/openspec/changes/4481-read-each-config-file-as-yaml/proposal.md new file mode 100644 index 0000000000..0e418a0cb1 --- /dev/null +++ b/openspec/changes/4481-read-each-config-file-as-yaml/proposal.md @@ -0,0 +1,41 @@ +# Proposal: #4481 + +## Why + +A bare `off` or `on` as the value of `roadmap.intake.jev` stops the settings load (#4481). The settings save writes a config file with ruamel.yaml, which writes YAML 1.2 (`round_trip.edit`). The readers read the file with PyYAML `yaml.safe_load`, which reads YAML 1.1. In YAML 1.1, a bare `off` is `false`, a bare `no` is `false` and a bare `12:30` is the number 750. So `devops config set roadmap.intake.jev off` writes `jev: off`, and the next load reads `false`, which the mode type refuses. The same defect occurs for each string setting: `devops config set search.language no` and `devops config set k8s.context 12:30` write the file and then stop each later load. + +## What Changes + +- Each reader of a config file reads it as YAML 1.2 with the safe loader of ruamel.yaml (`YAML(typ="safe", pure=True)`), the library that writes the file. The readers are the settings load (`settings._read_config_file`), the two readers of `write_history`, the audit of `devops config audit-keys`, the config in the ConfigMap template of `k8s/configmap.py`, and the project config read of the SSH key prefix (`crypto/ssh_keys.py`). +- `config/yaml_errors.py` holds the one YAML 1.2 reader, `parse_config_yaml`, and the errors of a load, `yaml_load_errors()`. `load_yaml` catches the `YAMLError` of ruamel.yaml in place of the error of PyYAML. Each function imports ruamel.yaml when it runs, so a command that reads no config file does not import it. +- A bare `off`, `on`, `yes` or `no` in a config file loads as a string. A key that a mapping holds two times stops the load with an error that names the file, the line and the column. `JevMode`, `DecisionMode` and the refusal of a bool stay as they are: a bare `true` is still a bool, and the mode types refuse it. +- The ConfigMap render reads the manifest of the template with PyYAML, because Kubernetes reads the manifest. Only the config in the manifest is read as YAML 1.2. +- `docs/CONFIGURATION.md` and `docs/roadmap/intake.md` state that a config file is read as YAML 1.2. +- These behaviors are observable (the settings load, `devops config set`, `devops config audit-keys`, the ConfigMap render and the SSH key prefix), so the change has a spec delta. + +## Capabilities + +- `config-commands`: ADDED requirements for the YAML 1.2 read of each config file. MODIFIED requirement "A write or an edit of a config file quotes no text of a file that a YAML parser cannot load", because no reader of a config file uses PyYAML after this change. + +## Impact + +- Each command that loads the settings imports ruamel.yaml when it reads a config file: 29 more modules. `uv run devops ci --only startup-imports` measures the start of the help commands. +- Values that change type, from the census of the committed config inputs: none. Values of the YAML 1.1 forms change: a bare `0755` loads as 755 and not as 493, a bare `1:30` loads as the string `1:30`, so a number setting refuses it, and a bare `1e3` loads as the number 1000.0. +- The change fits one pull request. + +## Feasibility + +The premise was confirmed with commands on PyYAML 6 and ruamel.yaml 0.19.1, the version that `pyproject.toml` pins: + +- `yaml.safe_load("jev: off")` gives `{'jev': False}`, and `YAML(typ="safe", pure=True).load("jev: off")` gives `{'jev': 'off'}`. The same holds for `on`, `yes` and `no`. `12:30` gives 750 with PyYAML and `'12:30'` with ruamel.yaml. +- A key that a mapping holds two times raises `DuplicateKeyError`, a `MarkedYAMLError` with a mark. `roadmap: [unclosed` raises `ParserError` with a mark. `!!int ` raises `ValueError`, `!!bool ` raises `KeyError`, and a document that nests too deep raises `RecursionError`, as with PyYAML. `!!timestamp ` raises `ConstructorError` with a mark, where PyYAML raised `AttributeError`. +- ruamel.yaml.clib is not installed. `pure=True` keeps the Python parser of YAML 1.2 also when it is installed: the deprecation text of `ruamel.yaml.main.safe_load` names `typ='safe', pure=True` as its replacement. +- Census of the readers: `git grep -nE 'yaml\.safe_load(_all)?\(' -- 'src/*.py'` gives 44 lines. 7 of them are in `src/devops_cli/config`, `commands/config.py`, `k8s/configmap.py` and `crypto/ssh_keys.py`: 6 read a config file, and 1 reads the Kubernetes manifest of the ConfigMap template and stays PyYAML. The other 37 lines read other files (manifests, rule packs, `labels.yml`, `.pre-commit-config.yaml`), not a config file of devops-cli. +- Census of the values: on `config.example.yaml` and the config in `k8s/devops/configmap.example.yaml`, 0 of 84 values change between the two readers. +- With `import devops_cli.config.settings` done first, `import ruamel.yaml` adds 29 modules. + +## Existing Tool Considered + +ruamel.yaml (`ruamel-yaml==0.19.1`), an open and maintained library that `pyproject.toml` already pins and that `round_trip.edit` uses to write the file. Its safe loader reads YAML 1.2, the version that the writer writes. The change builds no code to keep: each reader calls the loader of the library. + +The change deletes this internal code: the PyYAML imports of `config/settings.py` and `config/write_history.py`, the `errors` parameter of `load_yaml`, `_LOAD_ERRORS` of `config/round_trip.py` and `_AUDIT_READ_ERRORS` of `commands/config.py`. diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md b/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md new file mode 100644 index 0000000000..c42676acd8 --- /dev/null +++ b/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md @@ -0,0 +1,72 @@ +## ADDED Requirements + +### Requirement: The settings load reads a config file as YAML 1.2 +The settings load SHALL read each config file as YAML 1.2, the version that a settings save writes. A bare `off`, `on`, `yes` or `no` SHALL load as a string, and a bare `true` or `false` SHALL load as a bool. A key that a mapping holds two times SHALL stop the load with a configuration error that names the file, the line and the column, and that quotes no text of the file. + +#### Scenario: A bare off or on for the intake mode +- **WHEN** the active config file holds `roadmap.intake.jev` with the bare value `off`, or with the bare value `on` +- **THEN** `load_settings()` gives `roadmap.intake.jev` equal to that string + +#### Scenario: A bare off for a decision point +- **WHEN** the active config file holds `roadmap.decisions` with `stage.verify_screen: off` +- **THEN** `load_settings()` gives the mode `off` for `stage.verify_screen` + +#### Scenario: A YAML bool for the intake mode +- **WHEN** the active config file holds `roadmap.intake.jev: true` +- **THEN** `load_settings()` raises a validation error for the field `roadmap.intake.jev` + +#### Scenario: A key that a mapping holds two times +- **WHEN** the active config file holds `ai:`, ` provider: ollama` and ` provider: FAKE-value` +- **THEN** the load fails with the message `Cannot load the settings: is not valid YAML (DuplicateKeyError) at line 3, column 3.`, the error has no cause and no context, and no output holds `FAKE-value` + +### Requirement: devops config set writes a value that the next load reads as the same string +After `devops config set ` writes a string setting to the config file, the next settings load SHALL give the same string, also for a word that YAML 1.1 reads as a bool or a number. + +#### Scenario: A word that YAML 1.1 reads as a bool or a number +- **WHEN** `devops config set` runs with `roadmap.intake.jev off`, with `search.language no` or with `k8s.context 12:30` +- **THEN** the command exits 0, and `devops config get` of the key prints the value that was set + +### Requirement: The audit record of a config write compares the values as YAML 1.2 +The audit record of a config write SHALL read the file before and after the write as YAML 1.2, and it SHALL name only the keys whose values changed. + +#### Scenario: A quoted value that a write makes bare +- **WHEN** a write changes the line ` context: "12:30"` under `k8s:` to ` context: 12:30`, and changes nothing else +- **THEN** the audit record of the write names no changed key + +### Requirement: devops config audit-keys reads a config file as YAML 1.2 +`devops config audit-keys` SHALL read each config file as YAML 1.2. A credential whose bare value is a word that YAML 1.1 reads as `false`, such as `no`, SHALL count as a plaintext secret. + +#### Scenario: A credential with the bare value no +- **WHEN** the active config file holds `ai.api_key: no`, and `devops config audit-keys --json` runs +- **THEN** `plaintext_leaks` names `ai.api_key` of the file, `is_compliant` is false, and the command exits 1 + +### Requirement: The ConfigMap render reads the config of its template as YAML 1.2 +The ConfigMap render SHALL read the config in the ConfigMap template as YAML 1.2. It SHALL write the config so that a YAML 1.2 read of the rendered config gives the same value for each setting. + +#### Scenario: A bare off in the template +- **WHEN** the config of the ConfigMap template holds `roadmap.intake.jev: off` with no quotes +- **THEN** the render succeeds, and a YAML 1.2 read of the rendered config gives the string `off` for `roadmap.intake.jev` + +### Requirement: The SSH key prefix reads a project config file as YAML 1.2 +The SSH key prefix SHALL read `ssh.key_prefix` from a project config file as YAML 1.2. + +#### Scenario: A bare no as the key prefix of a project +- **WHEN** the project config file of a workspace holds `ssh.key_prefix: no` with no quotes, and no other source sets the prefix +- **THEN** the key prefix of the workspace is `no` + +## MODIFIED Requirements + +### Requirement: A write or an edit of a config file quotes no text of a file that a YAML parser cannot load +When devops-cli reads a config file without the settings load, and ruamel.yaml cannot load the file with the YAML 1.2 reader or with the round trip, the read SHALL fail with a configuration error. The message SHALL name the file and the type of the error, and the line and the column when the error gives them. The message, the exception chain of the error and the output of the command SHALL hold no text of the file. + +#### Scenario: A local tag that ruamel.yaml accepts and PyYAML does not +- **WHEN** the active config file holds `ai:`, ` provider: ollama` and ` api_key: !vault FAKE-value-tag`, and `devops config unset ai.provider` runs +- **THEN** the command exits 1 with the message `Cannot read the config file: is not valid YAML (ConstructorError) at line 3, column 12.`, the error has no cause and no context, no output holds `FAKE-value-tag`, and the file stays as it was + +#### Scenario: A tagged value that a parser cannot build +- **WHEN** the round trip finds or edits a key in a file that holds `api_key: !!int FAKE-value-int` or `api_key: !!bool FAKE-value-bool` +- **THEN** it fails with a configuration error that names the file and the type of the error, `ValueError` or `KeyError`, the error has no cause and no context, and no text of the error holds the value in any case + +#### Scenario: The audit record of a write +- **WHEN** the audit record of a write parses a file that holds `api_key: !vault FAKE-value-tag` +- **THEN** it fails with a configuration error that holds no text of the file diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md new file mode 100644 index 0000000000..63f65541a3 --- /dev/null +++ b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md @@ -0,0 +1,21 @@ +# Tasks + +## 1. Read each config file as YAML 1.2 + +Kind: behavior. Reads: `src/devops_cli/config/round_trip.py`. Changes: `src/devops_cli/config/yaml_errors.py`, `src/devops_cli/config/settings.py`, `src/devops_cli/config/write_history.py`, `src/devops_cli/config/round_trip.py`, `src/devops_cli/commands/config.py`, `src/devops_cli/k8s/configmap.py`, `src/devops_cli/crypto/ssh_keys.py`, `tests/config/test_config_file_yaml_1_2.py`, `tests/config/test_config_yaml_load_errors.py`, `tests/config/test_config_file_that_is_not_yaml.py`, `tests/config/test_config_write_history.py`, `tests/commands/test_config.py`, `tests/commands/test_config_audit_keys.py`, `tests/k8s/test_k8s_configmap.py`, `tests/crypto/test_ssh.py`. + +- [ ] 1.1 Write the failing tests: a bare `off` and `on` for `roadmap.intake.jev`, a bare `off` in `roadmap.decisions`, a YAML bool, and a duplicate key through the settings load; `devops config set` of `roadmap.intake.jev off`, `search.language no` and `k8s.context 12:30`; the audit record of a write; `devops config audit-keys` of a credential `no`; the ConfigMap render of a bare `off`; the SSH key prefix `no` of a project config file. + - Verification: `$ uv run devops ci test tests/config/test_config_file_yaml_1_2.py tests/commands/test_config.py tests/config/test_config_write_history.py tests/commands/test_config_audit_keys.py tests/k8s/test_k8s_configmap.py tests/crypto/test_ssh.py` +- [ ] 1.2 Add `parse_config_yaml` and `yaml_load_errors` to `config/yaml_errors.py`, make `load_yaml` catch the errors of ruamel.yaml, and remove its `errors` parameter. Read the config file with `parse_config_yaml` in `config/settings.py`, `config/write_history.py`, `commands/config.py`, `k8s/configmap.py` and `crypto/ssh_keys.py`. Remove `_LOAD_ERRORS` of `config/round_trip.py` and `_AUDIT_READ_ERRORS` of `commands/config.py`. Move the load error tests from PyYAML to the YAML 1.2 reader. + - Verification: `$ uv run devops ci test tests/config/test_config_file_yaml_1_2.py tests/commands/test_config.py tests/config/test_config_write_history.py tests/commands/test_config_audit_keys.py tests/k8s/test_k8s_configmap.py tests/crypto/test_ssh.py tests/config/test_config_yaml_load_errors.py tests/config/test_config_file_that_is_not_yaml.py` + +## 2. Documents + +Kind: documents. Changes: `src/devops_cli/docs/generator.py`, `docs/CONFIGURATION.md`, `docs/roadmap/intake.md`. + +- [ ] 2.1 State in the generated configuration reference (`docs/generator.py`, `docs/CONFIGURATION.md`) and in `docs/roadmap/intake.md` that a config file is read as YAML 1.2, so a bare `off`, `on`, `yes` or `no` is a string. + - Verification: `$ uv run devops docs generate --check` + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). From ca542e19b41f0bfdf488c6c9f7e84ce89ccb7353 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 11 Nov 2026 19:38:55 +0000 Subject: [PATCH 2/9] test(config): a config file is read as YAML 1.2 Refs #4481. --- .../tasks.md | 2 +- tests/commands/test_config.py | 19 +++++ tests/commands/test_config_audit_keys.py | 17 ++++ tests/config/test_config_file_yaml_1_2.py | 80 +++++++++++++++++++ tests/config/test_config_write_history.py | 14 +++- tests/crypto/test_ssh.py | 12 +++ tests/k8s/test_k8s_configmap.py | 12 +++ 7 files changed, 154 insertions(+), 2 deletions(-) create mode 100644 tests/config/test_config_file_yaml_1_2.py diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md index 63f65541a3..4a19a70f94 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md @@ -4,7 +4,7 @@ Kind: behavior. Reads: `src/devops_cli/config/round_trip.py`. Changes: `src/devops_cli/config/yaml_errors.py`, `src/devops_cli/config/settings.py`, `src/devops_cli/config/write_history.py`, `src/devops_cli/config/round_trip.py`, `src/devops_cli/commands/config.py`, `src/devops_cli/k8s/configmap.py`, `src/devops_cli/crypto/ssh_keys.py`, `tests/config/test_config_file_yaml_1_2.py`, `tests/config/test_config_yaml_load_errors.py`, `tests/config/test_config_file_that_is_not_yaml.py`, `tests/config/test_config_write_history.py`, `tests/commands/test_config.py`, `tests/commands/test_config_audit_keys.py`, `tests/k8s/test_k8s_configmap.py`, `tests/crypto/test_ssh.py`. -- [ ] 1.1 Write the failing tests: a bare `off` and `on` for `roadmap.intake.jev`, a bare `off` in `roadmap.decisions`, a YAML bool, and a duplicate key through the settings load; `devops config set` of `roadmap.intake.jev off`, `search.language no` and `k8s.context 12:30`; the audit record of a write; `devops config audit-keys` of a credential `no`; the ConfigMap render of a bare `off`; the SSH key prefix `no` of a project config file. +- [x] 1.1 Write the failing tests: a bare `off` and `on` for `roadmap.intake.jev`, a bare `off` in `roadmap.decisions`, a YAML bool, and a duplicate key through the settings load; `devops config set` of `roadmap.intake.jev off`, `search.language no` and `k8s.context 12:30`; the audit record of a write; `devops config audit-keys` of a credential `no`; the ConfigMap render of a bare `off`; the SSH key prefix `no` of a project config file. - Verification: `$ uv run devops ci test tests/config/test_config_file_yaml_1_2.py tests/commands/test_config.py tests/config/test_config_write_history.py tests/commands/test_config_audit_keys.py tests/k8s/test_k8s_configmap.py tests/crypto/test_ssh.py` - [ ] 1.2 Add `parse_config_yaml` and `yaml_load_errors` to `config/yaml_errors.py`, make `load_yaml` catch the errors of ruamel.yaml, and remove its `errors` parameter. Read the config file with `parse_config_yaml` in `config/settings.py`, `config/write_history.py`, `commands/config.py`, `k8s/configmap.py` and `crypto/ssh_keys.py`. Remove `_LOAD_ERRORS` of `config/round_trip.py` and `_AUDIT_READ_ERRORS` of `commands/config.py`. Move the load error tests from PyYAML to the YAML 1.2 reader. - Verification: `$ uv run devops ci test tests/config/test_config_file_yaml_1_2.py tests/commands/test_config.py tests/config/test_config_write_history.py tests/commands/test_config_audit_keys.py tests/k8s/test_k8s_configmap.py tests/crypto/test_ssh.py tests/config/test_config_yaml_load_errors.py tests/config/test_config_file_that_is_not_yaml.py` diff --git a/tests/commands/test_config.py b/tests/commands/test_config.py index 57dc2e319f..d7d358d112 100644 --- a/tests/commands/test_config.py +++ b/tests/commands/test_config.py @@ -242,6 +242,25 @@ def test_config_set_of_an_unknown_key_exits_1_before_any_prompt_and_names_the_si assert isolate_devops_cli_config.read_text(encoding="utf-8") == config_before +@pytest.mark.parametrize( + ("key", "value"), + [ + pytest.param("roadmap.intake.jev", "off", id="mode-off"), + pytest.param("search.language", "no", id="bool-word"), + pytest.param("k8s.context", "12:30", id="sexagesimal"), + ], +) +def test_config_set_of_a_word_that_yaml_1_1_reads_as_a_bool_or_a_number_loads_back_as_set( + cli: Any, key: str, value: str +) -> None: + """The save writes the value with no quotes, because it is a string in YAML 1.2. The load + reads the file as YAML 1.2 too, so it gets the same string (#4481).""" + result = cli("config", "set", key, value) + loaded = cli("config", "get", key) + + assert (result.exit_code, loaded.exit_code, loaded.output) == (0, 0, f"{value}\n") + + def test_config_get_of_an_unknown_key_names_the_similar_keys(cli: Any) -> None: result = cli("config", "get", "firecrawl.apikey") diff --git a/tests/commands/test_config_audit_keys.py b/tests/commands/test_config_audit_keys.py index 7126b8e3ce..0b3a734710 100644 --- a/tests/commands/test_config_audit_keys.py +++ b/tests/commands/test_config_audit_keys.py @@ -223,6 +223,23 @@ def test_config_audit_keys_passes_a_nested_credential_that_holds_no_value( assert (result.exit_code, data["is_compliant"], data["plaintext_leaks"]) == (0, True, []) +def test_config_audit_keys_finds_a_credential_whose_bare_value_yaml_1_1_reads_as_false( + cli: Callable[..., Any], isolate_devops_cli_config: Path +) -> None: + """YAML 1.2 reads a bare `no` as a string, so the credential holds a value in plaintext. YAML + 1.1 read it as `false`, and the audit found no leak (#4481).""" + isolate_devops_cli_config.write_text("ai:\n api_key: no\n", encoding="utf-8") + + result = cli("config", "audit-keys", "--json") + + data = json.loads(result.stdout) + assert (result.exit_code, data["is_compliant"], data["plaintext_leaks"]) == ( + 1, + False, + [f"{isolate_devops_cli_config.resolve()}:ai.api_key"], + ) + + def test_config_audit_keys_finds_no_secret_key_in_a_config_file_whose_document_is_a_list( tmp_path: Path, ) -> None: diff --git a/tests/config/test_config_file_yaml_1_2.py b/tests/config/test_config_file_yaml_1_2.py new file mode 100644 index 0000000000..a4cbfd4571 --- /dev/null +++ b/tests/config/test_config_file_yaml_1_2.py @@ -0,0 +1,80 @@ +"""The settings load reads a config file as YAML 1.2, the version that a settings save writes (#4481). + +A save writes the file with ruamel.yaml. YAML 1.2 reads a bare `off`, `on`, `yes` or `no` as a +string. YAML 1.1 reads them as bools, and a bare `12:30` as the number 750. So a value that a save +wrote changed type at the next load, and the load stopped. A bare `true` is a bool in both +versions, so a mode setting still refuses it. +""" + +from __future__ import annotations + +import traceback +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from devops_cli.config.settings import load_settings, reset_settings_cache +from devops_cli.exceptions import ConfigurationError + +_CREDENTIAL = "FAKE-value" + + +def _add(config_path: Path, text: str) -> None: + """Add `text`, which holds top-level keys that the file does not hold, to the active config + file. The keys of the floor stay, so the load reaches no service.""" + config_path.write_text(config_path.read_text(encoding="utf-8") + text, encoding="utf-8") + reset_settings_cache() + + +@pytest.mark.parametrize("mode", ["off", "on"]) +def test_a_bare_mode_of_the_intake_loads_as_the_mode( + isolate_devops_cli_config: Path, mode: str +) -> None: + _add(isolate_devops_cli_config, f"roadmap:\n intake:\n jev: {mode}\n") + + assert load_settings().roadmap.intake.jev == mode + + +def test_a_bare_off_for_a_decision_point_loads_as_the_mode_off( + isolate_devops_cli_config: Path, +) -> None: + _add(isolate_devops_cli_config, "roadmap:\n decisions:\n stage.verify_screen: off\n") + + assert load_settings().roadmap.decisions == {"stage.verify_screen": "off"} + + +def test_a_yaml_bool_for_the_intake_mode_is_refused(isolate_devops_cli_config: Path) -> None: + _add(isolate_devops_cli_config, "roadmap:\n intake:\n jev: true\n") + + with pytest.raises(ValidationError) as refused: + load_settings() + + assert [error["loc"] for error in refused.value.errors()] == [("roadmap", "intake", "jev")] + + +def test_a_key_that_a_mapping_holds_two_times_stops_the_load_and_quotes_no_text( + isolate_devops_cli_config: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """YAML 1.2 refuses a duplicate key. YAML 1.1 kept the last value with no message. The error + has no cause and no context, and no frame of its traceback holds the text of the file.""" + isolate_devops_cli_config.write_text( + f"ai:\n provider: ollama\n provider: {_CREDENTIAL}\n", encoding="utf-8" + ) + reset_settings_cache() + + with pytest.raises(ConfigurationError) as raised: + load_settings() + + error = raised.value + shown = "".join( + traceback.TracebackException.from_exception(error, capture_locals=True).format() + ) + captured = capsys.readouterr() + assert (error.message, error.__cause__, error.__context__) == ( + f"Cannot load the settings: {isolate_devops_cli_config} is not valid YAML " + "(DuplicateKeyError) at line 3, column 3.", + None, + None, + ) + assert [text for text in (shown, captured.out, captured.err) if _CREDENTIAL in text] == [] diff --git a/tests/config/test_config_write_history.py b/tests/config/test_config_write_history.py index f06b0d3844..36c3fcc98d 100644 --- a/tests/config/test_config_write_history.py +++ b/tests/config/test_config_write_history.py @@ -10,7 +10,7 @@ from typing import Any from devops_cli.config.settings import load_settings, save_settings -from devops_cli.config.write_history import _copy +from devops_cli.config.write_history import _copy, record_write from tests.support.config_writes import config_writes, written_keys from tests.support.fakes.clock import ClockFake @@ -118,6 +118,18 @@ def test_a_config_write_that_changes_no_byte_writes_nothing_and_records_nothing( assert config_writes(isolate_data_dir) == [] +def test_a_write_that_only_drops_the_quotes_of_a_value_records_no_changed_key( + tmp_path: Path, isolate_data_dir: Path +) -> None: + """`"12:30"` and a bare `12:30` are the same string in YAML 1.2, the version that a save + writes. YAML 1.1 reads the bare form as the number 750 (#4481).""" + config = tmp_path / "config.yaml" + + record_write(config, b'k8s:\n context: "12:30"\n', b"k8s:\n context: 12:30\n", None) + + assert written_keys(isolate_data_dir) == [[]] + + def test_config_set_records_its_command_and_writes_the_key_it_changed_alone( cli: Any, isolate_devops_cli_config: Path, isolate_data_dir: Path ) -> None: diff --git a/tests/crypto/test_ssh.py b/tests/crypto/test_ssh.py index 96701a91a8..82c85a7081 100755 --- a/tests/crypto/test_ssh.py +++ b/tests/crypto/test_ssh.py @@ -160,6 +160,18 @@ def test_a_config_file_in_a_directory_without_a_project_marker_names_no_prefix( assert get_ssh_key_prefix(workspace) == "my_plain_repo" +def test_a_bare_no_in_the_project_config_file_is_the_key_prefix(tmp_path: Path) -> None: + """YAML 1.2, the version that a settings save writes, reads a bare `no` as a string. YAML 1.1 + read it as `false`, so the key took the name of its directory (#4481).""" + from devops_cli.crypto.ssh_keys import get_ssh_key_prefix + + workspace = tmp_path / "my_plain_repo" + (workspace / ".git").mkdir(parents=True) + (workspace / "config.yaml").write_text("ssh:\n key_prefix: no\n", encoding="utf-8") + + assert get_ssh_key_prefix(workspace) == "no" + + def test_devcontainer_name_survives_urls_next_to_comments(tmp_path: Path) -> None: """Verify the devcontainer name is the prefix when a string holds `//` beside real comments. diff --git a/tests/k8s/test_k8s_configmap.py b/tests/k8s/test_k8s_configmap.py index dc2d70db23..a525a1f5f4 100644 --- a/tests/k8s/test_k8s_configmap.py +++ b/tests/k8s/test_k8s_configmap.py @@ -6,6 +6,7 @@ import pytest import yaml +from ruamel.yaml import YAML from devops_cli.config.settings import AITasksConfig, GitHubAppConfig, ServiceConfig, Settings from devops_cli.exceptions.k8s import KubernetesContextError @@ -76,6 +77,17 @@ def test_render_devops_configmap_substitutes_repos_and_the_github_app() -> None: ) +def test_a_bare_off_in_the_template_renders_a_config_whose_yaml_1_2_read_is_off() -> None: + """The template holds `jev: off` with no quotes. The render reads the config as YAML 1.2, as + the Service loads it, so the mode is the string `off` (#4481).""" + template = SAMPLE_TEMPLATE + " roadmap:\n intake:\n jev: off\n" + + rendered = render_devops_configmap_content(template, repos=["owner/repo"], github_app=APP) + + config = yaml.safe_load(rendered)["data"]["devops-cli.yaml"] + assert YAML(typ="safe", pure=True).load(config)["roadmap"]["intake"]["jev"] == "off" + + @pytest.mark.parametrize( ("repos", "github_app"), [([], APP), (["owner/repo"], GitHubAppConfig(app_id=1001, installation_id=42))], From 51d34d0883ac71e5ee99e59fd17cf50d5efdf333 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 11 Nov 2026 19:56:39 +0000 Subject: [PATCH 3/9] fix(config): read each config file as YAML 1.2 A settings save writes a config file with ruamel.yaml, which writes YAML 1.2. The readers used PyYAML, which reads YAML 1.1, so a bare off, on, yes, no or 12:30 that a save wrote changed type at the next load and stopped it. Each reader of a config file now reads it with the safe loader of ruamel.yaml. Refs #4481. --- .../design.md | 2 +- .../specs/config-commands/spec.md | 2 +- .../tasks.md | 2 +- src/devops_cli/commands/config.py | 21 ++--- src/devops_cli/config/round_trip.py | 10 +-- src/devops_cli/config/settings.py | 15 ++-- src/devops_cli/config/write_history.py | 15 ++-- src/devops_cli/config/yaml_errors.py | 80 ++++++++++++------- src/devops_cli/crypto/ssh_keys.py | 16 ++-- src/devops_cli/k8s/configmap.py | 11 ++- tests/commands/test_config_audit_keys.py | 7 +- .../test_config_file_that_is_not_yaml.py | 35 ++++---- tests/config/test_config_yaml_load_errors.py | 46 ++++++----- 13 files changed, 154 insertions(+), 108 deletions(-) diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/design.md b/openspec/changes/4481-read-each-config-file-as-yaml/design.md index dbe226055b..ff45d48298 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/design.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/design.md @@ -7,7 +7,7 @@ - **The import of ruamel.yaml stays inside the functions.** `parse_config_yaml`, `load_yaml` and `yaml_load_errors` import ruamel.yaml when they run. A command that reads no config file, such as `devops config --help`, does not import the 29 modules of ruamel.yaml. `config/write_history.py` imports `round_trip`, which already imports ruamel.yaml. - **`load_yaml` catches the errors of ruamel.yaml.** `yaml_load_errors()` gives the `YAMLError` of ruamel.yaml and the errors of a value that the loader cannot build (`ValueError`, `LookupError`, `AttributeError`, `RecursionError`). `load_yaml` catches them for each parse, the round trip included, so its `errors` parameter goes. The rule of #1468 stays: the error names the file, the type of the error, and its line and column, and quotes no text of the file. The text of the file stays in the frame of the parse, which is not in the traceback of the error. - **The mode types stay as they are.** `JevMode`, `DecisionMode` and the refusal of a bool of #4438 do not change. A bare `true` is a bool in YAML 1.2, so the scenario "The old bool is refused" of `roadmap-intake-jev` stays true. -- **The ConfigMap render reads only its config as YAML 1.2.** Kubernetes reads the manifest of the template, and its parser reads YAML 1.1, so the render reads the manifest with PyYAML. The config in the manifest is a devops-cli config file, so the render reads it with `parse_config_yaml`. The render writes the config with PyYAML, which quotes each word that YAML 1.1 reads as a bool or a number, such as `'off'`. The YAML 1.2 reader of the Service reads the same string. +- **The ConfigMap render reads only its config as YAML 1.2.** Kubernetes reads the manifest of the template, and its parser reads YAML 1.1, so the render reads the manifest with PyYAML. The config in the manifest is a devops-cli config file, so the render reads it with `parse_config_yaml`. The render writes the config with PyYAML, which quotes each word that YAML 1.1 reads as a bool or a number, such as `'off'`. The YAML 1.2 reader of the Service reads the same string. The render validates the settings of the YAML 1.2 read of the text that it writes, so it never writes a config that the Service cannot load. - **The SSH key prefix reads the project config file as YAML 1.2.** `crypto/ssh_keys.py` reads `ssh.key_prefix` from a project config file without the settings load. It reads the same files, so it uses the same reader. It catches the same errors as before: a YAML error, an `OSError` and a `UnicodeDecodeError`. - **A duplicate key stops the load.** The safe loader of ruamel.yaml refuses a key that a mapping holds two times, as YAML 1.2 requires. PyYAML kept the last value with no message. The error names the file, the line and the column, so a person can remove the duplicate. diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md b/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md index c42676acd8..739ee96771 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md @@ -41,7 +41,7 @@ The audit record of a config write SHALL read the file before and after the writ - **THEN** `plaintext_leaks` names `ai.api_key` of the file, `is_compliant` is false, and the command exits 1 ### Requirement: The ConfigMap render reads the config of its template as YAML 1.2 -The ConfigMap render SHALL read the config in the ConfigMap template as YAML 1.2. It SHALL write the config so that a YAML 1.2 read of the rendered config gives the same value for each setting. +The ConfigMap render SHALL read the config in the ConfigMap template as YAML 1.2. It SHALL validate the settings of the YAML 1.2 read of the config that it writes, which is the config that the Service loads. #### Scenario: A bare off in the template - **WHEN** the config of the ConfigMap template holds `roadmap.intake.jev: off` with no quotes diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md index 4a19a70f94..632a354ce9 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md @@ -6,7 +6,7 @@ Kind: behavior. Reads: `src/devops_cli/config/round_trip.py`. Changes: `src/devo - [x] 1.1 Write the failing tests: a bare `off` and `on` for `roadmap.intake.jev`, a bare `off` in `roadmap.decisions`, a YAML bool, and a duplicate key through the settings load; `devops config set` of `roadmap.intake.jev off`, `search.language no` and `k8s.context 12:30`; the audit record of a write; `devops config audit-keys` of a credential `no`; the ConfigMap render of a bare `off`; the SSH key prefix `no` of a project config file. - Verification: `$ uv run devops ci test tests/config/test_config_file_yaml_1_2.py tests/commands/test_config.py tests/config/test_config_write_history.py tests/commands/test_config_audit_keys.py tests/k8s/test_k8s_configmap.py tests/crypto/test_ssh.py` -- [ ] 1.2 Add `parse_config_yaml` and `yaml_load_errors` to `config/yaml_errors.py`, make `load_yaml` catch the errors of ruamel.yaml, and remove its `errors` parameter. Read the config file with `parse_config_yaml` in `config/settings.py`, `config/write_history.py`, `commands/config.py`, `k8s/configmap.py` and `crypto/ssh_keys.py`. Remove `_LOAD_ERRORS` of `config/round_trip.py` and `_AUDIT_READ_ERRORS` of `commands/config.py`. Move the load error tests from PyYAML to the YAML 1.2 reader. +- [x] 1.2 Add `parse_config_yaml` and `yaml_load_errors` to `config/yaml_errors.py`, make `load_yaml` catch the errors of ruamel.yaml, and remove its `errors` parameter. Read the config file with `parse_config_yaml` in `config/settings.py`, `config/write_history.py`, `commands/config.py`, `k8s/configmap.py` and `crypto/ssh_keys.py`. Remove `_LOAD_ERRORS` of `config/round_trip.py` and `_AUDIT_READ_ERRORS` of `commands/config.py`. Move the load error tests from PyYAML to the YAML 1.2 reader. - Verification: `$ uv run devops ci test tests/config/test_config_file_yaml_1_2.py tests/commands/test_config.py tests/config/test_config_write_history.py tests/commands/test_config_audit_keys.py tests/k8s/test_k8s_configmap.py tests/crypto/test_ssh.py tests/config/test_config_yaml_load_errors.py tests/config/test_config_file_that_is_not_yaml.py` ## 2. Documents diff --git a/src/devops_cli/commands/config.py b/src/devops_cli/commands/config.py index 0f1a75b542..4b9641564a 100755 --- a/src/devops_cli/commands/config.py +++ b/src/devops_cli/commands/config.py @@ -52,7 +52,11 @@ save_settings, similar_config_keys, ) -from devops_cli.config.yaml_errors import YAML_LOAD_ERRORS, yaml_error_location +from devops_cli.config.yaml_errors import ( + parse_config_yaml, + yaml_error_location, + yaml_load_errors, +) from devops_cli.core.binaries import check_binary from devops_cli.core.cli import new_typer from devops_cli.dry_run import is_dry_run, render_dry_run_result @@ -685,10 +689,6 @@ def audit_stream( # Command: devops config audit-keys # ============================================================================= -# The audit refuses the errors that the settings load refuses (#1468), and an error that stops the -# read of the file. -_AUDIT_READ_ERRORS: tuple[type[Exception], ...] = (*YAML_LOAD_ERRORS, OSError) - def _plaintext_secret_keys( node: dict[Any, Any], secret_options: frozenset[str], prefix: str = "" @@ -710,13 +710,14 @@ def _scan_yaml_for_secret_keys(cfg_file: Path) -> list[str] | None: or None if the file is unreadable. A leak names the full path: the global config file and a project config file can both have the - name ``config.yaml`` (#2426). A key is found at its full dotted key, at any depth (#2511). + name ``config.yaml`` (#2426). A key is found at its full dotted key, at any depth (#2511). The + audit reads the file as YAML 1.2, as the settings load does (#4481). It refuses the errors that + the load refuses (#1468), and an error that stops the read of the file. """ - import yaml - + read_errors: tuple[type[Exception], ...] = (*yaml_load_errors(), OSError) try: - raw_cfg = yaml.safe_load(cfg_file.read_text(encoding="utf-8")) or {} - except _AUDIT_READ_ERRORS as err: + raw_cfg = parse_config_yaml(cfg_file.read_text(encoding="utf-8")) or {} + except read_errors as err: # The message of the error and the mark of a YAML error quote the file's content, which # may hold the value. where = yaml_error_location(err) diff --git a/src/devops_cli/config/round_trip.py b/src/devops_cli/config/round_trip.py index 07f1f49563..bafc93d2aa 100644 --- a/src/devops_cli/config/round_trip.py +++ b/src/devops_cli/config/round_trip.py @@ -26,13 +26,13 @@ from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap, CommentedSeq -from ruamel.yaml.error import CommentMark, YAMLError +from ruamel.yaml.error import CommentMark from ruamel.yaml.events import DocumentStartEvent from ruamel.yaml.representer import RoundTripRepresenter from ruamel.yaml.tokens import CommentToken from ruamel.yaml.util import load_yaml_guess_indent -from devops_cli.config.yaml_errors import YAML_LOAD_ERRORS, load_yaml +from devops_cli.config.yaml_errors import load_yaml from devops_cli.exceptions import ConfigurationError from devops_cli.lang import ERRORS @@ -49,9 +49,6 @@ _SEQUENCE_SLOTS: Final = 2 _SEQUENCE_COMMENT: Final = 0 _NULL_TAG: Final = "tag:yaml.org,2002:null" -# The errors of a load: those of PyYAML, and `YAMLError` of ruamel.yaml. Both parsers raise -# `ValueError` or `KeyError` with the value in the message for a tag that they cannot build (#2451). -_LOAD_ERRORS: Final = (*YAML_LOAD_ERRORS, YAMLError) # The node that holds a comment: a mapping and a key, or a sequence and an index. _Owner = tuple[CommentedMap | CommentedSeq, Any] @@ -120,7 +117,7 @@ def parse() -> tuple[Any, Any, Any]: return document, sequence_indent, sequence_offset document, sequence_indent, sequence_offset = load_yaml( - parse, name=name, action=ERRORS.config.not_yaml_save, errors=_LOAD_ERRORS + parse, name=name, action=ERRORS.config.not_yaml_save ) head = "" if document is None: @@ -200,7 +197,6 @@ def find(text: str, dotted: str, *, name: str) -> tuple[KeyPath, int] | None: lambda: YAML(typ="rt").load(text), name=name, action=ERRORS.config.not_yaml_read, - errors=_LOAD_ERRORS, ) return _find(document, dotted, (), name=name) diff --git a/src/devops_cli/config/settings.py b/src/devops_cli/config/settings.py index 7c862ea6b0..c406832853 100644 --- a/src/devops_cli/config/settings.py +++ b/src/devops_cli/config/settings.py @@ -17,7 +17,6 @@ from typing import Annotated, Any import httpx2 -import yaml from pydantic import ( AfterValidator, AnyHttpUrl, @@ -158,7 +157,7 @@ setting_variables, ) from devops_cli.config.os_keyring import store_keyring_secret -from devops_cli.config.yaml_errors import load_yaml +from devops_cli.config.yaml_errors import load_yaml, parse_config_yaml from devops_cli.core.dns_names import OptionalConfiguredDomain from devops_cli.core.untrusted_trees import reads_untrusted_trees from devops_cli.exceptions import ConfigurationError @@ -1706,15 +1705,15 @@ def _stamps_are_settled(stamps: tuple[_FileStamp, _FileStamp]) -> bool: def _read_config_file(path: Path) -> Any: - """The YAML document of the config file `path`, or `{}` for an empty file. + """The YAML 1.2 document of the config file `path`, or `{}` for an empty file. - A file that is not valid YAML raises ConfigurationError that names the file, the type of the - error, and its line and column when the error has a mark, and quotes no text of the file - (`load_yaml`, #1468). An `OSError` names only the file and is not a YAML problem, so it goes - up as it is. + A settings save writes YAML 1.2, so the load reads the same version (#4481). A file that is not + valid YAML raises ConfigurationError that names the file, the type of the error, and its line + and column when the error has a mark, and quotes no text of the file (`load_yaml`, #1468). An + `OSError` names only the file and is not a YAML problem, so it goes up as it is. """ return load_yaml( - lambda: yaml.safe_load(path.read_text(encoding="utf-8")) or {}, + lambda: parse_config_yaml(path.read_text(encoding="utf-8")) or {}, name=str(path), action=ERRORS.config.not_yaml_load, ) diff --git a/src/devops_cli/config/write_history.py b/src/devops_cli/config/write_history.py index 8d819b9822..c21f202459 100644 --- a/src/devops_cli/config/write_history.py +++ b/src/devops_cli/config/write_history.py @@ -20,8 +20,6 @@ from pathlib import Path from typing import Any -import yaml - from devops_cli.config.constants import ( CONST_AUDIT_ACTION_CONFIG_WRITE, CONST_CONFIG_BACKUP_INFIX, @@ -30,7 +28,7 @@ CONST_CONFIG_REDACTED_VALUE, ) from devops_cli.config.round_trip import KeyPath, changes, edit, leaves -from devops_cli.config.yaml_errors import load_yaml +from devops_cli.config.yaml_errors import load_yaml, parse_config_yaml from devops_cli.exceptions import ConfigurationError from devops_cli.lang import ERRORS @@ -89,7 +87,9 @@ def redact_credentials(data: bytes, paths: Collection[KeyPath], *, name: str) -> that is not UTF-8 text, that is not YAML, or that holds no mapping. The error does not quote the data, which can hold a credential.""" loaded = load_yaml( - lambda: yaml.safe_load(data.decode("utf-8")), name=name, action=ERRORS.config.not_yaml_read + lambda: parse_config_yaml(data.decode("utf-8")), + name=name, + action=ERRORS.config.not_yaml_read, ) text = data.decode("utf-8") if loaded is None: @@ -171,10 +171,11 @@ def record_write(path: Path, previous: bytes | None, content: bytes, backup: Pat def _mapping(content: bytes | None, *, name: str) -> Mapping[str, Any]: - """The mapping that the config file `name` holds, or an empty one for no file or no mapping. - Content that PyYAML cannot load raises ConfigurationError, which quotes no text of it (#2451).""" + """The YAML 1.2 mapping that the config file `name` holds, or an empty one for no file or no + mapping. A save writes YAML 1.2, so a value that only lost its quotes is the same value (#4481). + Content that does not load raises ConfigurationError, which quotes no text of it (#2451).""" loaded = ( - load_yaml(lambda: yaml.safe_load(content), name=name, action=ERRORS.config.not_yaml_read) + load_yaml(lambda: parse_config_yaml(content), name=name, action=ERRORS.config.not_yaml_read) if content else None ) diff --git a/src/devops_cli/config/yaml_errors.py b/src/devops_cli/config/yaml_errors.py index 934df1a1d5..d0c34dcdaf 100644 --- a/src/devops_cli/config/yaml_errors.py +++ b/src/devops_cli/config/yaml_errors.py @@ -1,33 +1,40 @@ -"""One way to read a config file that a YAML parser cannot load (#2451). +"""One way to read a config file, and one way to report a config file that does not load (#2451, +#4481). -A config file can hold a credential. The message of a PyYAML error quotes the line where the parser -stopped, and the `buffer` of its mark holds the full text of the file. The safe loader of PyYAML and -the round-trip loader of ruamel.yaml also raise `ValueError`, `KeyError`, `IndexError` or -`AttributeError` for a tagged value that they cannot build, such as `!!int `, and the message -quotes the value. They raise `RecursionError` for a document that nests too deep. The decode of a -file that is not UTF-8 raises `UnicodeDecodeError`, whose `object` holds the bytes of the file. +A settings save writes a config file with ruamel.yaml, which writes YAML 1.2 (`round_trip`). So +`parse_config_yaml` reads a config file as YAML 1.2, with the safe loader of the same library. A +YAML 1.1 reader, such as PyYAML, reads a bare `off`, `on`, `yes` or `no` as a bool and a bare +`12:30` as the number 750, so a string that a save wrote changed type at the next load. + +A config file can hold a credential. The message of a YAML error quotes the line where the parser +stopped, and its mark holds the text of the file. The loaders of ruamel.yaml also raise +`ValueError`, `KeyError`, `IndexError` or `AttributeError` for a tagged value that they cannot +build, such as `!!int `, and the message quotes the value. They raise `RecursionError` for a +document that nests too deep. The decode of a file that is not UTF-8 raises `UnicodeDecodeError`, +whose `object` holds the bytes of the file. `load_yaml` turns each of these errors into one ConfigurationError that names the file, the type of the error, and its line and column when the error has a mark. The error quotes no text of the file. -It has no cause and no context that holds the first error. This module does not import ruamel.yaml, -which the start of every command would then load. A caller that parses with ruamel.yaml passes the -error class of ruamel.yaml in `errors`. +It has no cause and no context that holds the first error. + +Each function imports ruamel.yaml when it runs. The settings module imports this module, and the +import of ruamel.yaml adds 29 modules, so a command that reads no config file does not pay for it. """ from __future__ import annotations from collections.abc import Callable - -import yaml +from typing import Any, Final from devops_cli.exceptions import ConfigurationError from devops_cli.lang import ERRORS -# The errors of `yaml.safe_load` and of the UTF-8 decode: `UnicodeDecodeError` is a `ValueError`, -# and `KeyError` and `IndexError` are `LookupError`s. `tests/config/test_config_file_that_is_not_yaml.py` -# holds a file for each. An `OSError` names only the file, so it is not here and goes up. -YAML_LOAD_ERRORS: tuple[type[Exception], ...] = ( - yaml.YAMLError, +# The errors of a value that a loader cannot build, and of the UTF-8 decode: `UnicodeDecodeError` +# is a `ValueError`, and `KeyError` and `IndexError` are `LookupError`s. The round trip raises +# `AttributeError` for `!!omap `. `tests/config/test_config_file_that_is_not_yaml.py` and +# `tests/config/test_config_yaml_load_errors.py` hold a file for each. An `OSError` names only the +# file, so it is not here and goes up. +_BUILD_ERRORS: Final[tuple[type[Exception], ...]] = ( ValueError, LookupError, AttributeError, @@ -35,19 +42,34 @@ ) -def load_yaml[T]( - parse: Callable[[], T], - *, - name: str, - action: str, - errors: tuple[type[Exception], ...] = YAML_LOAD_ERRORS, -) -> T: +def yaml_load_errors() -> tuple[type[Exception], ...]: + """The errors of a load of a config file: the `YAMLError` of ruamel.yaml, and the errors of a + value that the loader cannot build.""" + from ruamel.yaml.error import YAMLError + + return (YAMLError, *_BUILD_ERRORS) + + +def parse_config_yaml(text: str | bytes) -> Any: + """The YAML 1.2 document of the config file text `text`, or None when it holds no document. + + The safe loader of ruamel.yaml builds only plain types. `pure=True` keeps the Python parser of + YAML 1.2 also when ruamel.yaml.clib is installed. A new loader for each call shares no state + between threads. A key that a mapping holds two times raises `DuplicateKeyError`. + """ + from ruamel.yaml import YAML + + return YAML(typ="safe", pure=True).load(text) + + +def load_yaml[T](parse: Callable[[], T], *, name: str, action: str) -> T: """The result of `parse`, which reads the YAML of the file `name`. - An error of `errors` raises ConfigurationError. Its message starts with `action`, such as - `Cannot read the config file`. The error is raised after the `except` block, so it has no cause - and no context. Another error, such as an `OSError`, goes up as it is. + An error of `yaml_load_errors()` raises ConfigurationError. Its message starts with `action`, + such as `Cannot read the config file`. The error is raised after the `except` block, so it has + no cause and no context. Another error, such as an `OSError`, goes up as it is. """ + errors = yaml_load_errors() try: return parse() except errors as exc: @@ -61,8 +83,8 @@ def load_yaml[T]( def yaml_error_location(exc: Exception) -> str: """` at line , column ` where a parser stopped, counted from 1, or "" when the error has - no mark. PyYAML and ruamel.yaml give the same `problem_mark`. A function reads it, so that no - frame of the traceback of the ConfigurationError holds the mark.""" + no mark. A function reads it, so that no frame of the traceback of the ConfigurationError holds + the mark.""" mark = getattr(exc, "problem_mark", None) if mark is None: return "" diff --git a/src/devops_cli/crypto/ssh_keys.py b/src/devops_cli/crypto/ssh_keys.py index a6e37de48d..b43550e710 100755 --- a/src/devops_cli/crypto/ssh_keys.py +++ b/src/devops_cli/crypto/ssh_keys.py @@ -37,13 +37,16 @@ def _sanitize_prefix(raw_prefix: str) -> str: def _extract_prefix_from_yaml(cfg_file: Path) -> str | None: - """Extract and sanitize key_prefix from a YAML config file.""" - import yaml + """Extract and sanitize key_prefix from a config file, read as YAML 1.2 as the settings load + reads it (#4481). The log of a file that does not load quotes no text of it.""" + from ruamel.yaml.error import YAMLError + + from devops_cli.config.yaml_errors import parse_config_yaml, yaml_error_location if not cfg_file.is_file(): return None try: - data = yaml.safe_load(cfg_file.read_text(encoding="utf-8")) or {} + data = parse_config_yaml(cfg_file.read_text(encoding="utf-8")) or {} if not isinstance(data, dict): return None ssh_conf = data.get("ssh", {}) @@ -53,8 +56,11 @@ def _extract_prefix_from_yaml(cfg_file: Path) -> str | None: elif data.get("key_prefix"): raw_prefix = data["key_prefix"] return _sanitize_prefix(str(raw_prefix)) if raw_prefix else None - except (yaml.YAMLError, OSError, UnicodeDecodeError) as exc: - logger.debug("Failed reading YAML key_prefix from %s: %s", cfg_file, exc) + except (YAMLError, OSError, UnicodeDecodeError) as exc: + where = yaml_error_location(exc) + logger.debug( + "Failed reading YAML key_prefix from %s: %s%s", cfg_file, type(exc).__name__, where + ) return None diff --git a/src/devops_cli/k8s/configmap.py b/src/devops_cli/k8s/configmap.py index 54e279a9e7..6fc142314c 100644 --- a/src/devops_cli/k8s/configmap.py +++ b/src/devops_cli/k8s/configmap.py @@ -10,6 +10,7 @@ from devops_cli.config.defaults import DEFAULT_K8S_DIR from devops_cli.config.settings import GitHubAppConfig, Settings, load_settings +from devops_cli.config.yaml_errors import parse_config_yaml from devops_cli.exceptions.k8s import KubernetesContextError _CONFIG_KEY = "devops-cli.yaml" @@ -64,13 +65,17 @@ def render_devops_configmap_content( """The ConfigMap template with its service section set to `repos` and `github_app`. The template's config is read as YAML and written again, so the applied ConfigMap does not - keep the template's comments. + keep the template's comments. Kubernetes reads the manifest, so the manifest is read with + PyYAML. The config in it is a config file of devops-cli, which the Service reads as YAML 1.2, + so the render reads it as YAML 1.2 too (#4481). PyYAML writes it again and quotes each word + that YAML 1.1 reads as a bool or a number, such as `'off'`. The render validates the YAML 1.2 + read of the text that it writes, which is the config that the Service loads. """ manifest = yaml.safe_load(template_content) data = manifest.get("data") if isinstance(manifest, dict) else None if not isinstance(data, dict): data = {} - config = yaml.safe_load(data.get(_CONFIG_KEY) or "") + config = parse_config_yaml(data.get(_CONFIG_KEY) or "") if not isinstance(config, dict) or not isinstance(config.get("service"), dict): raise KubernetesContextError( "Could not locate standard service configuration block in devops ConfigMap template." @@ -78,8 +83,8 @@ def render_devops_configmap_content( config["service"] = _service_block( repos, github_app, poll_interval_seconds, github_requests_per_hour ) - Settings.model_validate(config) data[_CONFIG_KEY] = yaml.dump(config, Dumper=_BlockDumper, sort_keys=False) + Settings.model_validate(parse_config_yaml(data[_CONFIG_KEY])) return yaml.dump(manifest, Dumper=_BlockDumper, sort_keys=False) diff --git a/tests/commands/test_config_audit_keys.py b/tests/commands/test_config_audit_keys.py index 0b3a734710..e528b6fc81 100644 --- a/tests/commands/test_config_audit_keys.py +++ b/tests/commands/test_config_audit_keys.py @@ -472,7 +472,7 @@ def test_the_help_of_audit_keys_and_unset_name_the_command_that_removes_a_leak( ), pytest.param( f"ai:\n api_key: !!timestamp {_LOADER_CREDENTIAL}\n".encode(), - "AttributeError", + "ConstructorError at line 2, column 12", id="timestamp", ), pytest.param( @@ -501,8 +501,9 @@ def test_config_audit_keys_reports_a_global_config_file_that_the_yaml_loader_can ) -> None: """The audit refuses the errors of the YAML loader that the settings load refuses (#1468). - The message of these errors quotes the value, so the audit names only the file and the type of - the error. It prints the full report and exits 1. + The message of these errors quotes the value, so the audit names only the file, the type of + the error, and its line and column when the error has a mark. It prints the full report and + exits 1. """ global_config = write_global_config(content).resolve() diff --git a/tests/config/test_config_file_that_is_not_yaml.py b/tests/config/test_config_file_that_is_not_yaml.py index c761bd2af5..1236f9e9f4 100644 --- a/tests/config/test_config_file_that_is_not_yaml.py +++ b/tests/config/test_config_file_that_is_not_yaml.py @@ -1,12 +1,12 @@ """A config file that is not valid YAML stops the settings from loading with an error that names the file, the line and the column, and that quotes no text of the file (#1468). -The error of PyYAML quotes the line where the parser stopped, and the `buffer` of its mark holds the -full text of the file. A malformed line is where a pasted credential usually is. The safe loader of -PyYAML also raises `ValueError`, `KeyError`, `IndexError` or `AttributeError` for a tagged value -that it cannot build, with the value in the message, and `RecursionError` for a document that nests -too deep. The decode of a file that is not UTF-8 raises `UnicodeDecodeError`, whose `object` holds -the bytes of the file. +The settings load reads the file as YAML 1.2 with the safe loader of ruamel.yaml (#4481). Its error +quotes the line where the parser stopped, and its mark holds the text of the file. A malformed line +is where a pasted credential usually is. The loader also raises `ValueError`, `KeyError` or +`IndexError` for a tagged value that it cannot build, with the value in the message, and +`RecursionError` for a document that nests too deep. The decode of a file that is not UTF-8 raises +`UnicodeDecodeError`, whose `object` holds the bytes of the file. """ from __future__ import annotations @@ -39,7 +39,7 @@ def test_a_config_file_that_is_not_yaml_names_its_file_line_and_column_and_quote isolate_devops_cli_config: Path, capsys: pytest.CaptureFixture[str] ) -> None: """The error has no cause and no context, so no traceback and no tool that walks the chain - gets the error of PyYAML. No frame of the traceback holds the error or its mark.""" + gets the error of the loader. No frame of the traceback holds the error or its mark.""" isolate_devops_cli_config.write_text(_NOT_YAML, encoding="utf-8") error, shown = _load_error() @@ -56,28 +56,32 @@ def test_a_config_file_that_is_not_yaml_names_its_file_line_and_column_and_quote @pytest.mark.parametrize( - ("content", "error_type"), + ("content", "error_type", "location"), [ - pytest.param(f"ai:\n api_key: !!int {_CREDENTIAL}\n".encode(), "ValueError", id="int"), - pytest.param(f"ai:\n api_key: !!bool {_CREDENTIAL}\n".encode(), "KeyError", id="bool"), + pytest.param(f"ai:\n api_key: !!int {_CREDENTIAL}\n".encode(), "ValueError", "", id="int"), + pytest.param(f"ai:\n api_key: !!bool {_CREDENTIAL}\n".encode(), "KeyError", "", id="bool"), pytest.param( f"ai:\n api_key: !!timestamp {_CREDENTIAL}\n".encode(), - "AttributeError", + "ConstructorError", + " at line 2, column 12", id="timestamp", ), pytest.param( f"ai:\n api_key: {_CREDENTIAL}\n timeout: !!int ''\n".encode(), "IndexError", + "", id="empty-int", ), pytest.param( f"ai:\n api_key: {_CREDENTIAL}\n tags: {'[' * 10_000}{']' * 10_000}\n".encode(), "RecursionError", + "", id="deep-nesting", ), pytest.param( f"ai:\n api_key: {_CREDENTIAL}\xe9\n".encode("latin-1"), "UnicodeDecodeError", + "", id="not-utf-8", ), ], @@ -87,16 +91,19 @@ def test_a_config_file_that_the_yaml_loader_cannot_load_names_its_file_and_quote capsys: pytest.CaptureFixture[str], content: bytes, error_type: str, + location: str, ) -> None: - """These errors have no mark, so the message names the file and the type of the error. The - error of `!!bool` quotes the value in lowercase, so the check ignores the case.""" + """An error with a mark gives its line and column, and an error with no mark names only the + file and the type of the error. The error of `!!bool` quotes the value in lowercase, so the + check ignores the case.""" isolate_devops_cli_config.write_bytes(content) error, shown = _load_error() captured = capsys.readouterr() assert (error.message, error.__cause__, error.__context__) == ( - f"Cannot load the settings: {isolate_devops_cli_config} is not valid YAML ({error_type}).", + f"Cannot load the settings: {isolate_devops_cli_config} is not valid YAML " + f"({error_type}){location}.", None, None, ) diff --git a/tests/config/test_config_yaml_load_errors.py b/tests/config/test_config_yaml_load_errors.py index 57365949e1..5b465ba31f 100644 --- a/tests/config/test_config_yaml_load_errors.py +++ b/tests/config/test_config_yaml_load_errors.py @@ -1,11 +1,12 @@ -"""A read of a config file that PyYAML or ruamel.yaml cannot load shows no text of the file (#2451). +"""A read of a config file that ruamel.yaml cannot load shows no text of the file (#2451). The settings load does this since #1468. These paths read a config file without the settings load: the audit record of a write (`write_history`), the round trip that edits a file (`round_trip`) and -`devops config unset`. ruamel.yaml accepts a local tag such as `!vault`, and PyYAML does not. Both -parsers raise `ValueError` or `KeyError` for a tagged value that they cannot build, and the message -quotes the value. A config file can hold a credential, so the error names the file, the type of the -error and its position, and quotes no text. It has no cause and no context. +`devops config unset`. The round trip accepts a local tag such as `!vault`, and the YAML 1.2 reader +(`parse_config_yaml`) does not. Both raise `ValueError` or `KeyError` for a tagged value that they +cannot build, and the message quotes the value. A config file can hold a credential, so the error +names the file, the type of the error and its position, and quotes no text. It has no cause and no +context. """ from __future__ import annotations @@ -15,17 +16,17 @@ from pathlib import Path import pytest -import yaml from devops_cli.config import round_trip from devops_cli.config.write_history import _mapping, redact_credentials -from devops_cli.config.yaml_errors import load_yaml +from devops_cli.config.yaml_errors import load_yaml, parse_config_yaml from devops_cli.exceptions import ConfigurationError _CREDENTIAL = "FAKE-value" _VAULT = f"ai:\n provider: ollama\n api_key: !vault {_CREDENTIAL}-tag\n" _INT = f"ai:\n api_key: !!int {_CREDENTIAL}-int\n" _BOOL = f"ai:\n api_key: !!bool {_CREDENTIAL}-bool\n" +_OMAP = f"ai:\n api_key: !!omap {_CREDENTIAL}-omap\n" _NOT_YAML = f"ai:\n api_key: {_CREDENTIAL}: x\n" @@ -39,14 +40,15 @@ def _refusal(action: Callable[[], object]) -> tuple[ConfigurationError, str]: def _leaks(*texts: str) -> list[str]: - """The texts that hold the credential, in any case: PyYAML quotes a `!!bool` value in lowercase.""" + """The texts that hold the credential, in any case: a loader quotes a `!!bool` value in + lowercase.""" return [text for text in texts if _CREDENTIAL.casefold() in text.casefold()] def test_the_helper_names_the_file_the_type_and_the_position_of_a_marked_error() -> None: error, shown = _refusal( lambda: load_yaml( - lambda: yaml.safe_load(_NOT_YAML), name="config.yaml", action="Cannot read" + lambda: parse_config_yaml(_NOT_YAML), name="config.yaml", action="Cannot read" ) ) @@ -62,22 +64,22 @@ def test_the_helper_names_the_file_the_type_and_the_position_of_a_marked_error() ("parse", "error_type", "location"), [ pytest.param( - lambda: yaml.safe_load(_VAULT), + lambda: parse_config_yaml(_VAULT), "ConstructorError", " at line 3, column 12", - id="pyyaml-tag", + id="tag", ), - pytest.param(lambda: yaml.safe_load(_INT), "ValueError", "", id="pyyaml-int"), - pytest.param(lambda: yaml.safe_load(_BOOL), "KeyError", "", id="pyyaml-bool"), + pytest.param(lambda: parse_config_yaml(_INT), "ValueError", "", id="int"), + pytest.param(lambda: parse_config_yaml(_BOOL), "KeyError", "", id="bool"), pytest.param( - lambda: yaml.safe_load(b"a: \xe9"), + lambda: parse_config_yaml(b"a: \xe9"), "ReaderError", "", - id="pyyaml-bytes", + id="bytes", ), ], ) -def test_the_helper_turns_each_error_of_pyyaml_into_one_error_without_text( +def test_the_helper_turns_each_error_of_the_yaml_1_2_reader_into_one_error_without_text( parse: Callable[[], object], error_type: str, location: str ) -> None: error, shown = _refusal(lambda: load_yaml(parse, name="f.yaml", action="Cannot read")) @@ -91,7 +93,9 @@ def test_the_helper_turns_each_error_of_pyyaml_into_one_error_without_text( def test_the_helper_returns_the_value_of_a_parse_that_works() -> None: - assert load_yaml(lambda: yaml.safe_load("a: 1\n"), name="f", action="Cannot read") == {"a": 1} + assert load_yaml(lambda: parse_config_yaml("a: 1\n"), name="f", action="Cannot read") == { + "a": 1 + } def test_the_helper_lets_an_error_that_is_not_a_load_error_go_up() -> None: @@ -121,7 +125,10 @@ def test_the_redaction_of_a_credential_quotes_no_text_of_the_file() -> None: assert (error.__cause__, error.__context__, _leaks(error.message, shown)) == (None, None, []) -@pytest.mark.parametrize("text", [pytest.param(_INT, id="int"), pytest.param(_BOOL, id="bool")]) +@pytest.mark.parametrize( + "text", + [pytest.param(_INT, id="int"), pytest.param(_BOOL, id="bool"), pytest.param(_OMAP, id="omap")], +) def test_the_round_trip_quotes_no_text_of_a_file_with_a_tag_it_cannot_build(text: str) -> None: found, found_shown = _refusal(lambda: round_trip.find(text, "ai.provider", name="c.yaml")) edited, edited_shown = _refusal( @@ -138,7 +145,8 @@ def test_unset_stops_for_a_file_with_a_local_tag_and_shows_no_text_of_it( isolate_devops_cli_config: Path, capsys: pytest.CaptureFixture[str], ) -> None: - """`ruamel.yaml` accepts `!vault`, and PyYAML does not. The command stops before it writes.""" + """The round trip accepts `!vault`, and the YAML 1.2 reader does not. The command stops before + it writes.""" from devops_cli.config.settings import remove_config_key isolate_devops_cli_config.write_text(_VAULT, encoding="utf-8") From fe1b26afb1852a286fae1825c42d47effdfd8010 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 11 Nov 2026 20:07:11 +0000 Subject: [PATCH 4/9] docs(config): state that a config file is read as YAML 1.2 Refs #4481. --- docs/CONFIGURATION.md | 2 +- docs/roadmap/intake.md | 2 +- openspec/changes/4481-read-each-config-file-as-yaml/tasks.md | 2 +- src/devops_cli/docs/generator.py | 4 ++++ 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3aff12c85a..001a91799a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -9,7 +9,7 @@ DevOps CLI supports hierarchical configuration resolution through: 4. **Global User Configuration** (`~/.config/devops-cli/config.yaml`) 5. **System Defaults** -`setting_sources` in `src/devops_cli/config/settings.py` declares the order of items 2 to 5 one time, as pydantic-settings sources. A setting takes the value of the first source that holds it, and only that value is checked against the type of the setting: a value that a variable replaces is not checked. A null in the project file is no value, so the value of the global file stays. A config file whose document is not a mapping of keys to values stops the load with an error that names the file. `DEVOPS_CLI_DATA_DIR` also moves each data path that no variable of its own sets into that directory, so the data paths of a config file do not apply. A credential resolves in its own order: the OS keyring, Vault, its variable, and last the config file, for a credential that a config file can hold. +`setting_sources` in `src/devops_cli/config/settings.py` declares the order of items 2 to 5 one time, as pydantic-settings sources. A setting takes the value of the first source that holds it, and only that value is checked against the type of the setting: a value that a variable replaces is not checked. A null in the project file is no value, so the value of the global file stays. A config file whose document is not a mapping of keys to values stops the load with an error that names the file. A settings save writes a config file as YAML 1.2, and each read of a config file reads YAML 1.2 too. So a bare `off`, `on`, `yes`, `no` or `12:30` is a string, and only a bare `true` or `false` is a bool. A key that a mapping holds two times stops the load with an error that names the file, the line and the column. `DEVOPS_CLI_DATA_DIR` also moves each data path that no variable of its own sets into that directory, so the data paths of a config file do not apply. A credential resolves in its own order: the OS keyring, Vault, its variable, and last the config file, for a credential that a config file can hold. A `devops review` command reads a tree it does not own. Started in a repository other than devops-cli's own, it looks for no project configuration, reading only the file `DEVOPS_CLI_CONFIG` names, and it resolves a relative data path under `~/.local/share/devops-cli` rather than under that repository, so its default data directory is `~/.local/share/devops-cli/.data`. What a review keeps -- its sessions, the feedback dataset, runs, samples, library contracts and AI spend -- every other command started outside devops-cli's own repository reads and writes there too. devops-cli's own repository is the one whose checkout holds the source of the devops-cli that runs, as an editable install's does; its code already runs, so a review started there, or in any worktree of it, reads its project configuration and keeps all data under its main worktree's `.data`, as every other command does. A clone nested in that checkout is another repository, and an installed devops-cli trusts no repository this way. An absolute `DEVOPS_CLI_DATA_DIR` or `data.dir` names the data directory every command uses. diff --git a/docs/roadmap/intake.md b/docs/roadmap/intake.md index 3b2b7668f8..95f03eade4 100644 --- a/docs/roadmap/intake.md +++ b/docs/roadmap/intake.md @@ -45,7 +45,7 @@ devops gh issues close --reason not-planned ## Jev for the proposal -The setting `roadmap.intake.jev` has three values (ADR 0019). `off` is the default and makes no Jev request. `shadow` keeps the `triage` model for every label and every flag, and records what TypeSafe Jev (`typesafe/jev-1.14`) would answer. `on` asks Jev for the fields of the proposal in place of the `triage` model. Jev must not decide yet: on the 25 closed issues of `devops roadmap eval jev` it ties the `triage` model on type, and it is behind on priority, Value and Effort. Use `shadow` to measure it on real new issues. +The setting `roadmap.intake.jev` has three values (ADR 0019). `off` is the default and makes no Jev request. `shadow` keeps the `triage` model for every label and every flag, and records what TypeSafe Jev (`typesafe/jev-1.14`) would answer. `on` asks Jev for the fields of the proposal in place of the `triage` model. Jev must not decide yet: on the 25 closed issues of `devops roadmap eval jev` it ties the `triage` model on type, and it is behind on priority, Value and Effort. Use `shadow` to measure it on real new issues. A config file is read as YAML 1.2 ([configuration reference](../CONFIGURATION.md)), so `jev: off` and `jev: on` with no quotes are the modes `off` and `on`. A bool, such as `jev: true`, is not a mode, and the settings do not load. One request holds a question for each field that has a fixed list: diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md index 632a354ce9..01b602935e 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md @@ -13,7 +13,7 @@ Kind: behavior. Reads: `src/devops_cli/config/round_trip.py`. Changes: `src/devo Kind: documents. Changes: `src/devops_cli/docs/generator.py`, `docs/CONFIGURATION.md`, `docs/roadmap/intake.md`. -- [ ] 2.1 State in the generated configuration reference (`docs/generator.py`, `docs/CONFIGURATION.md`) and in `docs/roadmap/intake.md` that a config file is read as YAML 1.2, so a bare `off`, `on`, `yes` or `no` is a string. +- [x] 2.1 State in the generated configuration reference (`docs/generator.py`, `docs/CONFIGURATION.md`) and in `docs/roadmap/intake.md` that a config file is read as YAML 1.2, so a bare `off`, `on`, `yes` or `no` is a string. - Verification: `$ uv run devops docs generate --check` ## Workflow follow-up diff --git a/src/devops_cli/docs/generator.py b/src/devops_cli/docs/generator.py index f293c5b6a6..a07f93d262 100644 --- a/src/devops_cli/docs/generator.py +++ b/src/devops_cli/docs/generator.py @@ -866,6 +866,10 @@ def generate_configuration_docs(self) -> str: "a value that a variable replaces is not checked. A null in the project file is no " "value, so the value of the global file stays. A config file whose document is not a " "mapping of keys to values stops the load with an error that names the file. " + "A settings save writes a config file as YAML 1.2, and each read of a config file " + "reads YAML 1.2 too. So a bare `off`, `on`, `yes`, `no` or `12:30` is a string, and " + "only a bare `true` or `false` is a bool. A key that a mapping holds two times stops " + "the load with an error that names the file, the line and the column. " "`DEVOPS_CLI_DATA_DIR` also moves each data path that no variable of its own sets into " "that directory, so the data paths of a config file do not apply. A credential " "resolves in its own order: the OS keyring, Vault, its variable, and last the config " From 49e7a9b02a02c5fa5c23847797e17b8616cd54f9 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 11 Nov 2026 22:08:14 +0000 Subject: [PATCH 5/9] docs(config): the YAML library page names the YAML 1.2 config reader --- .../4481-read-each-config-file-as-yaml/tasks.md | 4 +++- .../devops_cli/libraries/pyyaml_jinja2.md | 17 ++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md index 01b602935e..4871b18a01 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md @@ -11,10 +11,12 @@ Kind: behavior. Reads: `src/devops_cli/config/round_trip.py`. Changes: `src/devo ## 2. Documents -Kind: documents. Changes: `src/devops_cli/docs/generator.py`, `docs/CONFIGURATION.md`, `docs/roadmap/intake.md`. +Kind: documents. Changes: `src/devops_cli/docs/generator.py`, `docs/CONFIGURATION.md`, `docs/roadmap/intake.md`, `src/devops_cli/ai/knowledge_base/devops_cli/libraries/pyyaml_jinja2.md`. - [x] 2.1 State in the generated configuration reference (`docs/generator.py`, `docs/CONFIGURATION.md`) and in `docs/roadmap/intake.md` that a config file is read as YAML 1.2, so a bare `off`, `on`, `yes` or `no` is a string. - Verification: `$ uv run devops docs generate --check` +- [x] 2.2 State in the knowledge page of PyYAML that PyYAML reads YAML 1.1, that `parse_config_yaml` reads each config file as YAML 1.2, and that `load_yaml` has no `errors` parameter. + - Verification: `$ uv run devops ci --check --only docs` ## Workflow follow-up diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/libraries/pyyaml_jinja2.md b/src/devops_cli/ai/knowledge_base/devops_cli/libraries/pyyaml_jinja2.md index 3dde2362ec..d6ffd0619d 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/libraries/pyyaml_jinja2.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/libraries/pyyaml_jinja2.md @@ -7,7 +7,7 @@ sources: - "https://pyyaml.org/" - "https://jinja.palletsprojects.com/" - "https://yaml.dev/doc/ruamel.yaml/" -reviewed: "2026-10-24" +reviewed: "2026-11-11" tags: - "pyyaml" - "jinja2" @@ -29,10 +29,11 @@ tags: ## 2. General Information & Architecture -**PyYAML** is a YAML 1.2 parser and emitter for Python. **Jinja2** is a fast, expressive, extensible templating engine powering template rendering across Python frameworks. +**PyYAML** is a YAML 1.1 parser and emitter for Python. **ruamel.yaml** reads and writes YAML 1.2. **Jinja2** is a fast, expressive, extensible templating engine powering template rendering across Python frameworks. In `devops-cli`: - **Kubernetes & GitOps YAML**: Parses and serializes Kubernetes manifests, ArgoCD Application specifications, Helm values overrides, and Kustomize patches. +- **Config files**: ruamel.yaml reads and writes each config file of devops-cli as YAML 1.2 (#4481). YAML 1.1 reads a bare `off`, `on`, `yes` or `no` as a bool and a bare `12:30` as the number 750. So do not read a config file with PyYAML. - **DevContainer & Agent Scaffolding**: Uses Jinja2 templates (`src/devops_cli/templates/`) to dynamically scaffold `.devcontainer/devcontainer.json` and MCP configuration files (`AGENTS.md` is generated in Python). --- @@ -42,7 +43,7 @@ In `devops-cli`: | Library | Strengths | Weaknesses | Why `devops-cli` Chose PyYAML + Jinja2 | | :--- | :--- | :--- | :--- | | **`PyYAML` + `jinja2`** | Battle-tested, supports `CSafeLoader`/`CSafeDumper` in C/Rust, expressive templating (loops, filters, macros). | PyYAML does not preserve round-trip comments natively. | **Selected**: The definitive industry standard for cloud-native manifest generation. | -| **`ruamel.yaml`** | Round-trip mode keeps the comments, the order of the keys, the quotes and the unknown keys of a file that it edits. | Slower than PyYAML, and one indentation for all of a document. | Used for one job: `devops_cli.config.round_trip` edits `config.yaml` in place when a command saves settings (#1999). PyYAML `safe_load` / `safe_dump` reads and writes every other YAML file. | +| **`ruamel.yaml`** | Round-trip mode keeps the comments, the order of the keys, the quotes and the unknown keys of a file that it edits. | Slower than PyYAML, and one indentation for all of a document. | Used for the config files of devops-cli: `devops_cli.config.round_trip` edits `config.yaml` in place when a command saves settings (#1999), and `config/yaml_errors.py::parse_config_yaml` reads each config file with the safe loader, as YAML 1.2 (#4481). PyYAML `safe_load` / `safe_dump` reads and writes every other YAML file. | | **`mako`** | High-performance templating engine. | Less standard in the Kubernetes and DevContainer ecosystem than Jinja2. | Rejected: Jinja2 is the universal standard across Ansible, Helm, and DevContainers. | | **Python f-strings** | Built into Python. | Unsafe for complex multi-line templates, lacks template inheritance and reusable partial blocks. | Rejected: Jinja2 isolates template files cleanly from Python code logic. | @@ -50,7 +51,7 @@ In `devops-cli`: ## 4. Key Concepts & Core Patterns -1. **`yaml.safe_load(text)`**: Always use `safe_load` instead of `yaml.load` to prevent arbitrary code execution vulnerabilities. +1. **`yaml.safe_load(text)`**: Always use `safe_load` instead of `yaml.load` to prevent arbitrary code execution vulnerabilities. For a config file of devops-cli, use `parse_config_yaml`, which reads YAML 1.2. 2. **`jinja2.Environment`**: `core/templating.py` uses a cached `SandboxedEnvironment(FileSystemLoader, undefined=StrictUndefined)`; values are encoded with `| tojson` and output is re-parsed as JSON. Templates scaffold devcontainer.json and MCP configs; AGENTS.md is generated in Python. 3. **Template Inheritance**: Reuses base template headers across DevContainer configurations. @@ -60,20 +61,18 @@ In `devops-cli`: ### Safe YAML Parsing -The message of a PyYAML error quotes the line where the parser stopped, and the `buffer` of its `problem_mark` holds the full text of the document. The safe loader also raises `ValueError`, `KeyError`, `IndexError` or `AttributeError` for a tagged value that it cannot build, such as `!!int `, and the message quotes the value. It raises `RecursionError` for a document that nests too deep. ruamel.yaml raises `ValueError` and `KeyError` in the same way. A file can hold a credential, so the error that you raise names the type of the error and its position, and quotes no text. Do not catch these errors by hand: call `config/yaml_errors.py::load_yaml` with the parse. It catches the error types by name (a blind `except Exception` is a swallowed failure that `tests/test_swallowed_failures_ratchet.py` refuses), reads the position in a function so that no frame of the traceback holds the mark, and raises the ConfigurationError after the `except` block, so it has no cause and no context that holds the first error. An `OSError` goes up, because it names only the file. A parse with ruamel.yaml passes the `YAMLError` of ruamel.yaml in `errors`. `config/settings.py::_read_config_file`, `config/write_history.py` and `config/round_trip.py` read the config files this way. +The message of a YAML error quotes the line where the parser stopped, and its `problem_mark` holds the text of the document. The safe loaders of PyYAML and ruamel.yaml also raise `ValueError`, `KeyError`, `IndexError` or `AttributeError` for a tagged value that they cannot build, such as `!!int `, and the message quotes the value. They raise `RecursionError` for a document that nests too deep. A file can hold a credential, so the error that you raise names the type of the error and its position, and quotes no text. Do not catch these errors by hand: call `config/yaml_errors.py::load_yaml` with the parse. It catches the errors of `yaml_load_errors()` by name (a blind `except Exception` is a swallowed failure that `tests/test_swallowed_failures_ratchet.py` refuses), reads the position in a function so that no frame of the traceback holds the mark, and raises the ConfigurationError after the `except` block, so it has no cause and no context that holds the first error. An `OSError` goes up, because it names only the file. `load_yaml` catches the `YAMLError` of ruamel.yaml, so the parse reads with ruamel.yaml: `parse_config_yaml` for a config file. `config/settings.py::_read_config_file`, `config/write_history.py` and `config/round_trip.py` read the config files this way. ```python from pathlib import Path from typing import Any -import yaml - -from devops_cli.config.yaml_errors import load_yaml +from devops_cli.config.yaml_errors import load_yaml, parse_config_yaml def load_yaml_file(path: Path) -> Any: return load_yaml( - lambda: yaml.safe_load(path.read_text(encoding="utf-8")) or {}, + lambda: parse_config_yaml(path.read_text(encoding="utf-8")) or {}, name=str(path), action="Cannot load the settings", ) From 25c47c6b1a74b99840e733028ede07d9fdc7592e Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 11 Nov 2026 23:21:19 +0000 Subject: [PATCH 6/9] test(config): merge a test section into the config file, not add a second key The YAML 1.2 read of a config file refuses a key that a mapping holds two times. Two test files added a second ai or qdrant key to the config file of the test, so the load stopped. They now merge their keys into the section of the file through the config fixture. --- tests/ai/rag/test_qdrant_timeout_setting.py | 17 ++++++------- .../ai/test_service_client_configured_urls.py | 24 +++++++++---------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/tests/ai/rag/test_qdrant_timeout_setting.py b/tests/ai/rag/test_qdrant_timeout_setting.py index 07384480d1..b23d0fbd90 100644 --- a/tests/ai/rag/test_qdrant_timeout_setting.py +++ b/tests/ai/rag/test_qdrant_timeout_setting.py @@ -7,6 +7,7 @@ from __future__ import annotations +from collections.abc import Callable from pathlib import Path import pytest @@ -21,18 +22,18 @@ pytestmark = pytest.mark.usefixtures("keyring_store") -def _configure_qdrant(config: Path, timeout: float) -> None: - """Append a `qdrant` section to the test's config file, at an address that needs no DNS.""" - section = f"qdrant:\n url: http://127.0.0.1:6333\n timeout: {timeout}\n" - config.write_text(config.read_text(encoding="utf-8") + section, encoding="utf-8") +def _configure_qdrant(config: Callable[..., Path], timeout: float) -> None: + """Merge a `qdrant` address that needs no DNS and `timeout` into the `qdrant` section of the + test's config file. A second `qdrant` key in the file would stop the load (#4481).""" + config(qdrant={"url": "http://127.0.0.1:6333", "timeout": timeout}) def test_the_qdrant_timeout_is_read_from_the_config_file_and_the_environment( - isolate_devops_cli_config: Path, monkeypatch: pytest.MonkeyPatch + config: Callable[..., Path], monkeypatch: pytest.MonkeyPatch ) -> None: """Verify the default is 300 s, a config file sets it, and the environment overrides that.""" default = settings_module.load_settings().qdrant.timeout - _configure_qdrant(isolate_devops_cli_config, 450) + _configure_qdrant(config, 450) from_file = settings_module.load_settings().qdrant.timeout monkeypatch.setenv("DEVOPS_CLI_QDRANT_TIMEOUT", "600") from_env = settings_module.load_settings().qdrant.timeout @@ -73,12 +74,12 @@ def test_a_qdrant_timeout_in_the_config_file_must_be_positive() -> None: ], ) def test_each_builder_gives_its_qdrant_client_the_configured_timeout( - build: object, isolate_devops_cli_config: Path + build: object, config: Callable[..., Path] ) -> None: """The review investigation, the `rag_search` tool, `devops ai rag query` and the library vector store build their client with `resolve_rag_components`; indexing's upserts and deletes go through `resolve_qdrant_client`. Both pass `qdrant.timeout`, not the default.""" - _configure_qdrant(isolate_devops_cli_config, 450) + _configure_qdrant(config, 450) client = build() # type: ignore[operator] diff --git a/tests/ai/test_service_client_configured_urls.py b/tests/ai/test_service_client_configured_urls.py index edade15a6e..0179ff0383 100644 --- a/tests/ai/test_service_client_configured_urls.py +++ b/tests/ai/test_service_client_configured_urls.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Callable from pathlib import Path from typing import Any @@ -120,7 +121,7 @@ def test_review_path_unconfigured_exits_nonzero_and_names_setting( def test_gateway_only_config_routes_all_calls_to_gateway( - isolate_devops_cli_config: Any, + config: Callable[..., Path], web: WebFake, ) -> None: """With gateway-only config, the `web` fake verifies calls go to gateway URL and never localhost:11434.""" @@ -128,18 +129,17 @@ def test_gateway_only_config_routes_all_calls_to_gateway( from devops_cli.ai.rag.embeddings import EmbeddingsEngine from devops_cli.config.settings import load_settings - existing_cfg = isolate_devops_cli_config.read_text(encoding="utf-8") - isolate_devops_cli_config.write_text( - existing_cfg + "\nai:\n" - " provider: gateway\n" - " gateway_url: https://192.0.2.1:4000/v1\n" - " ollama_urls: []\n" - " allow_private_network: true\n" - " cache:\n" - " enabled: false\n", - encoding="utf-8", + # The `ai` section of the test's config file takes these keys. A second `ai` key in the file + # would stop the load (#4481). + config( + ai={ + "provider": "gateway", + "gateway_url": "https://192.0.2.1:4000/v1", + "ollama_urls": [], + "allow_private_network": True, + "cache": {"enabled": False}, + } ) - reset_settings_cache() settings = load_settings() def answer(request: httpx2.Request) -> httpx2.Response: From 13a7a36bd09e3da06c057deb4d2896a74284062f Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Thu, 12 Nov 2026 00:21:44 +0000 Subject: [PATCH 7/9] test(config): a project config file that does not load gives no SSH key prefix --- tests/crypto/test_ssh.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/crypto/test_ssh.py b/tests/crypto/test_ssh.py index 82c85a7081..42499dc84d 100755 --- a/tests/crypto/test_ssh.py +++ b/tests/crypto/test_ssh.py @@ -172,6 +172,37 @@ def test_a_bare_no_in_the_project_config_file_is_the_key_prefix(tmp_path: Path) assert get_ssh_key_prefix(workspace) == "no" +@pytest.mark.parametrize( + ("text", "error"), + [ + pytest.param( + "ssh:\n key_prefix: FAKE-value\nssh:\n key_prefix: FAKE-value\n", + "DuplicateKeyError at line 3, column 1", + id="a key two times", + ), + pytest.param("ssh:\n key_prefix: !!int FAKE-value\n", "ValueError", id="a bad tag"), + ], +) +def test_a_project_config_file_that_does_not_load_names_no_prefix( + text: str, error: str, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """A project config file that the settings load refuses gives no prefix, so the key takes the + name of its directory. The log names the error and quotes no text of the file (#4481).""" + from devops_cli.crypto.ssh_keys import get_ssh_key_prefix + + workspace = tmp_path / "my_plain_repo" + (workspace / ".git").mkdir(parents=True) + (workspace / "config.yaml").write_text(text, encoding="utf-8") + + with caplog.at_level("DEBUG", logger="devops_cli.crypto.ssh_keys"): + prefix = get_ssh_key_prefix(workspace) + + assert (prefix, "FAKE-value" in caplog.text) == ("my_plain_repo", False) + assert caplog.messages == [ + f"Failed reading YAML key_prefix from {workspace / 'config.yaml'}: {error}" + ] + + def test_devcontainer_name_survives_urls_next_to_comments(tmp_path: Path) -> None: """Verify the devcontainer name is the prefix when a string holds `//` beside real comments. From 190d0aa6bcd7e0b69497d420ed96887e78342462 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Thu, 12 Nov 2026 00:22:39 +0000 Subject: [PATCH 8/9] fix(config): the SSH key prefix read catches the errors of the settings load The read of ssh.key_prefix from a project config file caught only a YAML error. A tagged value that the YAML 1.2 loader cannot build, such as !!int , raised ValueError with the value in its message and stopped the command. The read now catches the errors of the settings load, and its try block holds only the read and the parse. --- .../design.md | 2 +- .../specs/config-commands/spec.md | 6 +++- .../tasks.md | 8 +++-- src/devops_cli/crypto/ssh_keys.py | 32 +++++++++++-------- 4 files changed, 29 insertions(+), 19 deletions(-) diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/design.md b/openspec/changes/4481-read-each-config-file-as-yaml/design.md index ff45d48298..e806a16985 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/design.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/design.md @@ -8,7 +8,7 @@ - **`load_yaml` catches the errors of ruamel.yaml.** `yaml_load_errors()` gives the `YAMLError` of ruamel.yaml and the errors of a value that the loader cannot build (`ValueError`, `LookupError`, `AttributeError`, `RecursionError`). `load_yaml` catches them for each parse, the round trip included, so its `errors` parameter goes. The rule of #1468 stays: the error names the file, the type of the error, and its line and column, and quotes no text of the file. The text of the file stays in the frame of the parse, which is not in the traceback of the error. - **The mode types stay as they are.** `JevMode`, `DecisionMode` and the refusal of a bool of #4438 do not change. A bare `true` is a bool in YAML 1.2, so the scenario "The old bool is refused" of `roadmap-intake-jev` stays true. - **The ConfigMap render reads only its config as YAML 1.2.** Kubernetes reads the manifest of the template, and its parser reads YAML 1.1, so the render reads the manifest with PyYAML. The config in the manifest is a devops-cli config file, so the render reads it with `parse_config_yaml`. The render writes the config with PyYAML, which quotes each word that YAML 1.1 reads as a bool or a number, such as `'off'`. The YAML 1.2 reader of the Service reads the same string. The render validates the settings of the YAML 1.2 read of the text that it writes, so it never writes a config that the Service cannot load. -- **The SSH key prefix reads the project config file as YAML 1.2.** `crypto/ssh_keys.py` reads `ssh.key_prefix` from a project config file without the settings load. It reads the same files, so it uses the same reader. It catches the same errors as before: a YAML error, an `OSError` and a `UnicodeDecodeError`. +- **The SSH key prefix reads the project config file as YAML 1.2.** `crypto/ssh_keys.py` reads `ssh.key_prefix` from a project config file without the settings load. It reads the same files, so it uses the same reader. It catches the errors that the settings load catches (`yaml_load_errors()`) and an `OSError`, so a tagged value that the loader cannot build gives no prefix and does not stop the command. The `try` block holds only the read and the parse. - **A duplicate key stops the load.** The safe loader of ruamel.yaml refuses a key that a mapping holds two times, as YAML 1.2 requires. PyYAML kept the last value with no message. The error names the file, the line and the column, so a person can remove the duplicate. ## Rejected alternatives diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md b/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md index 739ee96771..76c1258466 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md @@ -48,12 +48,16 @@ The ConfigMap render SHALL read the config in the ConfigMap template as YAML 1.2 - **THEN** the render succeeds, and a YAML 1.2 read of the rendered config gives the string `off` for `roadmap.intake.jev` ### Requirement: The SSH key prefix reads a project config file as YAML 1.2 -The SSH key prefix SHALL read `ssh.key_prefix` from a project config file as YAML 1.2. +The SSH key prefix SHALL read `ssh.key_prefix` from a project config file as YAML 1.2. A project config file that the settings load refuses SHALL give no prefix, and the log of the read SHALL quote no text of the file. #### Scenario: A bare no as the key prefix of a project - **WHEN** the project config file of a workspace holds `ssh.key_prefix: no` with no quotes, and no other source sets the prefix - **THEN** the key prefix of the workspace is `no` +#### Scenario: A project config file that does not load +- **WHEN** the project config file of a workspace holds `ssh.key_prefix: !!int FAKE-value`, or holds the `ssh` key two times, and no other source sets the prefix +- **THEN** the key prefix of the workspace is the name of its directory, and the log names the type of the error and holds no `FAKE-value` + ## MODIFIED Requirements ### Requirement: A write or an edit of a config file quotes no text of a file that a YAML parser cannot load diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md index 4871b18a01..8ee98fc08b 100644 --- a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md +++ b/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md @@ -2,12 +2,14 @@ ## 1. Read each config file as YAML 1.2 -Kind: behavior. Reads: `src/devops_cli/config/round_trip.py`. Changes: `src/devops_cli/config/yaml_errors.py`, `src/devops_cli/config/settings.py`, `src/devops_cli/config/write_history.py`, `src/devops_cli/config/round_trip.py`, `src/devops_cli/commands/config.py`, `src/devops_cli/k8s/configmap.py`, `src/devops_cli/crypto/ssh_keys.py`, `tests/config/test_config_file_yaml_1_2.py`, `tests/config/test_config_yaml_load_errors.py`, `tests/config/test_config_file_that_is_not_yaml.py`, `tests/config/test_config_write_history.py`, `tests/commands/test_config.py`, `tests/commands/test_config_audit_keys.py`, `tests/k8s/test_k8s_configmap.py`, `tests/crypto/test_ssh.py`. +Kind: behavior. Reads: `src/devops_cli/config/round_trip.py`. Changes: `src/devops_cli/config/yaml_errors.py`, `src/devops_cli/config/settings.py`, `src/devops_cli/config/write_history.py`, `src/devops_cli/config/round_trip.py`, `src/devops_cli/commands/config.py`, `src/devops_cli/k8s/configmap.py`, `src/devops_cli/crypto/ssh_keys.py`, `tests/config/test_config_file_yaml_1_2.py`, `tests/config/test_config_yaml_load_errors.py`, `tests/config/test_config_file_that_is_not_yaml.py`, `tests/config/test_config_write_history.py`, `tests/commands/test_config.py`, `tests/commands/test_config_audit_keys.py`, `tests/k8s/test_k8s_configmap.py`, `tests/crypto/test_ssh.py`, `tests/ai/test_service_client_configured_urls.py`, `tests/ai/rag/test_qdrant_timeout_setting.py`. -- [x] 1.1 Write the failing tests: a bare `off` and `on` for `roadmap.intake.jev`, a bare `off` in `roadmap.decisions`, a YAML bool, and a duplicate key through the settings load; `devops config set` of `roadmap.intake.jev off`, `search.language no` and `k8s.context 12:30`; the audit record of a write; `devops config audit-keys` of a credential `no`; the ConfigMap render of a bare `off`; the SSH key prefix `no` of a project config file. +- [x] 1.1 Write the failing tests: a bare `off` and `on` for `roadmap.intake.jev`, a bare `off` in `roadmap.decisions`, a YAML bool, and a duplicate key through the settings load; `devops config set` of `roadmap.intake.jev off`, `search.language no` and `k8s.context 12:30`; the audit record of a write; `devops config audit-keys` of a credential `no`; the ConfigMap render of a bare `off`; the SSH key prefix `no` of a project config file, and of a project config file that does not load. - Verification: `$ uv run devops ci test tests/config/test_config_file_yaml_1_2.py tests/commands/test_config.py tests/config/test_config_write_history.py tests/commands/test_config_audit_keys.py tests/k8s/test_k8s_configmap.py tests/crypto/test_ssh.py` -- [x] 1.2 Add `parse_config_yaml` and `yaml_load_errors` to `config/yaml_errors.py`, make `load_yaml` catch the errors of ruamel.yaml, and remove its `errors` parameter. Read the config file with `parse_config_yaml` in `config/settings.py`, `config/write_history.py`, `commands/config.py`, `k8s/configmap.py` and `crypto/ssh_keys.py`. Remove `_LOAD_ERRORS` of `config/round_trip.py` and `_AUDIT_READ_ERRORS` of `commands/config.py`. Move the load error tests from PyYAML to the YAML 1.2 reader. +- [x] 1.2 Add `parse_config_yaml` and `yaml_load_errors` to `config/yaml_errors.py`, make `load_yaml` catch the errors of ruamel.yaml, and remove its `errors` parameter. Read the config file with `parse_config_yaml` in `config/settings.py`, `config/write_history.py`, `commands/config.py`, `k8s/configmap.py` and `crypto/ssh_keys.py`. Make the SSH key prefix read catch `yaml_load_errors()`. Remove `_LOAD_ERRORS` of `config/round_trip.py` and `_AUDIT_READ_ERRORS` of `commands/config.py`. Move the load error tests from PyYAML to the YAML 1.2 reader. - Verification: `$ uv run devops ci test tests/config/test_config_file_yaml_1_2.py tests/commands/test_config.py tests/config/test_config_write_history.py tests/commands/test_config_audit_keys.py tests/k8s/test_k8s_configmap.py tests/crypto/test_ssh.py tests/config/test_config_yaml_load_errors.py tests/config/test_config_file_that_is_not_yaml.py` +- [x] 1.3 Make the two tests that add a second `ai` or `qdrant` key to the config file of the test merge their keys into the section through the `config` fixture. The YAML 1.2 read refuses a key that a mapping holds two times. + - Verification: `$ uv run devops ci test tests/ai/test_service_client_configured_urls.py tests/ai/rag/test_qdrant_timeout_setting.py` ## 2. Documents diff --git a/src/devops_cli/crypto/ssh_keys.py b/src/devops_cli/crypto/ssh_keys.py index b43550e710..9d490be762 100755 --- a/src/devops_cli/crypto/ssh_keys.py +++ b/src/devops_cli/crypto/ssh_keys.py @@ -38,30 +38,34 @@ def _sanitize_prefix(raw_prefix: str) -> str: def _extract_prefix_from_yaml(cfg_file: Path) -> str | None: """Extract and sanitize key_prefix from a config file, read as YAML 1.2 as the settings load - reads it (#4481). The log of a file that does not load quotes no text of it.""" - from ruamel.yaml.error import YAMLError - - from devops_cli.config.yaml_errors import parse_config_yaml, yaml_error_location + reads it (#4481). A file that the load refuses gives no prefix, and its log quotes no text of + the file.""" + from devops_cli.config.yaml_errors import ( + parse_config_yaml, + yaml_error_location, + yaml_load_errors, + ) if not cfg_file.is_file(): return None + read_errors: tuple[type[Exception], ...] = (*yaml_load_errors(), OSError) try: data = parse_config_yaml(cfg_file.read_text(encoding="utf-8")) or {} - if not isinstance(data, dict): - return None - ssh_conf = data.get("ssh", {}) - raw_prefix = None - if isinstance(ssh_conf, dict) and ssh_conf.get("key_prefix"): - raw_prefix = ssh_conf["key_prefix"] - elif data.get("key_prefix"): - raw_prefix = data["key_prefix"] - return _sanitize_prefix(str(raw_prefix)) if raw_prefix else None - except (YAMLError, OSError, UnicodeDecodeError) as exc: + except read_errors as exc: where = yaml_error_location(exc) logger.debug( "Failed reading YAML key_prefix from %s: %s%s", cfg_file, type(exc).__name__, where ) return None + if not isinstance(data, dict): + return None + ssh_conf = data.get("ssh", {}) + raw_prefix = None + if isinstance(ssh_conf, dict) and ssh_conf.get("key_prefix"): + raw_prefix = ssh_conf["key_prefix"] + elif data.get("key_prefix"): + raw_prefix = data["key_prefix"] + return _sanitize_prefix(str(raw_prefix)) if raw_prefix else None def _resolve_prefix_from_project_config(target_dir: Path) -> str | None: From 7fc3f07d928c8dddaad8a290e163f68b5b26760f Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Thu, 12 Nov 2026 00:36:09 +0000 Subject: [PATCH 9/9] docs(openspec): archive 4481-read-each-config-file-as-yaml --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/config-commands/spec.md | 0 .../tasks.md | 0 openspec/specs/config-commands/spec.md | 60 ++++++++++++++++++- 6 files changed, 59 insertions(+), 1 deletion(-) rename openspec/changes/{4481-read-each-config-file-as-yaml => archive/2026-11-12-4481-read-each-config-file-as-yaml}/.openspec.yaml (100%) rename openspec/changes/{4481-read-each-config-file-as-yaml => archive/2026-11-12-4481-read-each-config-file-as-yaml}/design.md (100%) rename openspec/changes/{4481-read-each-config-file-as-yaml => archive/2026-11-12-4481-read-each-config-file-as-yaml}/proposal.md (100%) rename openspec/changes/{4481-read-each-config-file-as-yaml => archive/2026-11-12-4481-read-each-config-file-as-yaml}/specs/config-commands/spec.md (100%) rename openspec/changes/{4481-read-each-config-file-as-yaml => archive/2026-11-12-4481-read-each-config-file-as-yaml}/tasks.md (100%) diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/.openspec.yaml b/openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/.openspec.yaml similarity index 100% rename from openspec/changes/4481-read-each-config-file-as-yaml/.openspec.yaml rename to openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/.openspec.yaml diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/design.md b/openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/design.md similarity index 100% rename from openspec/changes/4481-read-each-config-file-as-yaml/design.md rename to openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/design.md diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/proposal.md b/openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/proposal.md similarity index 100% rename from openspec/changes/4481-read-each-config-file-as-yaml/proposal.md rename to openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/proposal.md diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md b/openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/specs/config-commands/spec.md similarity index 100% rename from openspec/changes/4481-read-each-config-file-as-yaml/specs/config-commands/spec.md rename to openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/specs/config-commands/spec.md diff --git a/openspec/changes/4481-read-each-config-file-as-yaml/tasks.md b/openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/tasks.md similarity index 100% rename from openspec/changes/4481-read-each-config-file-as-yaml/tasks.md rename to openspec/changes/archive/2026-11-12-4481-read-each-config-file-as-yaml/tasks.md diff --git a/openspec/specs/config-commands/spec.md b/openspec/specs/config-commands/spec.md index 1dc295636b..f18b7208c6 100644 --- a/openspec/specs/config-commands/spec.md +++ b/openspec/specs/config-commands/spec.md @@ -468,7 +468,7 @@ A temporary file written during a config write MUST have a mode no more open tha - **THEN** `plaintext_leaks` is empty, `is_compliant` is true, and the command exits 0 ### Requirement: A write or an edit of a config file quotes no text of a file that a YAML parser cannot load -When devops-cli reads a config file without the settings load, and PyYAML or ruamel.yaml cannot load the file, the read SHALL fail with a configuration error. The message SHALL name the file and the type of the error, and the line and the column when the error gives them. The message, the exception chain of the error and the output of the command SHALL hold no text of the file. +When devops-cli reads a config file without the settings load, and ruamel.yaml cannot load the file with the YAML 1.2 reader or with the round trip, the read SHALL fail with a configuration error. The message SHALL name the file and the type of the error, and the line and the column when the error gives them. The message, the exception chain of the error and the output of the command SHALL hold no text of the file. #### Scenario: A local tag that ruamel.yaml accepts and PyYAML does not - **WHEN** the active config file holds `ai:`, ` provider: ollama` and ` api_key: !vault FAKE-value-tag`, and `devops config unset ai.provider` runs @@ -496,3 +496,61 @@ The search for a project config file SHALL accept a file in the base directory. #### Scenario: Key prefix with a stray config file - **WHEN** a `config.yaml` that sets `ssh.key_prefix` is in an ancestor with no project marker, and no other source sets the prefix - **THEN** the key prefix is the name of the workspace directory + +### Requirement: The settings load reads a config file as YAML 1.2 +The settings load SHALL read each config file as YAML 1.2, the version that a settings save writes. A bare `off`, `on`, `yes` or `no` SHALL load as a string, and a bare `true` or `false` SHALL load as a bool. A key that a mapping holds two times SHALL stop the load with a configuration error that names the file, the line and the column, and that quotes no text of the file. + +#### Scenario: A bare off or on for the intake mode +- **WHEN** the active config file holds `roadmap.intake.jev` with the bare value `off`, or with the bare value `on` +- **THEN** `load_settings()` gives `roadmap.intake.jev` equal to that string + +#### Scenario: A bare off for a decision point +- **WHEN** the active config file holds `roadmap.decisions` with `stage.verify_screen: off` +- **THEN** `load_settings()` gives the mode `off` for `stage.verify_screen` + +#### Scenario: A YAML bool for the intake mode +- **WHEN** the active config file holds `roadmap.intake.jev: true` +- **THEN** `load_settings()` raises a validation error for the field `roadmap.intake.jev` + +#### Scenario: A key that a mapping holds two times +- **WHEN** the active config file holds `ai:`, ` provider: ollama` and ` provider: FAKE-value` +- **THEN** the load fails with the message `Cannot load the settings: is not valid YAML (DuplicateKeyError) at line 3, column 3.`, the error has no cause and no context, and no output holds `FAKE-value` + +### Requirement: devops config set writes a value that the next load reads as the same string +After `devops config set ` writes a string setting to the config file, the next settings load SHALL give the same string, also for a word that YAML 1.1 reads as a bool or a number. + +#### Scenario: A word that YAML 1.1 reads as a bool or a number +- **WHEN** `devops config set` runs with `roadmap.intake.jev off`, with `search.language no` or with `k8s.context 12:30` +- **THEN** the command exits 0, and `devops config get` of the key prints the value that was set + +### Requirement: The audit record of a config write compares the values as YAML 1.2 +The audit record of a config write SHALL read the file before and after the write as YAML 1.2, and it SHALL name only the keys whose values changed. + +#### Scenario: A quoted value that a write makes bare +- **WHEN** a write changes the line ` context: "12:30"` under `k8s:` to ` context: 12:30`, and changes nothing else +- **THEN** the audit record of the write names no changed key + +### Requirement: devops config audit-keys reads a config file as YAML 1.2 +`devops config audit-keys` SHALL read each config file as YAML 1.2. A credential whose bare value is a word that YAML 1.1 reads as `false`, such as `no`, SHALL count as a plaintext secret. + +#### Scenario: A credential with the bare value no +- **WHEN** the active config file holds `ai.api_key: no`, and `devops config audit-keys --json` runs +- **THEN** `plaintext_leaks` names `ai.api_key` of the file, `is_compliant` is false, and the command exits 1 + +### Requirement: The ConfigMap render reads the config of its template as YAML 1.2 +The ConfigMap render SHALL read the config in the ConfigMap template as YAML 1.2. It SHALL validate the settings of the YAML 1.2 read of the config that it writes, which is the config that the Service loads. + +#### Scenario: A bare off in the template +- **WHEN** the config of the ConfigMap template holds `roadmap.intake.jev: off` with no quotes +- **THEN** the render succeeds, and a YAML 1.2 read of the rendered config gives the string `off` for `roadmap.intake.jev` + +### Requirement: The SSH key prefix reads a project config file as YAML 1.2 +The SSH key prefix SHALL read `ssh.key_prefix` from a project config file as YAML 1.2. A project config file that the settings load refuses SHALL give no prefix, and the log of the read SHALL quote no text of the file. + +#### Scenario: A bare no as the key prefix of a project +- **WHEN** the project config file of a workspace holds `ssh.key_prefix: no` with no quotes, and no other source sets the prefix +- **THEN** the key prefix of the workspace is `no` + +#### Scenario: A project config file that does not load +- **WHEN** the project config file of a workspace holds `ssh.key_prefix: !!int FAKE-value`, or holds the `ssh` key two times, and no other source sets the prefix +- **THEN** the key prefix of the workspace is the name of its directory, and the log names the type of the error and holds no `FAKE-value`