Comprehensive Rules for building, testing, and operating automated macOS compliance tooling and workflows.
Your compliance team is drowning in spreadsheets, your Mac fleet is drifting from baseline, and every audit becomes a firefighting exercise. While you're manually checking FileVault status and screenshot interval settings across hundreds of devices, security gaps are widening by the hour.
Managing macOS compliance manually doesn't scale. You're facing:
Traditional approaches fail because they treat compliance as a checklist instead of continuous automation.
These Cursor Rules transform your development workflow into a compliance-first automation factory. You'll build Python-powered tooling that automatically enforces, monitors, and reports on security controls across your entire macOS environment.
Framework-Native Architecture: Every control maps directly to CIS, NIST, or PCI-DSS requirements with automatic evidence collection and standardized reporting.
MDM-Agnostic Integration: Whether you're using Jamf Pro, Microsoft Intune, or Kandji, you'll build unified automation that works across platforms through standardized API patterns.
Zero-Touch Operations: From enrollment to audit, your systems will maintain compliance automatically with intelligent remediation that minimizes user disruption.
Cut Audit Preparation from Weeks to Hours Instead of manually sampling devices and collecting screenshots, your automated tooling generates comprehensive compliance reports on-demand. Real scenario: Generate a complete CIS benchmark report across 1,000 Macs in under 10 minutes.
Eliminate Configuration Drift Continuous monitoring detects and corrects policy violations automatically. When a user disables FileVault or changes screensaver timeout, remediation happens within minutes, not months.
Scale Compliance Operations Add 100 new Macs to your environment? They automatically receive the complete security baseline during enrollment. No manual configuration, no missed controls.
Unified Multi-Framework Support Build once, comply everywhere. Your automation handles CIS benchmarks for general security, NIST 800-53 for federal requirements, and PCI-DSS for payment processing simultaneously.
# SSH into each Mac individually
ssh [email protected]
# Run manual checks
defaults read com.apple.screensaver idleTime
fdesetup status
# Record results in spreadsheet
# Repeat for 500+ devices
@dataclass(frozen=True)
class ComplianceControl:
id: str # CIS-2.3.2
severity: Literal["low", "medium", "high", "critical"]
framework: str
domain: str
key: str
expected_value: Any
async def audit_fleet(controls: list[ComplianceControl]) -> ComplianceReport:
"""Run complete compliance audit across Mac fleet"""
results = await gather(*[
audit_control(control, device_list)
for control in controls
])
return ComplianceReport(
compliant_devices=sum(r.compliant for r in results),
violations=sum(r.violations for r in results),
remediation_required=sum(r.needs_fix for r in results)
)
# CIS-5.1.1: Disable Guest Account
async def remediate_guest_account(device: MacDevice) -> RemediationResult:
"""Automatically disable guest account on non-compliant devices"""
try:
await mdm_client.push_profile(
device_id=device.id,
profile=GuestAccountProfile(enabled=False)
)
return RemediationResult.SUCCESS
except MDMError as e:
await alert_security_team(device, e)
return RemediationResult.FAILED
# .github/workflows/compliance-audit.yml
- name: Daily Compliance Scan
run: |
python -m compliance_tool audit --framework CIS --severity high
python -m compliance_tool report --format json --output compliance-report.json
- name: Auto-Remediate Low-Risk Violations
if: ${{ env.VIOLATIONS_FOUND == 'true' }}
run: |
python -m compliance_tool remediate --severity low --auto-approve
# Clone your compliance automation repository
git clone <your-repo>
cd macos-compliance-automation
# Install dependencies with compliance-focused tooling
pip install -r requirements.txt # httpx, rich, loguru, pydantic
# Configure pre-commit hooks for security
pre-commit install
# profiles/cis-benchmark.yaml
controls:
- id: CIS-2.3.2
severity: high
action: enforce
payload:
domain: com.apple.screensaver
key: idleTime
type: integer
value: 900 # 15 minutes
- id: CIS-5.1.1
severity: medium
action: audit
payload:
domain: com.apple.loginwindow
key: GuestEnabled
type: boolean
value: false
# src/mdm/jamf_client.py
@dataclass(frozen=True)
class JamfComplianceClient:
base_url: str
token: str
async def get_compliance_status(self, computer_id: str) -> ComplianceStatus:
"""Fetch current compliance state from Jamf Pro"""
data = await self._request("GET", f"/computers/id/{computer_id}")
return ComplianceStatus.from_jamf_data(data)
async def push_remediation_profile(self, profile: ComplianceProfile):
"""Deploy configuration profile for remediation"""
payload = profile.to_jamf_payload()
return await self._request("POST", "/configuration-profiles", json=payload)
# tests/test_compliance_controls.py
@pytest.mark.asyncio
async def test_filevault_enforcement():
"""Verify FileVault gets enabled automatically"""
mock_device = MacDevice(id="test-001", filevault_enabled=False)
result = await remediate_filevault(mock_device)
assert result.status == "remediated"
assert result.control_id == "CIS-5.8.1"
assert mock_device.filevault_enabled is True
# src/monitoring/compliance_monitor.py
class ComplianceMonitor:
def __init__(self, mdm_client: MDMClient):
self.mdm = mdm_client
async def run_continuous_audit(self):
"""Monitor compliance status every 4 hours"""
while True:
violations = await self.scan_for_violations()
if violations:
await self.handle_violations(violations)
await asyncio.sleep(14400) # 4 hours
Audit Preparation Time: Reduced from 2-3 weeks to 2-3 hours with automated evidence collection and standardized reporting.
Mean Time to Remediation: Cut from 15 days (manual process) to 4 hours (automated detection and fix) for standard policy violations.
Compliance Coverage: Achieve 99.5% baseline adherence across your Mac fleet instead of the typical 70-80% with manual processes.
Framework Readiness: Simultaneously maintain CIS Level 2, NIST 800-53 Moderate, and industry-specific requirements without additional manual overhead.
Operational Efficiency: Your security team focuses on strategic initiatives instead of device-by-device compliance checking, freeing up 60-70% of previously manual effort.
Your macOS compliance program transforms from reactive firefighting to proactive automation that scales with your organization and adapts to new requirements automatically.
You are an expert in macOS compliance automation.
Technology Stack Declaration
- Python 3.11 (automation, data-handling, API clients)
- Bash (Zsh-compatible) for lightweight on-device scripts
- YAML/JSON for declarative policy files
- MDM APIs: Jamf Pro, Kandji, Mosyle, VMware Workspace ONE, Microsoft Intune Graph
- Apple native security services: FileVault, Gatekeeper, XProtect, Endpoint Security
- CI/CD: GitHub Actions, GitLab CI, or Azure Pipelines
- Compliance Frameworks: CIS macOS Benchmark, NIST 800-53/171, PCI-DSS, HIPAA, ISO 27001
Key Principles
- Automate everything: zero-touch enrollment, baseline creation, audit, and remediation.
- Idempotent code & scripts: repeat executions must never create drift.
- Align every control with a framework reference (e.g., `CIS-2.3.2` comment in code).
- Treat the Mac as immutable infrastructure; never rely on user interaction.
- Fail fast, alert early; remediate silently when safe.
- Minimize user disruption: schedule heavy tasks during idle time, defer reboots.
- Store configuration as code (CaC) in Git; require code review & signed commits.
Python
- Follow PEP8 + Black formatting; enforce with pre-commit.
- Use type hints everywhere, enable `mypy --strict`.
- Organize repo with `src/`, `tests/`, `profiles/`, `scripts/`.
- Use `dataclass(frozen=True)` for immutable compliance objects.
- Prefer `pathlib.Path` over raw paths.
- Wrap MDM API calls in dedicated client classes; expose only async public methods.
- Use `rich` or `loguru` for structured, colorized CLI output.
- Sample client skeleton:
```python
from __future__ import annotations
from dataclasses import dataclass
import httpx
@dataclass(frozen=True)
class JamfClient:
base_url: str
token: str
async def _request(self, method: str, url: str, **kw):
async with httpx.AsyncClient(timeout=30) as client:
r = await client.request(method, f"{self.base_url}{url}", headers={"Authorization": f"Bearer {self.token}"}, **kw)
r.raise_for_status()
return r.json()
async def get_computers(self):
return await self._request("GET", "/JSSResource/computers")
```
Bash (Zsh-compatible)
- Start every script with `#!/usr/bin/env bash` and `set -euo pipefail`.
- Validate input early; abort if running as root when not required.
- Always return explicit exit codes (0 success, 1 error, 2 remediated).
- Example remediation stub:
```bash
#!/usr/bin/env bash
set -euo pipefail
if [[ $(fdesetup status) == "FileVault is On." ]]; then
exit 0
else
echo "Turning on FileVault…" >&2
fdesetup enable -user "$USER"
exit 2
fi
```
Error Handling & Validation
- Wrap every API call in retry logic with exponential back-off (≤3 attempts).
- Normalise and centralise exceptions: raise `ComplianceDriftError`, `RemediationError`, `MDMApiError`.
- Log to macOS unified logging (subsystem `com.company.compliance`).
- In CI, fail pipeline if any control is `non_compliant` or `remediation_failed`.
- Immediate remediation allowed only for LOW impact controls; HIGH impact require approval workflow.
Framework-Specific Rules
Jamf Pro
- Use Jamf Pro Configuration Profiles for settings; reserve custom scripts for gaps.
- Tag every Script payload with `#control: CIS-5.5.1 #severity: medium`.
- Use Patch Management to enforce minimum OS version within 15 days of release.
Microsoft Intune
- Use Device Compliance policies first, then custom PLIST profile with OMA-URI when unavailable.
- Names: `macOS_<framework>_<control>_<severity>` (e.g., `macOS_CIS_2.3.2_high`).
MDM-Agnostic
- Baselines live in `profiles/*.yaml`. Schema:
```yaml
id: CIS-2.3.2
severity: high
action: enforce
payload:
domain: com.apple.screensaver
key: idleTime
type: integer
value: 900
```
- A single Python generator converts YAML → MDM-specific JSON.
Additional Sections
Testing
- Write pytest unit tests with fixtures mocking MDM API.
- Weekly scheduled GitHub Action runs `maclint scan --simulate --all-controls`.
- Use `osquery` in CI to simulate endpoint responses.
Performance
- Batch API calls (≤100 devices per request) to avoid rate limits.
- Cache static lookups (e.g., framework mapping) in Redis for 24 h.
Security
- Store API tokens in macOS Keychain (local) or GitHub OIDC secrets (CI).
- Enable HTTP Strict Transport Security (HSTS) for self-hosted Jamf.
- Require mutual TLS for any on-prem MDM integrations.
Documentation & Versioning
- Markdown in `docs/controls/`. Each file: title, framework refs, rationale, test, remediation, rollback.
- Version baseline schema with SemVer; bump MAJOR on breaking control ID changes.
Release Workflow
1. PR merged ➜ CI runs full lint/test/audit.
2. Tag `vX.Y.Z` ➜ pipeline builds `baseline.pkg` signed & notarised.
3. MDM pushes package to Smart Group `Baseline Pending`.
4. Post-deploy health check marks group `Baseline Compliant`.