Repository navigation
feat(github): declarative branch protection auditor and repository secret synchronization - #197
Merged
Merged
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Critical branch-protection defects and secret-synchronization error-handling issues remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Pull request overview
Adds declarative GitHub branch-protection auditing/synchronization and libsodium-sealed repository secret synchronization.
Changes:
- Adds branch-protection policy models, auditing, and synchronization.
- Adds Keyring/Vault secret encryption and upload workflows.
- Adds CLI commands, tests, configuration, and documentation.
File summaries
| File | Description |
|---|---|
tests/test_github_secrets.py |
Secret synchronization tests |
tests/test_github_branch_protection.py |
Branch-protection tests |
src/devops_cli/lang/en/help.py |
CLI help text |
src/devops_cli/github/secrets.py |
Secret encryption and synchronization |
src/devops_cli/github/branch_protection.py |
Branch-protection logic |
src/devops_cli/github/__init__.py |
GitHub module exports |
src/devops_cli/commands/gh.py |
GitHub CLI commands |
README.md |
User-facing documentation |
docs/commands/gh.md |
GitHub command documentation |
docs/CLI_REFERENCE.md |
CLI reference updates |
docs/agent/tasks/task-114-branch-protection-secrets.md |
Task tracking |
.github/branch-protection.yml |
Declarative branch policies |
Review details
Suppressed comments (6)
.github/branch-protection.yml:27
- The release policy repeats the nonexistent
cicontext, so release-branch pull requests would also wait forever for a check GitHub never reports. Keep this entry aligned with the actual workflow/job check context after correcting the main policy.
- "ci"
src/devops_cli/github/branch_protection.py:114
BranchProtectionPolicyand its nested models use Pydantic's defaultextra='ignore', so misspelled or unsupported policy keys are silently discarded. For example, a typo such asrequired_status_checkcan make the loader fall back to an empty/default policy and the auditor may report compliance while the declared rule is absent. Configure these policy models withextra='forbid'and surface validation errors so declarative files fail closed.
policies.append(BranchProtectionPolicy(**item))
src/devops_cli/github/branch_protection.py:134
- The
ghresponse text is logged without masking here. CLI/API errors can contain credential-like or internal values, so sanitize and boundres.stderrbefore recording it, consistent with the repository's logging and output sanitization requirements.
logger.debug("Branch %s has no protection or fetch failed: %s", branch, res.stderr)
src/devops_cli/github/branch_protection.py:370
- The mutation failure path also logs raw
ghstderr, which can leak sensitive response text into logs. Mask and bound this value before logging, just as other GitHub error paths sanitize external output.
logger.error(
"Failed to update branch protection for %s on %s: %s",
branch,
repo,
res.stderr.strip()[:256],
src/devops_cli/github/branch_protection.py:114
BranchProtectionPolicy(**item)can raise a PydanticValidationErrorfor malformed policy fields, bypassing the loader'sGitHubOperationErrorcontract and structured error context. Wrap model validation in the domain exception;AGENTS.md:295requires domain errors to useDevOpsCLIError-derived exceptions.
policies.append(BranchProtectionPolicy(**item))
src/devops_cli/github/secrets.py:84
- Using
.get(..., '')means missing fields never raise the caughtKeyError: a successful{}response creates aGitHubPublicKeywith empty values, and the later failure is reported as encryption failure rather than an invalid GitHub response. Validate non-emptykey_idandkeybefore constructing the model.
return GitHubPublicKey(
key_id=str(data.get("key_id", "")),
key=str(data.get("key", "")),
)
except (json.JSONDecodeError, KeyError) as exc:
- Files reviewed: 12/12 changed files
- Comments generated: 11
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| required_status_checks: | ||
| strict: true | ||
| contexts: | ||
| - "ci" |
| def get_remote_branch_protection(repo: str, branch: str) -> dict[str, Any] | None: | ||
| """Fetch branch protection configuration from GitHub REST API via gh cli.""" | ||
| with trace_span("github.branch_protection.get", attributes={"repo": repo, "branch": branch}): | ||
| cmd = [CONST_GH_CLI, "api", f"repos/{repo}/branches/{branch}/protection"] |
Comment on lines
+133
to
+135
| if res.returncode != 0 or not res.stdout.strip(): | ||
| logger.debug("Branch %s has no protection or fetch failed: %s", branch, res.stderr) | ||
| return None |
| branch: str | None = None, | ||
| ) -> list[BranchProtectionAuditResult]: | ||
| """Audit branch protection settings against declared policies.""" | ||
| target_policies = [p for p in policies if branch is None or p.branch == branch] |
Comment on lines
+121
to
+126
| if clean_source == "vault": | ||
| from devops_cli.security.vault_broker import VaultSecretBroker | ||
|
|
||
| broker = VaultSecretBroker() | ||
| val = broker.get_secret(vault_path, key=name) | ||
| return str(val) if val is not None else None |
Comment on lines
+167
to
+180
| remote_contexts = set(checks_data.get("contexts", [])) | ||
| expected_contexts = set(policy.contexts) | ||
| missing_contexts = sorted(expected_contexts - remote_contexts) | ||
| if missing_contexts: | ||
| findings.append( | ||
| BranchProtectionAuditFinding( | ||
| branch=branch, | ||
| setting="required_status_checks.contexts", | ||
| expected=policy.contexts, | ||
| actual=list(remote_contexts), | ||
| compliant=False, | ||
| message=f"Missing required status checks: {', '.join(missing_contexts)}", | ||
| ) | ||
| ) |
Comment on lines
+95
to
+96
| cmd = [CONST_GH_CLI, "api", f"repos/{repo}/actions/secrets"] | ||
| res = run_subprocess(cmd, check=False, quiet=True) |
Comment on lines
+97
to
+99
| if res.returncode != 0 or not res.stdout.strip(): | ||
| logger.debug("Failed to list secrets for repository %s", repo) | ||
| return [] |
| ): | ||
| for name in unique_names: | ||
| secret_value = _resolve_secret_from_source(name, source=source, vault_path=vault_path) | ||
| if not secret_value: |
Comment on lines
+4
to
+5
| **PR**: [#197](https://github.com/dan-petty/devops-cli/pull/197) | ||
| **Status**: In Review |
dan-petty
added a commit
that referenced
this pull request
Sep 14, 2026
* feat(release): v0.2.17 * feat(sandbox): protocol-agnostic endpoint readiness and health probing subsystem (#107) Closes #107 * docs(agent): reconcile task 107 tracking to done (#107) * feat(telemetry): cgroup v2 metrics collection and prometheus application scraping (#108) Closes #108 * docs(agent): reconcile task 108 to done following PR #164 merge * docs(agent): require draft pull requests for in-progress work (#165) (#166) * docs(agent): require draft pull requests for in-progress work (#165) * docs(agent): align lifecycle definitions and update task index for PR #166 * fix(sandbox): resolve cpu delta sampling, ssrf boundaries, and cgroup fallback (#168) * fix(sandbox): remediate pr 164 review findings on sandbox metrics collection (#167) * test(sandbox): normalize whitespace in help assertion for variable terminal widths * test(sandbox): assert help option text without border wrapping sensitivity * fix(sandbox): address pr 168 review comments on url sanitization and telemetry contracts (#167) * fix(sandbox): resolve pr 168 review comments on cpu delta sampling, ssrf boundaries, and cgroup fallback (#167) * test(sandbox): remove redundant comment header in metrics tests * feat(pr): monitor pr checks, copilot reviews, and review threads (#170) (#171) * feat(github): automated pr monitoring and copilot review verification (#170) * fix(pr): resolve copilot review findings and enforce 5m/60s monitoring standards (#170) * feat(k8s): configurable k8s context setting and conditional minikube autostart (#172) (#174) * feat(k8s): configurable k8s context setting and conditional minikube autostart (#172) * docs(k8s): document minikube devcontainer lifecycle and external cluster configurations (#172) * fix(k8s): resolve copilot review findings for context validation and autostart (#172) * test(k8s): update qdrant secret lifecycle assertion for effective context flag (#172) * fix(github): project field options sync, complete pagination, generic owner resolution, and mock hostname standardization (#175) (#173) - Resolve automated GitHub Projects bot resetting status by auto-provisioning missing single-select options (e.g. 'In Review') - Implement complete pagination across projectsV2 items, issues, and PR endpoints - Resolve project owner dynamically via gh api user login without hardcoded usernames - Display draft PR warnings cleanly in monitor exit handler - Standardize all mock/dummy test values across all tests to example.com with no subdomain - Enforce complexity <= 10 and nesting <= 5 architectural invariants * fix(review): remediate devsecops findings and enhance review self-improvement loop (#176) (#177) * docs(agent): bootstrap task 176 for review findings remediation * fix(review): remediate DevSecOps findings and enhance review self-improvement loop (#176) * feat(telemetry): w3c traceparent propagation and distributed trace correlation (#109) (#178) * feat(telemetry): w3c traceparent propagation and distributed trace correlation (#109) * docs(agent): link draft PR 178 in task 109 tracking * fix(k8s): resolve helm ssa conflicts, loki validation, podsecurity, and qdrant permissions (#183) (#182) * fix(k8s): resolve helm ssa conflicts, loki validation, podsecurity, and qdrant permissions (#183) * docs(agent): link pull request #182 in task 183 tracking * feat(sandbox): streaming diagnostic log aggregator and panic detector (#110) (#179) * feat(sandbox): streaming diagnostic log aggregator and panic detector (#110) * docs(agent): link draft PR #179 in task-110 tracking * fix(sandbox): remediate review findings, demux streams, bound follow memory, and sanitize output (#110) * docs(agent): update task 110 status to In Review and record review thread resolutions * fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183) (#184) * fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183) * fix(github): remediate copilot review findings on pr merge readiness (#183) * fix(github): enforce review approval gate, exclude negative copilot headings, and forward tokens (#183) * fix(github): restrict copilot heading match, validate approval head sha, and support explicit env (#183) * fix(review): remediate DevSecOps findings and enhance review self-improvement loop (#185) (#186) * fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183) * fix(review): remediate session 20260913-060209 findings and enhance review self-improvement loop (#185) - sandbox probe: block metadata endpoints, bound regex len and search window, validate target URLs - telemetry waterfall: enforce hex trace ID validation and validate Jaeger endpoints against SSRF - telemetry context: add trace_flags parameter to generate_traceparent - sandbox logs: mask secrets in panic incidents and set 0o600 file / 0o700 dir permissions - sandbox metrics: reject cgroup path traversal and restrict parsing to valid cgroup hierarchies - sandbox models: truncate and mask probe result details and incident messages/stacktraces - sanitizer: mask secrets in non-flag arguments in sanitize_command_args_for_display - valkey client: correctly strip enclosing brackets from IPv6 hostnames - http client: validate timeout argument types - k8s stack lifecycle: mask non-localhost emails in bootstrap summary display - anti-hallucination dataset: calibrate false positives into common_hallucinations.json - documentation & prompts: update SELF_IMPROVEMENT.md, review.md, AGENTS.md, and task tracking * docs(agent): link pull request #186 in task 185 tracking * fix(review): address review feedback across sandbox, telemetry, k8s, and test fixtures (#185) - probe: canonicalize trailing dot and resolve host to block link-local/cloud metadata - waterfall: reject resolved metadata hosts and fix exception tuple in Jaeger trace query - k8s: mask short and malformed emails in bootstrap display and preserve PII in dry-run - pr monitor: exclude unknown mergeable_state from readiness and evaluate latest review per user - http client: raise HTTPTimeoutTypeError derived from ValidationError and TypeError - sandbox logs: unlink archive and raise SandboxError on incident chmod failure - sandbox metrics: enforce path-aware containment for cgroup v2 hierarchies - sandbox models: recursively sanitize nested details and reserve suffix length for truncation cap - telemetry context: raise TraceValidationError on invalid traceparent flags - conftest: detect and fail on unauthorized creation or deletion of workspace config.yaml - tasks: reconcile PR #184 mapping, update taxonomy to status/in-review, and re-sync index * fix(process): preserve GH_TOKEN and GITHUB_REPOSITORY for gh binary execution * fix(repo): prioritize git remote origin before GITHUB_REPOSITORY fallback * fix(security): pin vetted ip transports against dns rebinding and enforce clean merge state (#185) (#186) * feat(github): implement native devops cli functionality for gh operations and pr governance (#181) (#187) * feat(github): implement native devops cli functionality for gh operations and pr governance (#181) - Implement native devops pr ready, diff, and close subcommands - Implement native devops gh rate-limit and runs subcommands - Register FastMCP tools pr_ready, pr_diff, pr_close, gh_rate_limit, gh_runs_list, gh_run_view - Harden config discovery and add pytest safety barrier against workspace config mutations - Configure squid k8s deployment to use internal registry alias registry.local:5000 - Add comprehensive test coverage and documentation updates * feat(github): add REST fallbacks for pr view/checks, issues/pr edit, and resolve loki crashloop (#181) - Fall back to REST API in devops pr view and devops pr checks when GraphQL rate limits are exceeded - Add devops pr edit and devops gh issues edit subcommands - Register FastMCP tools pr_edit and gh_issue_edit - Disable loki-sc-rules sidecar in dev cluster k8s/logging/loki-values.yaml to eliminate k8s API watch crashloop - Add unit tests for pr/issue edit and REST fallbacks * docs(agent): link PR #187 in task 181 tracking * ci(workflows): gate pull request workflow on unresolved review threads and merge blockers (#188) - Update .github/workflows/ci.yml pull_request triggers to include ready_for_review - Add Verify PR Merge Readiness step to CI workflow calling devops pr check-readiness - Add devops pr check-readiness command and REST fallback for list_prs and list_threads - Add pr_check_readiness FastMCP tool and harden _run_mcp_cmd with mask_secrets - Sanitize output and validate formats in gh run view/list and pr view/checks/diff - Remediate and resolve 11 Copilot review findings across PR #187 * fix(process): preserve GH_TOKEN and GITHUB_REPOSITORY for gh binary execution * fix(repo): prioritize git remote origin before GITHUB_REPOSITORY fallback * fix(github): remediate review findings across pr readiness, sanitization, and rest fallbacks (#181) (#188) * fix(ci): support allow-blocked-state in pr check-readiness for github actions workflow * docs(agent): update task 181 checklist with passing ci checks and resolved review feedback * fix(github): add REST API fallback and rate limit handling for pr review threads (#180) (#189) (#191) * fix(github): add REST API fallback and rate limit handling for pr review threads (#180) (#189) * docs(agent): record PR #191 in task 180 tracking * docs(agent): require concise commit messages stating direct effect of change (#169) (#192) * fix(k8s): harden logging perimeter and scope fluent bit namespaces (#121) (#193) * chore(ci): align core dependencies and synchronize lockfile (#115) (#194) * feat(argo): implement automated gitops drift detection and watch command (#111) * feat(argo): implement automated gitops drift detection and watch command (#111) * fix(argo): address PR #195 review feedback on gitops webhook, secret masking, and baseline persistence * feat(github): declarative branch protection auditor and repository secret synchronization (#197) * feat(github): declarative branch protection auditor and repository secret synchronization * docs(agent): link PR #197 in task-114 tracking file * fix(github): lazily fetch public key during secret sync and isolate tests * chore(release): cut v0.2.17 and finalize release notes (#198) * feat(test): add deterministic async memory and connection pool profiler (#199) Implement deterministic async memory and connection pool profiler under devops test profile-memory (#199) Closes #199
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Implements declarative branch protection policy ruleset enforcement and libsodium-sealed repository secret synchronization:
.github/branch-protection.yml(devops gh branch-protection audit|sync).devops gh secrets sync).Closes #114