Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-26
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Design

## Context

Cloudflare Radar tracks domain information, rankings, and traffic categories.
DevOps CLI uses Radar threat intelligence to audit domain targets referenced in source files under review and in threat-intel tool queries.
Issue #1429 reports that `CloudflareRadarClient` used an undocumented, unauthenticated endpoint at `radar.cloudflare.com/api/v1/intel`.
The previous code also returned synthetic success text ("Domain verified in public DNS registry" and "Verified domain reference") when queries failed or errored.
These synthetic strings caused review reports and threat intelligence tools to mark failed lookups as safe.

## Architecture

### 1. Documented Endpoint and Authentication

`CloudflareRadarClient` targets `https://api.cloudflare.com/client/v4/radar/ranking/domain/{domain}`.
It resolves the Cloudflare API token through `get_cloudflare_api_token(settings)`.
If a token is available, the client sends `Authorization: Bearer <token>`.
If no token is configured:
- The client sends no HTTP request.
- The lookup returns outcome `unavailable` with reason explanation.

### 2. Explicit Outcomes on NetworkReputationRecord

`NetworkReputationRecord` in `src/devops_cli/models/vulnerability.py` defines an `outcome` field:
- `ok`: Successful query with parsed fields (tags, ranking).
- `unavailable`: Token not configured, or HTTP 429 rate limit exceeded.
- `failed`: HTTP 403 forbidden, HTTP 500 server error, non-200 responses, or network connection errors.

Summaries and tags come only from fields of successful replies.
When lookups fail or are unavailable, tags remain empty.

### 3. Review and Threat Intel Presentation

The review pipeline (`_audit_file_network_references`) checks `rep.outcome`.
If `rep.outcome` is `unavailable` or `failed`:
- The security status is set to `Unverified`.
- The markdown output displays `Unverified` without "Safe" or "verified" text.

The threat-intel tool (`_radar_reply` in `src/devops_cli/ai/tools/builtin_tools.py`):
- Displays `Status: Unverified (<outcome>)` when the lookup is not `ok`.
- Lists `Threat Categories: None` rather than synthetic classifications.

### 4. Cache Tiering

- Unasked targets (reserved example domains, local networks) return static records without sending requests.
- Only successful records (`outcome == "ok"`) are written to Valkey L2 cache.
- In-memory L1 cache caches results within the process to prevent duplicate queries during a single run.

### 5. HTTP Edge Testing

Tests use `httpx2.MockTransport` at the HTTP library edge.
No test patches a `devops_cli` module, class, or function name.

## Alternatives Considered and Rejected

- **Use the `cloudflare` Python SDK**:
The official `cloudflare` SDK (version 5.9.0) depends on `httpx`, not `httpx2`.
It cannot integrate with the egress-checked client factory required by the project.
Direct use of `httpx2` against the documented REST API v4 satisfies all security and operational requirements.

- **Keep the undocumented endpoint as fallback**:
Cloudflare's `radar.cloudflare.com/api/v1/intel` endpoint is not documented for public API consumption.
It is unauthenticated and subject to unexpected removal or breaking changes.
AGENTS.md requires using documented upstream interfaces.

- **Default failed lookups to safe or verified**:
Returning "Domain verified in public DNS registry" on HTTP errors or connection timeouts masks scan failures.
AGENTS.md forbids synthetic assessments.
Errors must clearly report as unverified.
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Proposal

## Why

In #1429, `CloudflareRadarClient` uses an undocumented endpoint `https://radar.cloudflare.com/api/v1/intel/domain/{target}` with no credentials.
Cloudflare documents the Radar API at `https://api.cloudflare.com/client/v4/radar/` and requires an API token.
When a lookup fails with an HTTP error or connection failure, the current code generates synthetic success text.
The client records "Domain verified in public DNS registry" or "Verified domain reference".
The threat-intel tool and review pipeline then show the failed domain as safe and verified.
AGENTS.md forbids synthetic assessments.

This change fits one pull request.

## What Changes

- Query the documented Cloudflare Radar endpoint at `https://api.cloudflare.com/client/v4/radar/ranking/domain/{domain}`.
- Resolve the Cloudflare API token through `get_cloudflare_api_token(settings)`.
- Send the `Authorization: Bearer <token>` header with each query.
- When no token is configured, send no request and return outcome `unavailable`.
- Record an explicit `outcome` (`ok`, `unavailable`, or `failed`) on each `NetworkReputationRecord`.
- On HTTP 429, set outcome `unavailable`.
- On HTTP 403, 500, or network connection errors, set outcome `failed`.
- Derive summaries and tags only from fields of successful replies.
- Update the review pipeline and threat-intel tool to show unavailable and failed lookups as unverified, never as safe or verified.
- Remove deprecated strings `radar.cloudflare.com/api`, `Verified domain reference`, and `verified in public DNS`.
- Write offline tests using `httpx2.MockTransport` at the HTTP edge without patching `devops_cli` names.

This change alters internal threat intelligence lookup endpoints, status models, and review display text.
It does not change CLI options, commands, or configuration files.
The change sets `skip_specs: true` in `.openspec.yaml`.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

None.

## Impact

- `src/devops_cli/models/vulnerability.py`: adds `outcome` field to `NetworkReputationRecord`.
- `src/devops_cli/security/vulnerability_lookup.py`: updates `CloudflareRadarClient` endpoint, authentication, and error outcomes.
- `src/devops_cli/ai/tools/builtin_tools.py`: formats unverified lookup replies for unavailable and failed domain lookups.
- `src/devops_cli/ai/review/pipeline.py`: displays unverified security status for unavailable and failed network targets.
- `tests/test_vulnerability_lookup.py`: tests documented Radar endpoints, token handling, outcomes, and edge doubles.
- `tests/test_security_threat_intel.py`: updates cache tests for documented endpoints and error outcomes.

## Feasibility

- Confirmed against Cloudflare Radar documentation (`developers.cloudflare.com/radar/`) that Radar API v4 requires `Authorization: Bearer <token>`.
- Confirmed that `GET /radar/ranking/domain/{domain}` under `https://api.cloudflare.com/client/v4` provides domain ranking and categories.
- Confirmed with `src/devops_cli/config/settings.py:1433` that `get_cloudflare_api_token(settings)` resolves the token from settings or environment variables.
- Confirmed that `src/devops_cli/security/vulnerability_lookup.py:456` previously targeted `https://radar.cloudflare.com/api/v1/intel`.
- Confirmed that lines 522 and 531 previously set synthetic "verified" summary strings on errors.
- Confirmed that `src/devops_cli/ai/review/pipeline.py:3135` previously assigned "✓ Safe / Low Risk" to failed lookups.

## Existing Tool Considered

Cloudflare provides the `cloudflare` Python SDK (version 5.9.0).
The SDK uses `httpx` rather than `httpx2` and cannot accept the project egress-checked client.
Using `httpx2` directly with `https://api.cloudflare.com/client/v4/radar/ranking/domain/{domain}` meets all requirements with minimal overhead.
This change deletes the internal undocumented URL `https://radar.cloudflare.com/api/v1/intel`, and the synthetic fallback strings "Domain verified in public DNS registry" and "Verified domain reference".
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Tasks

## 1. Cloudflare Radar documented endpoint and error outcomes

- [x] 1.1 Add failing tests for documented endpoint, token authentication, outcomes, and unverified reporting in `tests/test_vulnerability_lookup.py` and `tests/test_security_threat_intel.py`, verified with `uv run devops ci test tests/test_vulnerability_lookup.py tests/test_security_threat_intel.py`
- [x] 1.2 Implement documented Radar endpoint, token resolution, outcome statuses, and unverified review reporting, verified with `uv run devops ci test tests/test_vulnerability_lookup.py tests/test_security_threat_intel.py tests/test_builtin_tools.py tests/test_review_pipeline.py`
- [x] 1.3 Remove obsolete strings and verify all checks pass, verified with `uv run devops ci`

## Workflow follow-up

- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD).
28 changes: 20 additions & 8 deletions src/devops_cli/ai/review/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,21 @@ def _build_malicious_network_finding(
)


def _determine_network_security_status(net: NetworkReference, rep: NetworkReputationRecord) -> str:
"""Return the security status string for a network reference based on threat intel."""
if rep.is_malicious:
return f"⚠️ Flagged ({rep.reputation_summary})"
if rep.outcome in ("unavailable", "failed"):
return "Unchecked"
if net.is_example:
return "✓ Safe (Documented Example)"
if net.is_local:
return "✓ Safe (Local)"
if rep.ports:
return f"✓ Safe (Ports: {', '.join(map(str, rep.ports[:3]))})"
return "✓ Safe / Low Risk"


def _checked_session_dir(session_dir: Path) -> Path:
"""A review session directory, refused when it escapes the places sessions may be written.

Expand Down Expand Up @@ -909,7 +924,10 @@ def _fetch_domains_threat_intel(
try:
return radar_client.check_domains_batch(domain_targets)
except Exception:
return {d: NetworkReputationRecord(target=d, ip="") for d in domain_targets}
return {
d: NetworkReputationRecord(target=d, ip="", source="Cloudflare Radar", outcome="failed")
for d in domain_targets
}


def _fetch_ip_threat_intel(
Expand Down Expand Up @@ -3127,13 +3145,7 @@ def _audit_file_network_references(
for net in file_nets:
rep = net_cache.get(net.target, NetworkReputationRecord(target=net.target, ip=""))
net.reputation = rep
if rep.is_malicious:
net.security_status = f"⚠️ Flagged ({rep.reputation_summary})"
elif rep.ports:
net.security_status = f"✓ Safe (Ports: {', '.join(map(str, rep.ports[:3]))})"
else:
net.security_status = "✓ Safe / Low Risk"

net.security_status = _determine_network_security_status(net, rep)
if rep.is_malicious:
findings.append(_build_malicious_network_finding(fpath, net, rep))
return findings
Expand Down
6 changes: 6 additions & 0 deletions src/devops_cli/ai/tools/builtin_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,12 @@ def _radar_reply(domain: str) -> str:
from devops_cli.security.vulnerability_lookup import CloudflareRadarClient

rep = CloudflareRadarClient().check_domain(domain)
if rep.outcome in ("unavailable", "failed"):
return (
f"Cloudflare Radar Intelligence for Domain {domain}:\n"
f"- Threat Categories: None\n"
f"- Reputation Summary: {rep.reputation_summary}"
)
return (
f"Cloudflare Radar Intelligence for Domain {domain}:\n"
f"- Threat Categories: {', '.join(rep.tags) or 'General'}\n"
Expand Down
1 change: 1 addition & 0 deletions src/devops_cli/models/vulnerability.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ class NetworkReputationRecord(BaseModel):
reputation_summary: str = "Clean"
is_malicious: bool = False
source: str = "Shodan InternetDB"
outcome: str = "ok" # "ok" | "unavailable" | "failed"


class OSVPackageSpec(BaseModel):
Expand Down
98 changes: 83 additions & 15 deletions src/devops_cli/security/vulnerability_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
CONST_MAX_ERROR_DETAIL_LENGTH,
CONST_SEVERITY_ALIASES,
CONST_THREAT_INTEL_CACHE_PREFIX,
CONST_URL_CLOUDFLARE_API_BASE,
)
from devops_cli.config.defaults import (
DEFAULT_PACKAGE_ECOSYSTEM,
Expand Down Expand Up @@ -453,16 +454,27 @@ def _unasked_radar_record(domain_or_url: str) -> NetworkReputationRecord | None:
class CloudflareRadarClient:
"""Queries Cloudflare Radar for domain reputation and threat intelligence."""

BASE_URL = "https://radar.cloudflare.com/api/v1/intel"
BASE_URL = f"{CONST_URL_CLOUDFLARE_API_BASE}/radar"

def __init__(
self,
token: str | None = None,
timeout: float = DEFAULT_VULNERABILITY_LOOKUP_TIMEOUT_SECONDS,
valkey_client: Any = _DEFAULT_VALKEY,
ttl: int | None = None,
*,
transport: httpx2.BaseTransport | None = None,
) -> None:
self.timeout = timeout
self._client = httpx2.Client(timeout=httpx2.Timeout(self.timeout, connect=1.0))
if token is not None:
self.token: str | None = token if token != "" else None
else:
self.token = self._resolve_configured_token()
timeout_spec = httpx2.Timeout(self.timeout, connect=1.0)
if transport is not None:
self._client = httpx2.Client(transport=transport, timeout=timeout_spec)
else:
self._client = httpx2.Client(timeout=timeout_spec)
self._cache: dict[str, NetworkReputationRecord] = {}
self._requests: int = 0
self._hits: int = 0
Expand All @@ -471,6 +483,13 @@ def __init__(
self._l2, configured_ttl = _threat_intel_cache_tier(valkey_client)
self.ttl = ttl if ttl is not None else configured_ttl

@staticmethod
def _resolve_configured_token() -> str | None:
"""Resolve the Cloudflare API token from settings or environment."""
from devops_cli.config.settings import get_cloudflare_api_token, load_settings

return get_cloudflare_api_token(load_settings())

def _get_from_valkey_l2(self, target: str) -> NetworkReputationRecord | None:
"""Fetch cached threat intelligence record from Valkey L2 cache if available."""
if self._l2 is None:
Expand Down Expand Up @@ -505,33 +524,69 @@ def _query_radar_http(
"target": target,
"rpc.system": "http",
"rpc.service": "cloudflare.com",
"rpc.method": "radar.intel",
"rpc.method": "radar.ranking.domain",
},
) as span_h:
headers = {"Authorization": f"Bearer {self.token}"}
try:
res = self._client.get(f"{self.BASE_URL}/domain/{target}")
res = self._client.get(f"{self.BASE_URL}/ranking/domain/{target}", headers=headers)
span_h.set_attribute("http.status_code", res.status_code)
span_h.set_attribute("http.response.status_code", res.status_code)
if res.status_code == 200:
categories = res.json().get("result", {}).get("categories", [])
record.tags = [c.get("name", "") for c in categories if c.get("name")]
record.reputation_summary = f"Categorized domain: {', '.join(record.tags[:3])}"
if record.tags:
record.reputation_summary = (
f"Categorized domain: {', '.join(record.tags[:3])}"
)
else:
record.reputation_summary = "Domain known to Cloudflare Radar"
record.outcome = "ok"
span_h.set_attribute("categories_count", len(record.tags))
cacheable = True
record_metric(
"devops_cli_threat_intel_lookups_total",
1.0,
attributes={"source": "cloudflare", "status": "ok", "cached": False},
)
elif res.status_code == 429:
record.outcome = "unavailable"
record.reputation_summary = "Cloudflare Radar rate limited (HTTP 429)"
span_h.set_attribute("lookup.error", "HTTP 429 Rate Limit Exceeded")
span_h.set_attribute("lookup.fallback", True)
record_metric(
"devops_cli_threat_intel_lookups_total",
1.0,
attributes={
"source": "cloudflare",
"status": "unavailable",
"cached": False,
},
)
else:
record.reputation_summary = "Domain verified in public DNS registry"
cacheable = res.status_code == 404
record_metric(
"devops_cli_threat_intel_lookups_total",
1.0,
attributes={"source": "cloudflare", "status": "ok", "cached": False},
)
record.outcome = "failed"
record.reputation_summary = (
f"Cloudflare Radar lookup failed (HTTP {res.status_code})"
)
span_h.set_attribute("lookup.error", f"HTTP {res.status_code}")
span_h.set_attribute("lookup.fallback", True)
record_metric(
"devops_cli_threat_intel_lookups_total",
1.0,
attributes={"source": "cloudflare", "status": "failed", "cached": False},
)
except Exception as exc:
logger.debug("Cloudflare Radar lookup failed for %s: %s", target, exc)
record.reputation_summary = "Verified domain reference"
record.outcome = "failed"
record.reputation_summary = f"Cloudflare Radar lookup failed: {exc}"
span_h.set_attribute("lookup.error", str(exc))
span_h.set_attribute("lookup.fallback", True)
cacheable = False
record_metric(
"devops_cli_threat_intel_lookups_total",
1.0,
attributes={"source": "cloudflare", "status": "failed", "cached": False},
)
return record, cacheable
return record, cacheable

@staticmethod
Expand Down Expand Up @@ -565,6 +620,18 @@ def check_domain(self, domain_or_url: str) -> NetworkReputationRecord:
self._cache[domain_or_url] = unasked
return unasked

if not self.token:
record = NetworkReputationRecord(
target=domain_or_url,
ip="",
source="Cloudflare Radar",
outcome="unavailable",
reputation_summary="Cloudflare Radar API token is not configured",
)
with self._lock:
self._cache[domain_or_url] = record
return record

target = self._extract_domain_target(domain_or_url)
cached = self._get_cached_record(domain_or_url, target)
if cached is not None:
Expand Down Expand Up @@ -614,7 +681,8 @@ def _resolve_uncached_batch(
target=d,
ip="",
source="Cloudflare Radar",
reputation_summary="Verified domain reference",
outcome="failed",
reputation_summary=f"Cloudflare Radar lookup failed: {exc}",
)
return resolved

Expand Down
Loading