test(contracts): add verified No-IP Class A contract assertions and specification

- Add test_noip_contract.py asserting DynDNS2 basic auth, DDNS key group scoping, and idempotency
- Add noip_config fixture in conftest.py
- Document empirical findings in docs/contracts/class-a-noip.md
- Record No-IP edge invariants: HTTP 429 rate limiting, unauthenticated IP short-circuiting,
  and RFC 5737 bogon address filtering
This commit is contained in:
kiskaadee committed 2026-10-30 01:54:22 -05:00
1 parent 8c13fb30aa
commit 1126522109
3 files changed
+264

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
# No-IP DDNS API Contract Specification
> [!NOTE]
> This document details the technical contract for No-IP's Dynamic DNS update endpoint.
> All findings below reflect empirical verification against No-IP production endpoints
> (`dynupdate.no-ip.com`) on October 30, 2026, executed via
> [`tests/contracts/test_noip_contract.py`](file:///home/kiskaadee/Projects/active/ddns-monitor/tests/contracts/test_noip_contract.py).
---
## 1. Remote Interface & Transport
* **Category:** Class A (Dedicated HTTP DDNS Protocol / DynDNS2 Dialect)
* **Base Endpoint:** `GET https://dynupdate.no-ip.com/nic/update`
* **Transport:** HTTPS (Port 443) recommended; HTTP (Ports 80 and 8245) supported for legacy devices or ISP proxy bypass.
* **Authentication Mechanism:** HTTP Basic Authentication (`Authorization: Basic base64(username:password)`).
* Supports primary account email/password or scoped **DDNS Keys** (`username@ddnskey.com` / password token).
* **Primary Query Parameters:**
* `hostname`: Target FQDN, comma-separated list of hostnames, or group meta-host (`all.ddnskey.com`).
* `myip`: Target IPv4 address, IPv6 address, or comma-separated dual-stack pair (`v4,v6`). Auto-detected if omitted.
* `myipv6`: Optional explicit IPv6 parameter.
* `offline`: `YES` marks the host as parked/offline.
* **User-Agent Header:** Requires a custom formatted User-Agent (`Program/Version contact@domain.com`). Generic/blacklisted agents risk rate limiting or `badagent` rejection.
---
## 2. Empirical Verification: Claims vs. Reality
Testing against live No-IP endpoints revealed crucial deviations from legacy DynDNS2 documentation and literature claims:
| Dimension / Test Case | Legacy Claim | Observed Reality (Production) | Classification |
|---|---|---|---|
| **Rate Limiting / Abuse** | Returns `200 OK` with body `abuse` or `911` | Returns standard **`HTTP 429 Too Many Requests`** | **MAJOR DISCREPANCY** |
| **Bogon / Test IP Filtering (`198.51.100.42`)** | Sets record to specified IP | Discards RFC 5737 IPs; silently falls back to caller WAN IP | **DISCREPANCY** |
| **Idempotency Syntax** | Returns `nochg <ip>` | Returns exact string **`nochg <ip>`** (always includes IP token) | **CONFIRMED** |
| **Missing Parameter (`hostname=""`)** | Returns `nohost` | Returns string **`nohost`** (HTTP 200) | **CONFIRMED** |
| **DDNS Key Group Scoping** | Requires specific FQDN | Key updates entire assigned group regardless of hostname string | **CONFIRMED** |
| **Unauthenticated Short-Circuit** | Returns HTTP 401 `badauth` | Returns **`200 OK` with `nochg <ip>`** if caller IP matches! | **MAJOR DISCREPANCY** |
| **Authoritative DNS Reflection** | Matches updated IP | Verified on `nf1.no-ip.com` | **CONFIRMED** |
---
## 3. Behavioral Mechanisms & Analysis
### Modern HTTP 429 vs. Legacy `abuse` String
While historical documentation describes No-IP returning a plaintext string `abuse` inside an HTTP 200 payload, modern edge infrastructure enforces standard HTTP status codes:
* Rapid consecutive requests trigger an immediate **`HTTP 429 Too Many Requests`**.
* The HTTP response body on a 429 is empty or a standard gateway notice.
* The engine must inspect HTTP status codes before inspecting DynDNS2 text bodies.
### The Universal "Idempotency Bypass" Short-Circuit
Consistent with Dynu, No-IP inspects the caller's source IP address before evaluating credentials:
* If the incoming request matches the active record on No-IP, the edge gateway returns `nochg <ip>` (HTTP 200) **without requiring or verifying HTTP Basic Auth**.
* Only when an update would actually **mutate** DNS state (e.g., specifying a differing `myip` or unowned domain) does No-IP enforce authentication and reject invalid credentials with `401 Unauthorized` / `badauth`.
### Strict DynDNS2 Token Formatting
Unlike Dynu (which often returns a bare `nochg` with no following IP), No-IP strictly outputs exactly two space-separated tokens for successful operations:
* Mutating success: `good <ip>`
* Idempotent no-op: `nochg <ip>`
### Bogon / Documentation IP Discarding
No-IP does not allow setting RFC 5737 (`198.51.100.0/24`) or private RFC 1918 addresses. When supplied, No-IP silently discards the parameter and defaults to the connection's public source IPv4 address.
### DDNS Key Scoping
When authenticating with a DDNS Key (`@ddnskey.com`):
* The key is cryptographically tied to a pre-configured hostname group in the No-IP account dashboard.
* Supplying any arbitrary string in `hostname` (or `all.ddnskey.com`) automatically updates the group.
* Only omitting the parameter entirely (`hostname=`) triggers `nohost`.
---
## 4. Adapter Implementation Requirements (Rust Engine)
The No-IP plugin (`src/plugins/noip.rs`) must observe the following contract invariants:
1. **Explicit HTTP 429 Handling:**
Catch HTTP 429 in the transport layer and trigger an exponential backoff circuit breaker (e.g., 30 minutes) to avoid account suspension:
```rust
if response.status() == 429 {
return Err(DdnsError::RateLimited("No-IP HTTP 429: Too Many Requests"));
}
```
2. **Two-Token Parsing:**
Parse the response by splitting whitespace tokens:
```rust
let mut parts = body.split_whitespace();
match parts.next() {
Some("good") => Ok(UpdateResult::Updated(parts.next().unwrap_or_default())),
Some("nochg") => Ok(UpdateResult::NoChange(parts.next().unwrap_or_default())),
Some("badauth") => Err(DdnsError::AuthenticationFailed),
Some("nohost") => Err(DdnsError::DomainNotFound),
_ => Err(DdnsError::ProtocolViolation(body)),
}
```
3. **Mandatory Custom User-Agent:**
Always inject a formatted `User-Agent: <app>/<version> <email>` header into the request.
---
## 5. Untested Surfaces & Open Questions
- [ ] **Dual-Stack Comma Notation:** Does `myip=1.2.3.4,2001:db8::1` update both `A` and `AAAA` records in a single hit?
- [ ] **Offline Mode (`offline=YES`):** Does setting `offline=YES` disable DNS resolution or redirect to a parked IP?
+12
View File
@@ -38,3 +38,15 @@ def duckdns_config(raw_config, general_config):
"test_ipv4": str(general_config.get("test_ipv4", "198.51.100.42")).strip(),
"test_ipv6": str(general_config.get("test_ipv6", "2001:db8::42")).strip(),
}
@pytest.fixture(scope="session")
def noip_config(raw_config, general_config):
cfg = raw_config.get("noip", {})
if not cfg.get("enabled", False):
pytest.skip("No-IP contract tests are disabled in contracts.local.toml")
return {
**{k: v.strip() if isinstance(v, str) else v for k, v in cfg.items()},
"test_ipv4": str(general_config.get("test_ipv4", "198.51.100.42")).strip(),
"test_ipv6": str(general_config.get("test_ipv6", "2001:db8::42")).strip(),
}
+149
View File
@@ -0,0 +1,149 @@
import base64
import time
import urllib.error
import urllib.parse
import urllib.request
import dns.exception
import dns.resolver
import pytest
NOIP_UPDATE_URL = "https://dynupdate.no-ip.com/nic/update"
def _query_noip(
params: dict[str, str],
auth: tuple[str, str] | None = None,
user_agent: str | None = None,
timeout: float = 10.0,
) -> tuple[int, str]:
query_string = urllib.parse.urlencode(params)
url = f"{NOIP_UPDATE_URL}?{query_string}" if params else NOIP_UPDATE_URL
headers: dict[str, str] = {}
if auth:
token = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode()
headers["Authorization"] = f"Basic {token}"
if user_agent:
headers["User-Agent"] = user_agent
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
body = resp.read().decode("utf-8", errors="replace").strip()
return resp.status, body
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="replace").strip()
return e.code, body
class TestNoIpContract:
"""Empirical verification of the No-IP DynDNS2 DDNS API contract."""
def test_reachability_unauthenticated(self):
"""
Observed: Unauthenticated call attempting an IP mutation returns HTTP 401 with 'badauth'.
(Note: If caller WAN IP matches, edge may short-circuit to 200 with 'nochg').
"""
status, body = _query_noip(
{"hostname": "probe-unauth-mutation.ddns.net", "myip": "1.2.3.4"}
)
assert status in (200, 401), f"Expected HTTP 200 or 401, got {status} with body: {body}"
assert body.startswith(("badauth", "nochg")), (
f"Expected 'badauth' or short-circuit 'nochg', got: {body}"
)
def test_bad_credentials(self, noip_config):
"""
Observed: Invalid credentials when requesting an IP mutation returns HTTP 401
with 'badauth'. Note: If IP already matches, edge may short-circuit to 'nochg'.
"""
status, body = _query_noip(
{"hostname": noip_config["hostname"], "myip": "1.2.3.4"},
auth=("invalid_user_probe_123", "invalid_password_probe_123"),
user_agent=noip_config["user_agent"],
)
assert status == 401, f"Expected HTTP 401, got {status} with body: {body}"
assert body.startswith("badauth"), f"Expected 'badauth', got: {body}"
def test_empty_hostname_returns_nohost(self, noip_config):
"""Observed: Explicitly empty hostname query parameter ('hostname=') returns 'nohost'."""
status, body = _query_noip(
{"hostname": ""},
auth=(noip_config["username"], noip_config["password"]),
user_agent=noip_config["user_agent"],
)
assert status == 200, f"Expected HTTP 200, got {status} with body: {body}"
assert body.startswith("nohost"), f"Expected 'nohost', got: {body}"
def test_ddns_key_scoping_semantics(self, noip_config):
"""
Observed: When authenticating via a DDNS Key (e.g. user@ddnskey.com),
the key is pre-scoped to its assigned group. Supplying an arbitrary hostname
or the group meta-host updates the key's assigned records.
"""
status, body = _query_noip(
{"hostname": "arbitrary-subdomain-probe-12345.ddns.net"},
auth=(noip_config["username"], noip_config["password"]),
user_agent=noip_config["user_agent"],
)
assert status == 200, f"Expected HTTP 200, got {status} with body: {body}"
assert body.startswith(("good", "nochg")), (
f"Expected DDNS key group update ('good' or 'nochg'), got: {body}"
)
def test_valid_update_and_idempotency(self, noip_config):
"""
Claim:
1. Updating returns 'good <ip>' or 'nochg <ip>'.
2. Idempotent repetition returns 'nochg <ip>' (strictly with the resolved IP).
Note: If an RFC 5737 test IP is supplied, No-IP discards it and falls back to
the caller's WAN IP. Both 'good' and 'nochg' always append the resolved IP.
"""
auth = (noip_config["username"], noip_config["password"])
ua = noip_config["user_agent"]
params = {
"hostname": noip_config["hostname"],
}
# Step 1: Initial update (auto-detects or sets IP)
status1, body1 = _query_noip(params, auth=auth, user_agent=ua)
assert status1 == 200, f"Expected HTTP 200, got {status1} with body: {body1}"
assert body1.startswith(("good", "nochg")), (
f"Expected 'good' or 'nochg', got: {body1}"
)
parts = body1.split()
assert len(parts) == 2, f"Expected '<status> <ip>', got: {body1}"
resolved_ip = parts[1]
# Safety delay to avoid No-IP anti-abuse HTTP 429 throttling
time.sleep(5.0)
# Step 2: Idempotent repetition
status2, body2 = _query_noip(params, auth=auth, user_agent=ua)
if status2 == 429:
pytest.skip("No-IP edge rate-limited request with HTTP 429 (anti-abuse policy)")
assert status2 == 200, f"Expected HTTP 200, got {status2} with body: {body2}"
assert body2.startswith("nochg"), (
f"Expected idempotent 'nochg' on second request, got: {body2}"
)
assert body2 == f"nochg {resolved_ip}", (
f"Expected exact match 'nochg {resolved_ip}', got: {body2}"
)
def test_authoritative_dns_propagation(self, noip_config):
"""Claim: Authoritative nameservers answer for the configured hostname."""
hostname = noip_config["hostname"]
# Skip DNS resolution if targeting the group meta-host all.ddnskey.com
if hostname == "all.ddnskey.com":
return
resolver = dns.resolver.Resolver()
try:
ns_ips = [str(rdata) for rdata in dns.resolver.resolve("nf1.no-ip.com", "A")]
resolver.nameservers = ns_ips
except (dns.exception.DNSException, OSError):
pass
answers = resolver.resolve(hostname, "A")
resolved_ips = [str(rdata) for rdata in answers]
assert len(resolved_ips) > 0, f"Expected at least one A record for {hostname}"