From 742e58a5069ac55dfd4ba3d99ed3b0b91ca2a706 Mon Sep 17 00:00:00 2001 From: Jacob Page Date: Tue, 3 Nov 2026 17:34:25 -0800 Subject: [PATCH 1/5] fix(dns): replace records in place with dns set and confirm the final result `dns set` now replaces each record it keeps with a single in-place update instead of creating the new value and then deleting the old record. A replaced record keeps its ID, a TTL-only change is one call, and a failed update leaves the existing record untouched rather than leaving two values at the name. - Records that already match what you asked for are reported as `unchanged` and left alone, so running the same `set` twice changes nothing the second time. The result gains an `unchanged` count and `replaced` no longer includes them. - A replaced record keeps its current TTL unless you pass `--ttl`. - The result lists the records now in place, including their IDs. - After writing, `set` reads the type and name back and fails if the records there are not the ones you asked for, for example because someone else changed them while it ran. It lists what is extra and what is missing and removes nothing. - `--ttl` is checked up front for both `dns add` and `dns set`: 600 to 86400 seconds. Co-Authored-By: Claude Sonnet 5.5 --- rust/domains-client/openapi/domains.oas3.json | 111 ++++ rust/domains-client/src/lib.rs | 14 +- rust/src/dns/add.rs | 14 +- rust/src/dns/guides/dns.md | 8 +- rust/src/dns/list.rs | 4 +- rust/src/dns/records.rs | 9 +- rust/src/dns/records_tests.rs | 37 ++ rust/src/dns/set/mod.rs | 92 ++- rust/src/dns/set/outcome.rs | 78 ++- rust/src/dns/set/plan.rs | 124 +++-- rust/src/dns/set/verify.rs | 173 ++++++ rust/src/dns/set/verify_tests.rs | 225 ++++++++ rust/src/dns/set/write.rs | 263 +++------ rust/src/dns/set/write_tests.rs | 525 +++++------------- .../generate-api-catalog/src/domains_spec.rs | 28 +- 15 files changed, 990 insertions(+), 715 deletions(-) create mode 100644 rust/src/dns/set/verify.rs create mode 100644 rust/src/dns/set/verify_tests.rs diff --git a/rust/domains-client/openapi/domains.oas3.json b/rust/domains-client/openapi/domains.oas3.json index 44a0501b..c1495906 100644 --- a/rust/domains-client/openapi/domains.oas3.json +++ b/rust/domains-client/openapi/domains.oas3.json @@ -4069,6 +4069,117 @@ "tags": [ "Records" ] + }, + "put": { + "description": "Fully replaces an existing DNS resource record identified by\nrecordId within the zone. All writable fields applicable to the\nrecord type must be supplied; partial updates are not supported\non this endpoint. Changes are applied synchronously.\n\nGoDaddy-managed system records (SOA and NS) are read-only. When\nrecordId refers to such a record, the request fails with\n`409 Conflict` — the record exists but cannot be modified.\n", + "operationId": "replaceDNSRecord", + "parameters": [ + { + "description": "Optional client-generated request correlation identifier, propagated across services and returned in the response X-Request-Id header.\n", + "in": "header", + "name": "X-Request-Id", + "required": false, + "schema": { + "$ref": "#/components/schemas/uuid" + } + }, + { + "description": "Reseller acting on behalf of a shopper account. When present, all domain operations are scoped to the specified shopper. Absent, the authenticated entity's own account is used. Only valid for reseller OAuth tokens.\n", + "example": "shopper_123", + "in": "header", + "name": "X-Shopper-Id", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "The domain name in punycode A-label form (e.g., example.com). For IDNs, use the punycode representation.\n", + "example": "example.com", + "in": "path", + "name": "zone", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Server-assigned DNS record identifier within the zone.", + "example": "Aad7oqdXCms9mlJvm_m6UFYqmwjyP20H2KBmQHgttK9kGbF_TuI3knsocArQqIv5I0Kq5C0", + "in": "path", + "name": "recordId", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "apexARecord": { + "summary": "Replace apex A record", + "value": { + "data": "192.0.2.1", + "name": "@", + "ttl": 3600, + "type": "A" + } + }, + "tlsaRecord": { + "summary": "Replace a TLSA record (rotate to new SPKI pin)", + "value": { + "certificateData": "a3b4c5d6e7f8091a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a", + "matchingType": 1, + "name": "www", + "port": 443, + "protocol": "_tcp", + "selector": 1, + "ttl": 3600, + "type": "TLSA", + "usage": 3 + } + } + }, + "schema": { + "$ref": "#/components/schemas/DNSRecord" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DNSRecord" + } + } + }, + "description": "DNS record replaced.", + "headers": { + "X-Request-Id": { + "description": "Request correlation identifier echoed from the request or server-generated.", + "schema": { + "$ref": "#/components/schemas/uuid" + } + } + } + } + }, + "security": [ + { + "oauth2": [ + "domains.dns:update" + ] + } + ], + "summary": "Replace a DNS record", + "tags": [ + "Records" + ] } } }, diff --git a/rust/domains-client/src/lib.rs b/rust/domains-client/src/lib.rs index acc5de12..dfed9105 100644 --- a/rust/domains-client/src/lib.rs +++ b/rust/domains-client/src/lib.rs @@ -716,21 +716,15 @@ mod tests { } #[test] - fn replace_dns_record_stays_removed() { - // See https://github.com/godaddy/cli/issues/136 and the `NOTE:` - // comment above `/zones/{zone}/dns-records/{recordId}` in the - // vendored v3 yaml: this PUT returns 200 but silently replaces the - // entire dns-records collection instead of the one record. A spec - // sync that copies the upstream shape verbatim would reintroduce it. + fn replace_dns_record_is_exposed() { + // `dns set` replaces a retained record in place with this PUT. let spec = vendored_spec(); let methods = spec["paths"]["/v3/domains/zones/{zone}/dns-records/{recordId}"] .as_object() .expect("dns-records/{recordId} path exists"); assert!( - !methods.contains_key("put"), - "replaceDNSRecord (PUT) must stay excluded until a confirmed \ - server-side fix and a fresh live check against a real zone with \ - unrelated records — see godaddy/cli#136" + methods.contains_key("put"), + "replaceDNSRecord (PUT) missing" ); } } diff --git a/rust/src/dns/add.rs b/rust/src/dns/add.rs index d5da2c9b..f2e92be9 100644 --- a/rust/src/dns/add.rs +++ b/rust/src/dns/add.rs @@ -105,13 +105,13 @@ pub(super) fn command() -> RuntimeCommandSpec { ) .with_long( "Appends one or more DNS records to a domain without modifying any \ - existing records. Pass `--data` once per record value to add \ - multiple records for the same type+name (each is a separate v3 \ - create call). `--ttl` defaults to 3600 when omitted. DNS only \ - allows a CNAME or other record types at a name, never both — \ - adding into a name that already has the other kind fails with a \ - specific error naming the conflicting record. Use `dns set` to \ - replace the full record set for a type+name.", + existing records. Pass `--data` once per record value to add \ + multiple records for the same type+name (each is a separate v3 \ + create call). `--ttl` is 600 to 86400 seconds and defaults to 3600 \ + when omitted. DNS only allows a CNAME or other record types at a \ + name, never both — adding into a name that already has the other \ + kind fails with a specific error naming the conflicting record. Use \ + `dns set` to replace the full record set for a type+name.", ) .with_system("domain") .with_tier(Tier::Mutate) diff --git a/rust/src/dns/guides/dns.md b/rust/src/dns/guides/dns.md index fbfa8ee6..479f835b 100644 --- a/rust/src/dns/guides/dns.md +++ b/rust/src/dns/guides/dns.md @@ -33,13 +33,13 @@ Without filters, `list` returns every record. `--type` narrows to one record typ gddy dns add example.com --type A --name www --data 192.0.2.1 --ttl 3600 ``` -Pass `--data` more than once to add several records for the same type+name in one call — each becomes a separate record, and a failure on one doesn't stop the rest (the result reports created/failed counts with a per-value breakdown). `--ttl` defaults to 3600 seconds when omitted. +Pass `--data` more than once to add several records for the same type+name in one call — each becomes a separate record. `--ttl` is in seconds, from 600 (10 minutes) to 86400 (24 hours), and defaults to 3600 when omitted. A name can hold a CNAME or other record types, never both. Adding into a name that already has the other kind fails with an error naming the conflict — see `set --replace-conflicting-types` below if you actually want to replace it. ## Replacing records (`set`, destructive) -`set` replaces every record matching a type+name pair with exactly the `--data` value(s) you give it. It reconciles rather than deleting and recreating everything: existing records are paired with your `--data` values, whatever's no longer in your list is deleted, and whatever's new is created. There's no atomic in-place replace in v3, so each paired value is written as a new record before the old one it's replacing is deleted — record IDs are not reused across a replace. +`set` replaces every record matching a type+name pair with exactly the `--data` value(s) you give it. ``` gddy dns set example.com --type TXT --name @ --data "v=spf1 -all" @@ -51,9 +51,7 @@ Preview the plan before writing: gddy dns set example.com --type TXT --name @ --data "v=spf1 -all" --dry-run ``` -The dry-run preview lists the planned action (replace/create/delete) per record so you can confirm it before it runs for real. `set` is not atomic — a partial failure reports how many records were replaced, created, and deleted before it happened. - -To also remove a conflicting CNAME (or, when setting a CNAME, any other type) at that name, add `--replace-conflicting-types`. +The dry-run preview lists the planned action per record so you can confirm it before it runs for real. ## Deleting records diff --git a/rust/src/dns/list.rs b/rust/src/dns/list.rs index a785cba1..c1e20991 100644 --- a/rust/src/dns/list.rs +++ b/rust/src/dns/list.rs @@ -107,7 +107,9 @@ pub(super) fn command() -> RuntimeCommandSpec { /// The original `certificateData`/`usage`/`selector`/`matchingType` fields /// are left in place alongside it. Pure so the merge is unit-testable /// without a mock server. -fn build_list_output(records: &[types::DnsRecord]) -> Result, serde_json::Error> { +pub(super) fn build_list_output( + records: &[types::DnsRecord], +) -> Result, serde_json::Error> { records .iter() .map(|rec| { diff --git a/rust/src/dns/records.rs b/rust/src/dns/records.rs index fa3c7772..a0e5ec56 100644 --- a/rust/src/dns/records.rs +++ b/rust/src/dns/records.rs @@ -25,6 +25,9 @@ pub(super) const LISTABLE_TYPES: &[&str] = &[ ]; /// Default TTL (seconds) for `dns add`/`set` when `--ttl` is omitted (v3 requires a ttl). pub(super) const DEFAULT_TTL: i64 = 3600; +/// The TTL range (seconds) the API accepts: 10 minutes to 24 hours. +const MIN_TTL: i64 = 600; +const MAX_TTL: i64 = 86_400; /// The output fields of a DNS write that hold the zone and the record name. pub(super) const ZONE_AND_NAME: &[&str] = &["domain", "name"]; @@ -73,6 +76,7 @@ pub(super) fn parse_list_type_arg(raw: &str) -> Result { /// Optional record fields shared by `add` and `set`, including the CAA-only /// `flag`/`tag`, the TLSA-only `usage`/`selector`/`matching_type`, and the /// HTTPS/SVCB-only `parameters` (SvcParams). +#[derive(Clone)] pub(super) struct RecordOptions { pub(super) ttl: Option, pub(super) priority: Option, @@ -148,8 +152,9 @@ pub(super) struct RecordWriteArgs { #[arg(long, value_name = "VALUE", required = true)] pub(super) data: Vec, - /// Time-to-live in seconds (defaults to 3600 when omitted). - #[arg(long, value_name = "SECONDS", value_parser = clap::value_parser!(i64).range(1..))] + /// Time-to-live in seconds, 600 (10 minutes) to 86400 (24 hours). Defaults + /// to 3600 when omitted; `set` keeps a record's current TTL instead. + #[arg(long, value_name = "SECONDS", value_parser = clap::value_parser!(i64).range(MIN_TTL..=MAX_TTL))] pub(super) ttl: Option, /// Record priority (MX, SRV, HTTPS, and SVCB only). For HTTPS/SVCB, 0 diff --git a/rust/src/dns/records_tests.rs b/rust/src/dns/records_tests.rs index e7c3930b..9651f2fb 100644 --- a/rust/src/dns/records_tests.rs +++ b/rust/src/dns/records_tests.rs @@ -265,6 +265,43 @@ async fn fetch_records_keeps_server_side_filtering_everywhere_else() { assert_eq!(found.len(), 1, "no name given, nothing to filter out"); } +#[derive(clap::Parser)] +struct WriteCli { + #[command(flatten)] + args: RecordWriteArgs, +} + +fn parse_ttl(ttl: &str) -> Result, clap::Error> { + use clap::Parser; + WriteCli::try_parse_from([ + "t", + "example.com", + "--type", + "A", + "--name", + "www", + "--data", + "1.2.3.4", + "--ttl", + ttl, + ]) + .map(|cli| cli.args.ttl) +} + +#[test] +fn ttl_is_limited_to_the_range_the_api_accepts() { + assert_eq!(parse_ttl("600").expect("lower bound"), Some(600)); + assert_eq!(parse_ttl("86400").expect("upper bound"), Some(86_400)); + for bad in ["599", "1", "0", "86401"] { + let err = parse_ttl(bad).expect_err("out of range"); + let text = err.to_string(); + assert!( + text.contains("600") && text.contains("86400"), + "{bad}: {text}" + ); + } +} + #[test] fn verified_result_shows_the_requested_form_of_zone_and_name() { let payload = || { diff --git a/rust/src/dns/set/mod.rs b/rust/src/dns/set/mod.rs index 9ce40b35..3ca4a4e6 100644 --- a/rust/src/dns/set/mod.rs +++ b/rust/src/dns/set/mod.rs @@ -1,6 +1,7 @@ //! `dns set` — replace every record for a type+name pair (destructive). use cli_engine::{Alignment, CommandResult, CommandSpec, RuntimeCommandSpec, TableColumn, Tier}; +use serde_json::Value; use crate::domain::{api_error, make_client}; use crate::output_schema::output_schema; @@ -14,25 +15,34 @@ use super::records::{ZONE_AND_NAME, verified_result}; mod outcome; mod plan; +mod verify; mod write; use outcome::{SetOutcome, dry_run_set_preview, record_label, summarize_set_outcomes}; use plan::{SetAction, plan_set}; +use verify::verify_final_state; use write::{WriteRequest, apply_replace, write_with_conflict_handling}; -// `dns set` reconciles over v3's per-record ops; it reports how many records it -// replaced, created, and deleted to reach the desired set. +// `dns set` reconciles over the API's per-record ops; it reports how many records it +// replaced, left unchanged, created, and deleted to reach the desired set. output_schema!(DnsSetResult { "domain": "string"; "type": "string"; "name": "string"; "replaced": "number"; + "unchanged": "number"; "created": "number"; "deleted": "number"; "action": "string"; + "records": "[]object", optional; "plan": "[]object", optional; }); +/// The fields shown when the caller doesn't pass `--fields`; anything not +/// listed here is dropped from the output. +const DEFAULT_FIELDS: &str = + "domain,type,name,replaced,unchanged,created,deleted,action,records,plan"; + #[derive(Debug, Clone, clap::Args)] struct SetArgs { #[command(flatten)] @@ -44,18 +54,26 @@ struct SetArgs { replace_conflicting_types: bool, } -/// `plan` only appears on the `--dry-run` preview (the real set's success -/// payload has no per-action breakdown), so it renders as an indented child -/// table there instead of a raw JSON dump. +/// `records` (what the real set left in place) and `plan` (what `--dry-run` +/// would do) each appear on only one of the two outputs, and render as indented +/// child tables instead of a raw JSON dump. fn view_columns() -> Vec { vec![ TableColumn::new("domain", "Domain"), TableColumn::new("type", "Type"), TableColumn::new("name", "Name"), TableColumn::new("replaced", "Replaced").align(Alignment::Right), + TableColumn::new("unchanged", "Unchanged").align(Alignment::Right), TableColumn::new("created", "Created").align(Alignment::Right), TableColumn::new("deleted", "Deleted").align(Alignment::Right), TableColumn::new("action", "Action"), + TableColumn::new("records", "Records").nested(vec![ + TableColumn::new("type", "Type").essential(true), + TableColumn::new("name", "Name"), + TableColumn::new("data", "Data").essential(true), + TableColumn::new("ttl", "TTL").align(Alignment::Right), + TableColumn::new("recordId", "Record ID"), + ]), TableColumn::new("plan", "Plan").nested(vec![ TableColumn::new("action", "Action").essential(true), TableColumn::new("recordId", "Record ID"), @@ -73,11 +91,7 @@ pub(super) fn command() -> RuntimeCommandSpec { .with_long( "Replaces every DNS record for the given type+name pair with the \ values supplied via `--data`, discarding any records that were \ - there before. v3 has no bulk or in-place replace, so this reconciles \ - over per-record calls: for the overlap it creates the replacement \ - value then deletes the record it's replacing, it deletes the surplus, \ - and it creates the shortfall (so it is not atomic — a mid-run failure \ - is reported per record). This is destructive and irreversible — use \ + there before. This is destructive and irreversible — use \ `dns list --type --name ` to review first. Use `dns add` \ to append without removing existing records.\n\ \n\ @@ -90,7 +104,7 @@ pub(super) fn command() -> RuntimeCommandSpec { .with_system("domain") .with_tier(Tier::Destructive) .handles_dry_run(true) - .with_default_fields("domain,type,name,replaced,created,deleted,action,plan") + .with_default_fields(DEFAULT_FIELDS) .with_output_schema::() .with_view(view_columns()) .with_scopes(&[DOMAINS_DNS_UPDATE]), @@ -142,7 +156,7 @@ pub(super) fn command() -> RuntimeCommandSpec { .into_cli_error()); } let desired = v3_records(&name, &record_type, &data, &opts); - let plan = plan_set(&existing, &desired); + let plan = plan_set(&existing, &desired, opts.ttl); if ctx.dry_run() { let mut preview = dry_run_set_preview(&domain, &record_type, &name, &plan); domain_format.convert_fields(&mut preview, ZONE_AND_NAME); @@ -163,15 +177,27 @@ pub(super) fn command() -> RuntimeCommandSpec { value: &value, opts: &opts, replace_conflicting, + replacing: None, debug, }; - let old_record = existing + let old_ttl = existing + .iter() + .find(|r| r.record_id.as_deref() == Some(record_id.as_str())) + .map(|r| r.ttl); + outcomes.extend(apply_replace(&client, &req, &record_id, old_ttl).await); + } + SetAction::Unchanged { + record_id, + data: value, + } => { + let mut outcome = SetOutcome::new("unchanged", value, None); + if let Some(record) = existing .iter() - .find(|r| r.record_id.as_deref() == Some(record_id.as_str())); - let old_detail = record_label(&existing, &record_type, &record_id); - outcomes.extend( - apply_replace(&client, &req, &record_id, &old_detail, old_record).await, - ); + .find(|r| r.record_id.as_deref() == Some(record_id.as_str())) + { + outcome = outcome.with_record(record.clone()); + } + outcomes.push(outcome); } SetAction::Create { data: value } => { let req = WriteRequest { @@ -181,6 +207,7 @@ pub(super) fn command() -> RuntimeCommandSpec { value: &value, opts: &opts, replace_conflicting, + replacing: None, debug, }; outcomes.extend(write_with_conflict_handling(&client, &req).await); @@ -204,9 +231,32 @@ pub(super) fn command() -> RuntimeCommandSpec { } } - summarize_set_outcomes(&domain, &record_type, &name, &outcomes) - .map(|v| verified_result(domain_format, v, &domain, &record_type, &name)) - .map_err(super::mutate_failed) + let mut summary = summarize_set_outcomes(&domain, &record_type, &name, &outcomes) + .map_err(super::mutate_failed)?; + if let Some(records) = summary.get_mut("records").and_then(Value::as_array_mut) { + for record in records { + domain_format.convert_fields(record, &["name"]); + } + } + // The plan came from one earlier read, so confirm the type+name now + // holds exactly what was asked for before reporting success. + verify_final_state( + &client, + domain.as_str(), + &record_type, + &name, + &desired, + opts.ttl.is_some(), + debug, + ) + .await?; + Ok(verified_result( + domain_format, + summary, + &domain, + &record_type, + &name, + )) }, ) } diff --git a/rust/src/dns/set/outcome.rs b/rust/src/dns/set/outcome.rs index 245858ba..7e01a3e4 100644 --- a/rust/src/dns/set/outcome.rs +++ b/rust/src/dns/set/outcome.rs @@ -5,17 +5,21 @@ use domains_client::types; use serde_json::{Value, json}; +use super::super::list::build_list_output; use super::super::records::record_value; use super::plan::SetAction; /// Outcome of one applied `set` reconcile action, for reporting. pub(super) struct SetOutcome { - /// What was attempted: `"replaced"`, `"created"`, or `"deleted"`. + /// What was attempted: `"replaced"`, `"unchanged"`, `"created"`, or `"deleted"`. pub(super) kind: &'static str, /// The `--data` value (replace/create) or record id (delete). pub(super) detail: String, /// `Some(msg)` if the call failed. pub(super) error: Option, + /// The record as the API returned it after a successful create or + /// replace, or as it already stood for a replace that needed no change. + pub(super) record: Option, } impl SetOutcome { @@ -24,12 +28,19 @@ impl SetOutcome { kind, detail, error, + record: None, } } + + pub(super) fn with_record(mut self, record: types::DnsRecord) -> Self { + self.record = Some(record); + self + } } /// Build the `set` result from the applied reconcile outcomes: `Ok(json)` with -/// replaced/created/deleted counts when every action succeeded, or `Err(message)` +/// replaced/created/deleted counts and the records now in place (as `dns list` +/// shows them) when every action succeeded, or `Err(message)` /// — a non-zero exit — with a per-action ✓/✗ breakdown if any failed. Pure so the /// success/failure decision and tallies are unit-testable. pub(super) fn summarize_set_outcomes( @@ -45,7 +56,12 @@ pub(super) fn summarize_set_outcomes( .filter(|o| o.error.is_none() && o.kind == k) .count() }; - let (replaced, created, deleted) = (count("replaced"), count("created"), count("deleted")); + let (replaced, unchanged, created, deleted) = ( + count("replaced"), + count("unchanged"), + count("created"), + count("deleted"), + ); if failed > 0 { let breakdown = outcomes @@ -64,14 +80,20 @@ pub(super) fn summarize_set_outcomes( )); } + let written: Vec = outcomes.iter().filter_map(|o| o.record.clone()).collect(); + let records = build_list_output(&written) + .map_err(|e| format!("failed to serialize the resulting DNS records: {e}"))?; + Ok(json!({ "domain": domain, "type": record_type, "name": name, "replaced": replaced, + "unchanged": unchanged, "created": created, "deleted": deleted, "action": "set", + "records": records, })) } @@ -94,6 +116,9 @@ pub(super) fn dry_run_set_preview( SetAction::Replace { record_id, data } => { json!({"action": "replace", "recordId": record_id, "data": data}) } + SetAction::Unchanged { record_id, data } => { + json!({"action": "unchanged", "recordId": record_id, "data": data}) + } SetAction::Create { data } => json!({"action": "create", "data": data}), SetAction::Delete { record_id } => json!({"action": "delete", "recordId": record_id}), }) @@ -108,6 +133,7 @@ pub(super) fn dry_run_set_preview( // `with_default_fields` projection instead of being silently // stripped down to just domain/type/name. "replaced": count(|a| matches!(a, SetAction::Replace { .. })), + "unchanged": count(|a| matches!(a, SetAction::Unchanged { .. })), "created": count(|a| matches!(a, SetAction::Create { .. })), "deleted": count(|a| matches!(a, SetAction::Delete { .. })), "plan": plan_json, @@ -172,11 +198,13 @@ mod tests { fn summarize_set_reports_counts_and_flags_partial_failure() { let all_ok = vec![ SetOutcome::new("replaced", "9.9.9.9".into(), None), + SetOutcome::new("unchanged", "7.7.7.7".into(), None), SetOutcome::new("created", "8.8.8.8".into(), None), SetOutcome::new("deleted", "r3".into(), None), ]; let v = summarize_set_outcomes("example.com", "A", "www", &all_ok).expect("all ok"); assert_eq!(v["replaced"], 1); + assert_eq!(v["unchanged"], 1); assert_eq!(v["created"], 1); assert_eq!(v["deleted"], 1); @@ -187,19 +215,23 @@ mod tests { let err = summarize_set_outcomes("example.com", "A", "www", &mixed).expect_err("a failure"); assert!(err.contains("1 of 2"), "{err}"); assert!(err.contains("✗ created 8.8.8.8 — 422 bad"), "{err}"); + } - // A `apply_replace`-style "cleanup" outcome (the new value was created - // but the old record couldn't be deleted afterward) still fails the - // command, but must not be double-counted into `replaced`/`deleted` - // since the replace itself already succeeded. - let replace_with_cleanup_failure = vec![ - SetOutcome::new("replaced", "9.9.9.9".into(), None), - SetOutcome::new("cleanup", "A 1.2.3.4".into(), Some("still there".into())), + #[test] + fn summarize_set_lists_the_records_the_api_returned() { + let mut stored = tlsa_record("r1", "abc"); + stored.type_ = types::DnsRecordType("A".to_owned()); + stored.certificate_data = None; + stored.data = Some("9.9.9.9".to_owned()); + let outcomes = vec![ + SetOutcome::new("replaced", "9.9.9.9".into(), None).with_record(stored), + SetOutcome::new("deleted", "r3".into(), None), ]; - let err = summarize_set_outcomes("example.com", "A", "www", &replace_with_cleanup_failure) - .expect_err("cleanup failure still fails the command"); - assert!(err.contains("1 of 2"), "{err}"); - assert!(err.contains("✗ cleanup A 1.2.3.4 — still there"), "{err}"); + let v = summarize_set_outcomes("example.com", "A", "www", &outcomes).expect("all ok"); + let records = v["records"].as_array().expect("records array"); + assert_eq!(records.len(), 1, "a delete leaves no record behind: {v}"); + assert_eq!(records[0]["data"], "9.9.9.9"); + assert_eq!(records[0]["recordId"], "r1"); } #[test] @@ -209,7 +241,7 @@ mod tests { record_id: "r1".into(), data: "9.9.9.9".into(), }, - SetAction::Replace { + SetAction::Unchanged { record_id: "r2".into(), data: "8.8.8.8".into(), }, @@ -218,7 +250,8 @@ mod tests { }, ]; let preview = dry_run_set_preview("example.com", "A", "www", &plan); - assert_eq!(preview["replaced"], 2); + assert_eq!(preview["replaced"], 1); + assert_eq!(preview["unchanged"], 1); assert_eq!(preview["created"], 0); assert_eq!(preview["deleted"], 1); assert_eq!(preview["action"], "would set"); @@ -238,10 +271,17 @@ mod tests { data: "9.9.9.9".into(), }]; let preview = dry_run_set_preview("example.com", "A", "www", &plan); - let default_fields = "domain,type,name,replaced,created,deleted,action,plan"; - let projected = cli_engine::output::filter_fields(&preview, default_fields); + let projected = cli_engine::output::filter_fields(&preview, super::super::DEFAULT_FIELDS); for field in [ - "domain", "type", "name", "replaced", "created", "deleted", "action", "plan", + "domain", + "type", + "name", + "replaced", + "unchanged", + "created", + "deleted", + "action", + "plan", ] { assert!( !projected[field].is_null(), diff --git a/rust/src/dns/set/plan.rs b/rust/src/dns/set/plan.rs index 7192ccfa..c2753354 100644 --- a/rust/src/dns/set/plan.rs +++ b/rust/src/dns/set/plan.rs @@ -5,19 +5,15 @@ use domains_client::types; use crate::dns::records::{record_value, same_content}; -/// One reconcile action for `dns set` over v3's per-record endpoints. -/// -/// v3 has no atomic single-record replace: `PUT .../dns-records/{recordId}` -/// responds `200` but silently replaces the *entire* record collection with -/// just the system records and whatever's in the request body, discarding -/// everything else in the zone (reproduced live against a test zone; see -/// ). So `Replace` is executed as -/// create-the-new-value-then-delete-the-old-record, never as an in-place PUT. +/// One reconcile action for `dns set` over the API's per-record endpoints. #[derive(Debug, PartialEq)] pub(super) enum SetAction { - /// Create a record for the desired `--data` value, then delete the - /// existing record (`record_id`) it's replacing. + /// Replace the existing record (`record_id`) in place with the desired + /// `--data` value. Replace { record_id: String, data: String }, + /// The existing record (`record_id`) already is the desired one; nothing to + /// send. + Unchanged { record_id: String, data: String }, /// Remove an existing record no longer wanted. Delete { record_id: String }, /// Create a record for a surplus `--data` value. @@ -29,28 +25,10 @@ pub(super) enum SetAction { /// `Delete` the surplus existing, `Create` the surplus desired. Pure so the /// plan — the least-destructive way to emulate a set-replace over per-record v3 /// ops — is unit-testable. -/// -/// A desired record that some existing record already holds is paired with *that* -/// record before anything is paired by position. v3 rejects a create that -/// duplicates a record still present (`DUPLICATE_RECORD`), and under a purely -/// positional pairing that is not a harmless no-op: [`super::write::apply_replace`] -/// keeps the old record when its create fails, while the surplus `Delete` later in -/// the plan still runs — so narrowing `www A {1.2.3.4, 5.6.7.8}` to just `5.6.7.8` -/// would delete `5.6.7.8` and leave `1.2.3.4` behind, the exact inverse of what was -/// asked. Pairing retained records first means one that stays in the set is never -/// re-created. -/// -/// "Holds" is [`same_content`] — every field but `ttl`/`recordId`, the same test -/// `apply_replace` uses to skip a no-op — not a shared value. Records at one -/// type+name can share their value and differ in CAA `flag`/`tag`, TLSA -/// `usage`/`selector`/`matchingType`, SRV or HTTPS/SVCB fields, and pairing on the -/// value alone would pick the wrong one. -/// -/// Every `existing` record must carry a `recordId`; the caller rejects the set -/// before planning otherwise. pub(super) fn plan_set( existing: &[types::DnsRecord], desired: &[types::DnsRecord], + ttl: Option, ) -> Vec { let id = |r: &types::DnsRecord| r.record_id.clone().expect("existing record has a recordId"); let value = |r: &types::DnsRecord| record_value(r).unwrap_or_default().to_owned(); @@ -79,9 +57,14 @@ pub(super) fn plan_set( let mut actions = Vec::with_capacity(existing.len().max(desired.len())); for (d, want) in desired.iter().enumerate() { if let Some(e) = paired[d] { - actions.push(SetAction::Replace { - record_id: id(&existing[e]), - data: value(want), + let record_id = id(&existing[e]); + let data = value(want); + let unchanged = + same_content(&existing[e], want) && ttl.is_none_or(|t| t == existing[e].ttl); + actions.push(if unchanged { + SetAction::Unchanged { record_id, data } + } else { + SetAction::Replace { record_id, data } }); } } @@ -176,7 +159,7 @@ mod tests { let existing = a_stored(&[("r1", "1.1.1.1"), ("r2", "2.2.2.2"), ("r3", "3.3.3.3")]); let desired = a_wanted(&["9.9.9.9", "8.8.8.8"]); assert_eq!( - plan_set(&existing, &desired), + plan_set(&existing, &desired, None), vec![ SetAction::Replace { record_id: "r1".into(), @@ -193,7 +176,7 @@ mod tests { ); // 1 existing, 3 desired → reuse 1 id, create 2. assert_eq!( - plan_set(&a_stored(&[("r1", "z")]), &a_wanted(&["a", "b", "c"])), + plan_set(&a_stored(&[("r1", "z")]), &a_wanted(&["a", "b", "c"]), None), vec![ SetAction::Replace { record_id: "r1".into(), @@ -205,7 +188,7 @@ mod tests { ); // none existing → all creates. assert_eq!( - plan_set(&[], &a_wanted(&["x"])), + plan_set(&[], &a_wanted(&["x"]), None), vec![SetAction::Create { data: "x".into() }] ); } @@ -220,9 +203,9 @@ mod tests { // exactly the value the user asked to drop. let existing = a_stored(&[("r1", "1.2.3.4"), ("r2", "5.6.7.8")]); assert_eq!( - plan_set(&existing, &a_wanted(&["5.6.7.8"])), + plan_set(&existing, &a_wanted(&["5.6.7.8"]), None), vec![ - SetAction::Replace { + SetAction::Unchanged { record_id: "r2".into(), data: "5.6.7.8".into() }, @@ -240,13 +223,13 @@ mod tests { // one instead of issuing two creates that both fail as duplicates. let existing = a_stored(&[("r1", "1.2.3.4"), ("r2", "5.6.7.8")]); assert_eq!( - plan_set(&existing, &a_wanted(&["5.6.7.8", "1.2.3.4"])), + plan_set(&existing, &a_wanted(&["5.6.7.8", "1.2.3.4"]), None), vec![ - SetAction::Replace { + SetAction::Unchanged { record_id: "r2".into(), data: "5.6.7.8".into() }, - SetAction::Replace { + SetAction::Unchanged { record_id: "r1".into(), data: "1.2.3.4".into() }, @@ -260,9 +243,9 @@ mod tests { // The freed id r1 is reused positionally rather than deleted-and-created. let existing = a_stored(&[("r1", "1.2.3.4"), ("r2", "5.6.7.8")]); assert_eq!( - plan_set(&existing, &a_wanted(&["5.6.7.8", "9.9.9.9"])), + plan_set(&existing, &a_wanted(&["5.6.7.8", "9.9.9.9"]), None), vec![ - SetAction::Replace { + SetAction::Unchanged { record_id: "r2".into(), data: "5.6.7.8".into() }, @@ -279,13 +262,13 @@ mod tests { // Two identical --data values must not both pair with the same record. let existing = a_stored(&[("r1", "1.2.3.4"), ("r2", "1.2.3.4")]); assert_eq!( - plan_set(&existing, &a_wanted(&["1.2.3.4", "1.2.3.4"])), + plan_set(&existing, &a_wanted(&["1.2.3.4", "1.2.3.4"]), None), vec![ - SetAction::Replace { + SetAction::Unchanged { record_id: "r1".into(), data: "1.2.3.4".into() }, - SetAction::Replace { + SetAction::Unchanged { record_id: "r2".into(), data: "1.2.3.4".into() }, @@ -304,9 +287,9 @@ mod tests { stored("r2", "TLSA", CERT, &tlsa_opts(1)), ]; assert_eq!( - plan_set(&existing, &[wanted("TLSA", CERT, &tlsa_opts(1))]), + plan_set(&existing, &[wanted("TLSA", CERT, &tlsa_opts(1))], None), vec![ - SetAction::Replace { + SetAction::Unchanged { record_id: "r2".into(), data: CERT.into() }, @@ -331,9 +314,9 @@ mod tests { wanted("CAA", "digicert.com", &caa_opts("issue")), ]; assert_eq!( - plan_set(&existing, &desired), + plan_set(&existing, &desired, None), vec![ - SetAction::Replace { + SetAction::Unchanged { record_id: "r2".into(), data: "letsencrypt.org".into() }, @@ -345,6 +328,45 @@ mod tests { ); } + #[test] + fn plan_set_ignores_a_ttl_the_caller_did_not_pass() { + // The stored record has ttl 600; `a_wanted` builds with the 3600 default. + // Without an explicit --ttl that difference is not a change. + let mut slow = opts(); + slow.ttl = Some(600); + let existing = [stored("r1", "A", "1.2.3.4", &slow)]; + assert_eq!( + plan_set(&existing, &a_wanted(&["1.2.3.4"]), None), + vec![SetAction::Unchanged { + record_id: "r1".into(), + data: "1.2.3.4".into() + }] + ); + } + + #[test] + fn plan_set_replaces_when_an_explicit_ttl_differs() { + let existing = a_stored(&[("r1", "1.2.3.4")]); // stored at the 3600 default + let mut fast = opts(); + fast.ttl = Some(900); + let desired = [wanted("A", "1.2.3.4", &fast)]; + assert_eq!( + plan_set(&existing, &desired, Some(900)), + vec![SetAction::Replace { + record_id: "r1".into(), + data: "1.2.3.4".into() + }] + ); + // The same explicit ttl as stored is no change. + assert_eq!( + plan_set(&existing, &desired, Some(3600)), + vec![SetAction::Unchanged { + record_id: "r1".into(), + data: "1.2.3.4".into() + }] + ); + } + fn srv_opts() -> RecordOptions { RecordOptions { priority: Some(1), @@ -370,9 +392,9 @@ mod tests { stored("r2", "SRV", "b.example.com.", &o), ]; assert_eq!( - plan_set(&existing, &[wanted("SRV", "b.example.com", &o)]), + plan_set(&existing, &[wanted("SRV", "b.example.com", &o)], None), vec![ - SetAction::Replace { + SetAction::Unchanged { record_id: "r2".into(), data: "b.example.com".into() }, diff --git a/rust/src/dns/set/verify.rs b/rust/src/dns/set/verify.rs new file mode 100644 index 00000000..6cf726bc --- /dev/null +++ b/rust/src/dns/set/verify.rs @@ -0,0 +1,173 @@ +//! Final-state check for `dns set`: after the planned writes succeed, read the +//! type+name back and confirm the records now there are the ones that were +//! asked for. The plan is made from a single earlier read, so a record added or +//! changed by someone else in between would otherwise go unnoticed. + +use cli_engine::CliCoreError; +use domains_client::types; +use serde_json::Value; + +use crate::dns::records::{fetch_records, record_value}; + +/// What differs between the records asked for and the records now present. +#[derive(Debug, PartialEq)] +pub(super) struct Mismatch { + /// Asked for, but not present. + pub(super) missing: Vec, + /// Present, but not asked for. + pub(super) unexpected: Vec, +} + +/// The comparable content of a record: everything but its id and its type and +/// name (every record compared was fetched or built for the same type+name), and +/// its TTL unless the caller set one. The API stores domain names lower-cased +/// with a trailing dot (`Example.COM` comes back as `example.com.`), so text +/// fields are compared in that form; TXT is left as written since its text is +/// case-sensitive. +fn comparable(record: &types::DnsRecord, compare_ttl: bool) -> Value { + let mut value = serde_json::to_value(record).expect("DnsRecord always serializes to JSON"); + let is_txt = record.type_.as_str() == "TXT"; + if let Some(fields) = value.as_object_mut() { + for key in ["recordId", "type", "name"] { + fields.remove(key); + } + if !compare_ttl { + fields.remove("ttl"); + } + if !is_txt { + for field in fields.values_mut() { + if let Value::String(text) = field { + *text = text.trim_end_matches('.').to_lowercase(); + } + } + } + } + value +} + +/// A short human label for a record, including the fields that tell records +/// with the same value apart (MX priority, CAA tag, TLSA usage, …). +fn describe(record: &types::DnsRecord) -> String { + let mut parts = vec![record.type_.as_str().to_owned()]; + let numbers = [ + ("priority", record.priority.map(u32::from)), + ("weight", record.weight.map(u32::from)), + ("port", record.port.map(u32::from)), + ("flag", record.flag.map(u32::from)), + ("usage", record.usage.as_ref().map(|u| u32::from(u.0))), + ("selector", record.selector.as_ref().map(|s| u32::from(s.0))), + ( + "matching type", + record.matching_type.as_ref().map(|m| u32::from(m.0)), + ), + ]; + for (label, number) in numbers { + if let Some(number) = number { + parts.push(format!("{label} {number}")); + } + } + if let Some(tag) = &record.tag { + parts.push(format!("tag {tag}")); + } + parts.push(record_value(record).unwrap_or("(no data)").to_owned()); + if let Some(parameters) = &record.parameters { + parts.push(format!("parameters {parameters}")); + } + parts.join(" ") +} + +/// Compare the records now present against those asked for, as multisets. +/// `None` when they hold the same content. Pure so the rules are unit-testable. +pub(super) fn final_set_mismatch( + desired: &[types::DnsRecord], + actual: &[types::DnsRecord], + compare_ttl: bool, +) -> Option { + let mut remaining: Vec<(Value, &types::DnsRecord)> = actual + .iter() + .map(|r| (comparable(r, compare_ttl), r)) + .collect(); + let mut missing = Vec::new(); + for want in desired { + let key = comparable(want, compare_ttl); + match remaining.iter().position(|(have, _)| *have == key) { + Some(i) => { + remaining.remove(i); + } + None => missing.push(describe(want)), + } + } + let unexpected: Vec = remaining.iter().map(|(_, r)| describe(r)).collect(); + if missing.is_empty() && unexpected.is_empty() { + None + } else { + Some(Mismatch { + missing, + unexpected, + }) + } +} + +/// Read the type+name back and check it against `desired`. `Ok(())` when they +/// match; otherwise a non-zero error that lists what is extra and what is +/// missing and leaves the zone as it is — a record that appeared in the +/// meantime may belong to someone else, so it is reported rather than removed. +pub(super) async fn verify_final_state( + client: &domains_client::Client, + domain: &str, + record_type: &str, + name: &str, + desired: &[types::DnsRecord], + compare_ttl: bool, + debug: bool, +) -> Result<(), CliCoreError> { + let review = format!("gddy dns list {domain} --type {record_type} --name {name}"); + let actual = fetch_records(client, domain, Some(record_type), Some(name), debug) + .await + .map_err(|e| { + crate::error::GddyError::unexpected(format!( + "the change was applied, but reading {name} ({record_type}) back \ + to confirm it failed: {e}" + )) + .with_fix(format!("Run `{review}` to check the current records.")) + .into_cli_error() + })?; + + let Some(mismatch) = final_set_mismatch(desired, &actual, compare_ttl) else { + return Ok(()); + }; + let list = |items: &[String]| { + items + .iter() + .map(|item| format!(" - {item}")) + .collect::>() + .join("\n") + }; + let mut message = format!( + "set finished, but the records now at {name} ({record_type}) are not the \ + ones you asked for. Someone else may have changed them while this ran." + ); + if !mismatch.unexpected.is_empty() { + message.push_str(&format!( + "\nPresent but not requested:\n{}", + list(&mismatch.unexpected) + )); + } + if !mismatch.missing.is_empty() { + message.push_str(&format!( + "\nRequested but not present:\n{}", + list(&mismatch.missing) + )); + } + Err(crate::error::GddyError::unexpected(message) + .with_fix(format!( + "Nothing extra was removed. Run `{review}` to review the records, \ + then re-run `set` to replace them or `gddy dns delete` to remove the \ + unexpected ones." + )) + .into_cli_error()) +} + +#[cfg(test)] +#[path = "verify_tests.rs"] +mod tests; diff --git a/rust/src/dns/set/verify_tests.rs b/rust/src/dns/set/verify_tests.rs new file mode 100644 index 00000000..e774ec3e --- /dev/null +++ b/rust/src/dns/set/verify_tests.rs @@ -0,0 +1,225 @@ +use super::*; +use crate::dns::records::{RecordOptions, v3_record}; +use httpmock::prelude::*; +use serde_json::json; + +fn opts() -> RecordOptions { + RecordOptions { + ttl: None, + priority: None, + port: None, + weight: None, + protocol: None, + service: None, + flag: None, + tag: None, + usage: None, + selector: None, + matching_type: None, + parameters: None, + } +} + +fn a(value: &str) -> types::DnsRecord { + v3_record("www", "A", value, &opts()) +} + +fn stored(mut record: types::DnsRecord, id: &str) -> types::DnsRecord { + record.record_id = Some(id.to_owned()); + record +} + +#[test] +fn matching_sets_have_no_mismatch_whatever_their_order_or_ids() { + let desired = [a("1.1.1.1"), a("2.2.2.2")]; + let actual = [stored(a("2.2.2.2"), "r2"), stored(a("1.1.1.1"), "r1")]; + assert_eq!(final_set_mismatch(&desired, &actual, false), None); +} + +#[test] +fn a_record_added_by_someone_else_is_reported_as_unexpected() { + let desired = [a("192.0.2.10")]; + let actual = [ + stored(a("198.51.100.77"), "r9"), + stored(a("192.0.2.10"), "r1"), + ]; + assert_eq!( + final_set_mismatch(&desired, &actual, false), + Some(Mismatch { + missing: vec![], + unexpected: vec!["A 198.51.100.77".to_owned()], + }) + ); +} + +#[test] +fn a_requested_record_that_is_gone_is_reported_as_missing() { + let desired = [a("1.1.1.1"), a("2.2.2.2")]; + let actual = [stored(a("1.1.1.1"), "r1")]; + assert_eq!( + final_set_mismatch(&desired, &actual, false), + Some(Mismatch { + missing: vec!["A 2.2.2.2".to_owned()], + unexpected: vec![], + }) + ); +} + +#[test] +fn duplicates_are_counted_not_collapsed() { + let desired = [a("1.1.1.1")]; + let actual = [stored(a("1.1.1.1"), "r1"), stored(a("1.1.1.1"), "r2")]; + let mismatch = final_set_mismatch(&desired, &actual, false).expect("one extra"); + assert_eq!(mismatch.unexpected, vec!["A 1.1.1.1".to_owned()]); +} + +#[test] +fn ttl_is_compared_only_when_the_caller_set_one() { + let mut slow = opts(); + slow.ttl = Some(900); + let desired = [v3_record("www", "A", "1.1.1.1", &slow)]; + let actual = [stored(a("1.1.1.1"), "r1")]; // stored with the default 3600 + + assert_eq!(final_set_mismatch(&desired, &actual, false), None); + assert!(final_set_mismatch(&desired, &actual, true).is_some()); +} + +#[test] +fn names_are_compared_the_way_the_api_stores_them() { + // `Example.COM` is stored as `example.com.`. + let desired = [v3_record("www", "CNAME", "Example.COM", &opts())]; + let actual = [stored( + v3_record("www", "CNAME", "example.com.", &opts()), + "r1", + )]; + assert_eq!(final_set_mismatch(&desired, &actual, false), None); +} + +#[test] +fn txt_text_is_compared_exactly() { + let desired = [v3_record("www", "TXT", "Hello", &opts())]; + let actual = [stored(v3_record("www", "TXT", "hello", &opts()), "r1")]; + assert!(final_set_mismatch(&desired, &actual, false).is_some()); +} + +#[test] +fn records_that_differ_only_in_a_sibling_field_are_different() { + let mut p10 = opts(); + p10.priority = Some(10); + let mut p20 = opts(); + p20.priority = Some(20); + let desired = [v3_record("@", "MX", "mail.example.com.", &p10)]; + let actual = [stored( + v3_record("@", "MX", "mail.example.com.", &p20), + "r1", + )]; + let mismatch = final_set_mismatch(&desired, &actual, false).expect("priority differs"); + assert_eq!( + mismatch.missing, + vec!["MX priority 10 mail.example.com.".to_owned()] + ); + assert_eq!( + mismatch.unexpected, + vec!["MX priority 20 mail.example.com.".to_owned()] + ); +} + +fn client_for(server: &MockServer) -> domains_client::Client { + domains_client::client_with_builder( + reqwest::Client::builder(), + &server.base_url(), + "Bearer tok", + "req-1", + ) + .expect("build client") +} + +fn serve_records(server: &MockServer, items: Value) { + server.mock(|when, then| { + when.method(GET) + .path("/v3/domains/zones/example.com/dns-records") + .query_param("type", "A") + .query_param("name", "www"); + then.status(200) + .json_body(json!({ "items": items, "links": [] })); + }); +} + +#[tokio::test] +async fn verify_passes_when_the_zone_holds_exactly_the_requested_records() { + let server = MockServer::start_async().await; + serve_records( + &server, + json!([{ "recordId": "r1", "type": "A", "name": "www", "data": "1.1.1.1", "ttl": 3600 }]), + ); + verify_final_state( + &client_for(&server), + "example.com", + "A", + "www", + &[a("1.1.1.1")], + false, + false, + ) + .await + .expect("zone matches"); +} + +#[tokio::test] +async fn verify_fails_without_deleting_when_an_unrequested_record_appeared() { + let server = MockServer::start_async().await; + serve_records( + &server, + json!([ + { "recordId": "r1", "type": "A", "name": "www", "data": "1.1.1.1", "ttl": 3600 }, + { "recordId": "r9", "type": "A", "name": "www", "data": "198.51.100.77", "ttl": 3600 } + ]), + ); + let delete = server.mock(|when, then| { + when.method(DELETE); + then.status(204); + }); + + let err = verify_final_state( + &client_for(&server), + "example.com", + "A", + "www", + &[a("1.1.1.1")], + false, + false, + ) + .await + .expect_err("an extra record is a mismatch"); + + assert_eq!(delete.calls(), 0, "an unexpected record must be left alone"); + let text = format!("{err:?}"); + assert!(text.contains("Present but not requested"), "{text}"); + assert!(text.contains("A 198.51.100.77"), "{text}"); + assert!( + !text.contains("Requested but not present"), + "nothing requested is missing: {text}" + ); +} + +#[tokio::test] +async fn verify_reports_a_failed_read_back_as_applied_but_unconfirmed() { + let server = MockServer::start_async().await; + server.mock(|when, then| { + when.method(GET); + then.status(500); + }); + let err = verify_final_state( + &client_for(&server), + "example.com", + "A", + "www", + &[a("1.1.1.1")], + false, + false, + ) + .await + .expect_err("read-back failed"); + let text = format!("{err:?}"); + assert!(text.contains("the change was applied"), "{text}"); +} diff --git a/rust/src/dns/set/write.rs b/rust/src/dns/set/write.rs index 303e8387..268389ef 100644 --- a/rust/src/dns/set/write.rs +++ b/rust/src/dns/set/write.rs @@ -1,20 +1,21 @@ -//! Per-record write execution for `dns set`: creating/deleting individual -//! records, with the same name-exclusivity conflict handling `add` gets, plus -//! `set`'s opt-in auto-fix and create-then-delete replace semantics. +//! Per-record write execution for `dns set`: creating, replacing and deleting +//! individual records, with the same name-exclusivity conflict handling `add` +//! gets, plus `set`'s opt-in auto-fix. use domains_client::types; use crate::dns::conflicts::{ conflicting_records, conflicting_records_at, describe_duplicate_record, duplicate_record_issue, }; -use crate::dns::records::{RecordOptions, record_value, same_content, v3_record}; +use crate::dns::records::{RecordOptions, record_value, v3_record}; use crate::domain::{api_error, format_api_error}; use super::outcome::SetOutcome; -/// Context for one `set` create action, bundled to keep +/// Context for one `set` write action, bundled to keep /// [`write_with_conflict_handling`]'s signature within clippy's /// argument-count limit. +#[derive(Clone, Copy)] pub(super) struct WriteRequest<'a> { pub(super) domain: &'a str, pub(super) name: &'a str, @@ -22,9 +23,40 @@ pub(super) struct WriteRequest<'a> { pub(super) value: &'a str, pub(super) opts: &'a RecordOptions, pub(super) replace_conflicting: bool, + /// The existing record this write replaces in place (`PUT`); `None` for a + /// plain create (`POST`). + pub(super) replacing: Option<&'a str>, pub(super) debug: bool, } +/// Send `body` as a create, or — when `req.replacing` names a record — as an +/// in-place replace of that record. Returns the record as the API stored it. +async fn send_record( + client: &domains_client::Client, + req: &WriteRequest<'_>, + body: types::DnsRecord, +) -> Result>> { + match req.replacing { + Some(record_id) => client + .replace_dns_record() + .zone(req.domain) + .record_id(record_id) + .body(body) + .send() + .await + .map(|response| response.into_inner()) + .map_err(Box::new), + None => client + .create_dns_record() + .zone(req.domain) + .body(body) + .send() + .await + .map(|response| response.into_inner()) + .map_err(Box::new), + } +} + /// Delete each conflicting record — used only by `set --replace-conflicting-types` /// to auto-resolve a name-exclusivity conflict before retrying the write. /// Returns one `SetOutcome` per record (rather than bailing on the first @@ -74,37 +106,35 @@ async fn delete_conflicts( outcomes } -/// Create one record for `req.value` (a surplus `--data` value, or — via -/// [`apply_replace`] — the new half of a replace pairing), with the same -/// name-exclusivity conflict handling `add` gets (see -/// [`crate::dns::conflicts::describe_write_error`]) plus an opt-in auto-fix: with -/// `--replace-conflicting-types`, a genuine `DUPLICATE_RECORD` failure deletes -/// the conflicting record(s) and retries the write once. Returns the delete -/// outcomes (if any) followed by the outcome for the create itself, so -/// `outcomes.extend(...)` folds both into the same reconcile summary. The -/// terminal outcome's `kind` is always `"created"` — [`apply_replace`] -/// relabels it to `"replaced"` when this is the create half of a replace. +/// Write one record for `req.value` — a create for a surplus `--data` value, +/// or, when `req.replacing` is set (via [`apply_replace`]), an in-place replace +/// of that record — with the same name-exclusivity conflict handling `add` gets +/// (see [`crate::dns::conflicts::describe_write_error`]) plus an opt-in +/// auto-fix: with `--replace-conflicting-types`, a genuine `DUPLICATE_RECORD` +/// failure deletes the conflicting record(s) and retries the write once. +/// Returns the delete outcomes (if any) followed by the outcome for the write +/// itself, so `outcomes.extend(...)` folds both into the same reconcile +/// summary. The terminal outcome's `kind` is always `"created"` — +/// [`apply_replace`] relabels it to `"replaced"`. pub(super) async fn write_with_conflict_handling( client: &domains_client::Client, req: &WriteRequest<'_>, ) -> Vec { - const ACTION: &str = "creating DNS record"; + let action = if req.replacing.is_some() { + "replacing DNS record" + } else { + "creating DNS record" + }; let outcome = |err: Option| SetOutcome::new("created", req.value.to_string(), err); let body = v3_record(req.name, req.record_type, req.value, req.opts); - let err = match client - .create_dns_record() - .zone(req.domain) - .body(body) - .send() - .await - { - Ok(_) => return vec![outcome(None)], - Err(e) => e, + let err = match send_record(client, req, body).await { + Ok(record) => return vec![outcome(None).with_record(record)], + Err(e) => *e, }; let domains_client::Error::UnexpectedResponse(resp) = err else { return vec![outcome(Some( - api_error(ACTION, req.debug, err).await.to_string(), + api_error(action, req.debug, err).await.to_string(), ))]; }; let status = resp.status(); @@ -117,7 +147,7 @@ pub(super) async fn write_with_conflict_handling( if !duplicate_record_issue(&resp_body) { let msg = format_api_error( - ACTION, + action, status.as_u16(), &status.to_string(), &resp_body, @@ -153,173 +183,42 @@ pub(super) async fn write_with_conflict_handling( let mut outcomes = delete_conflicts(client, req.domain, &conflicts, req.debug).await; let retry_body = v3_record(req.name, req.record_type, req.value, req.opts); - let retry_err = match client - .create_dns_record() - .zone(req.domain) - .body(retry_body) - .send() - .await - { - Ok(_) => None, - Err(e) => Some(api_error(ACTION, req.debug, e).await.to_string()), + let retried = match send_record(client, req, retry_body).await { + Ok(record) => outcome(None).with_record(record), + Err(e) => outcome(Some(api_error(action, req.debug, *e).await.to_string())), }; - outcomes.push(outcome(retry_err)); + outcomes.push(retried); outcomes } -/// Apply one `set` "replace" reconcile action: create the new value via -/// [`write_with_conflict_handling`], then — only if that succeeded — delete -/// the record it's replacing. There's no atomic single-record replace in v3 -/// (see the note on `SetAction::Replace`), so this create-then-delete pair -/// is the least-destructive way to emulate one: if the create fails, the old -/// record is left untouched rather than risking data loss. +/// Apply one `set` "replace" reconcile action: replace the record +/// `old_record_id` in place with the desired value via a single `PUT`. Only +/// called for a pairing that actually changes something — +/// [`super::plan::plan_set`] has already set aside the ones that don't as +/// `Unchanged`. /// -/// `old_record` is the record being replaced, if known — when its content -/// already matches the desired record (a no-op `set`, e.g. re-running the -/// same command, or only some of several values actually changed) this is a -/// no-op: creating the "new" value while the identical old record still -/// exists would fail with v3's exact-duplicate `DUPLICATE_RECORD` (see -/// [`crate::dns::conflicts::describe_duplicate_record`]), which isn't a real -/// failure, just this pairing having nothing to do. Compares full record -/// content ([`same_content`]), not just the value — a record type whose -/// identity spans several fields (CAA's `flag`/`tag`, TLSA's `usage`/ -/// `selector`/`matchingType`, …) could otherwise have a field-only change -/// wrongly skipped as a no-op. `same_content` deliberately ignores `ttl`, so -/// an explicit `--ttl` change (checked separately here, against the *raw* -/// `req.opts.ttl` rather than `desired.ttl`'s defaulted value, so an omitted -/// `--ttl` never forces a replace just because the default differs from the -/// existing record's) still counts as a real change even when the value and -/// every other field are unchanged — but that one can't be create-then-delete -/// (the create would be an exact duplicate of the record it replaces), so it -/// goes through [`retime_record`] instead. +/// A `PUT` must carry a TTL. When the caller gave no `--ttl`, the record keeps +/// the TTL it has (`old_ttl`) rather than being reset to the default, the same +/// as a record `set` leaves alone. /// -/// Relabels the create outcome's `kind` from `"created"` to `"replaced"` so -/// `summarize_set_outcomes`'s tallies mean what the user asked for. If the -/// delete of the old record fails after a successful create, that's reported -/// as an extra `"cleanup"`-kind outcome — a kind `summarize_set_outcomes`'s -/// counts don't recognize, so it doesn't inflate replaced/created/deleted, -/// but its `error` still fails the command and shows up in the breakdown. +/// Relabels the write outcome's `kind` from `"created"` to `"replaced"` so +/// `summarize_set_outcomes`'s tallies mean what the user asked for. pub(super) async fn apply_replace( client: &domains_client::Client, req: &WriteRequest<'_>, old_record_id: &str, - old_detail: &str, - old_record: Option<&types::DnsRecord>, -) -> Vec { - let desired = v3_record(req.name, req.record_type, req.value, req.opts); - if let Some(old) = old_record.filter(|r| same_content(r, &desired)) { - // Same record; only an explicit `--ttl` (not the defaulted one on - // `desired`) that differs from the stored one is a change. - return match req.opts.ttl.filter(|&t| t != old.ttl) { - Some(_) => retime_record(client, req, old_record_id, old_detail, old).await, - None => vec![SetOutcome::new("replaced", req.value.to_string(), None)], - }; - } - - let mut outcomes = write_with_conflict_handling(client, req).await; - let Some(last) = outcomes.last_mut() else { - return outcomes; - }; - last.kind = "replaced"; - if last.error.is_some() { - return outcomes; - } - - if let Err(e) = client - .delete_dns_record() - .zone(req.domain) - .record_id(old_record_id) - .send() - .await - { - let msg = format!( - "the new value was created, but the previous record ({old_detail}) could not be \ - removed: {}; run `gddy dns list {} --type {} --name {}` to review the current \ - state and remove it manually if it's still there", - api_error("deleting the previous DNS record", req.debug, e).await, - req.domain, - req.record_type, - req.name, - ); - outcomes.push(SetOutcome::new( - "cleanup", - old_detail.to_string(), - Some(msg), - )); - } - outcomes -} - -/// Change only the TTL of a record `set` is keeping. v3 identifies a record by -/// its content, not its TTL, so creating the new-TTL record while the old one -/// still exists fails as an exact duplicate — the old record has to be deleted -/// first. That leaves the value missing until the create lands, so if the create -/// fails the old record is put back unchanged and the failure reported; only if -/// that restore fails too is a `"cleanup"` outcome added saying the record is gone. -async fn retime_record( - client: &domains_client::Client, - req: &WriteRequest<'_>, - old_record_id: &str, - old_detail: &str, - old: &types::DnsRecord, + old_ttl: Option, ) -> Vec { - let replaced = |err: Option| SetOutcome::new("replaced", req.value.to_string(), err); - - if let Err(e) = client - .delete_dns_record() - .zone(req.domain) - .record_id(old_record_id) - .send() - .await - { - return vec![replaced(Some( - api_error("deleting the previous DNS record", req.debug, e) - .await - .to_string(), - ))]; - } - - let mut outcomes = write_with_conflict_handling(client, req).await; - let Some(last) = outcomes.last_mut() else { - return outcomes; - }; - last.kind = "replaced"; - let Some(create_err) = last.error.clone() else { - return outcomes; + let mut opts = req.opts.clone(); + opts.ttl = opts.ttl.or(old_ttl); + let req = WriteRequest { + opts: &opts, + replacing: Some(old_record_id), + ..*req }; - - let restored = types::DnsRecord { - record_id: None, - ..old.clone() - }; - match client - .create_dns_record() - .zone(req.domain) - .body(restored) - .send() - .await - { - Ok(_) => { - last.error = Some(format!( - "{create_err}; the previous record was left as it was" - )) - } - Err(e) => { - let msg = format!( - "the previous record ({old_detail}) was removed to change its TTL, the new one \ - could not be created, and putting it back failed: {}; run `gddy dns list {} \ - --type {} --name {}` and re-create it with `gddy dns add` if it's gone", - api_error("restoring the previous DNS record", req.debug, e).await, - req.domain, - req.record_type, - req.name, - ); - outcomes.push(SetOutcome::new( - "cleanup", - old_detail.to_string(), - Some(msg), - )); - } + let mut outcomes = write_with_conflict_handling(client, &req).await; + if let Some(last) = outcomes.last_mut() { + last.kind = "replaced"; } outcomes } diff --git a/rust/src/dns/set/write_tests.rs b/rust/src/dns/set/write_tests.rs index 899a28f4..37f245e5 100644 --- a/rust/src/dns/set/write_tests.rs +++ b/rust/src/dns/set/write_tests.rs @@ -59,6 +59,7 @@ async fn write_with_conflict_handling_creates_without_conflict() { value: "1.2.3.4", opts: &opts, replace_conflicting: false, + replacing: None, debug: false, }; let outcomes = write_with_conflict_handling(&client_for(&server), &req).await; @@ -67,6 +68,8 @@ async fn write_with_conflict_handling_creates_without_conflict() { assert_eq!(outcomes.len(), 1); assert_eq!(outcomes[0].kind, "created"); assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); + let record = outcomes[0].record.as_ref().expect("the created record"); + assert_eq!(record.data.as_deref(), Some("1.2.3.4")); } #[tokio::test] @@ -99,6 +102,7 @@ async fn write_with_conflict_handling_sends_https_parameters_in_request_body() { value: ".", opts: &opts, replace_conflicting: false, + replacing: None, debug: false, }; let outcomes = write_with_conflict_handling(&client_for(&server), &req).await; @@ -146,6 +150,7 @@ async fn write_with_conflict_handling_sends_tlsa_fields_in_request_body() { value: cert, opts: &opts, replace_conflicting: false, + replacing: None, debug: false, }; let outcomes = write_with_conflict_handling(&client_for(&server), &req).await; @@ -192,6 +197,7 @@ async fn write_with_conflict_handling_conflict_without_flag_reports_message_and_ value: "1.2.3.4", opts: &opts, replace_conflicting: false, + replacing: None, debug: false, }; let outcomes = write_with_conflict_handling(&client_for(&server), &req).await; @@ -246,6 +252,7 @@ async fn write_with_conflict_handling_replace_flag_deletes_then_retries_in_order value: "1.2.3.4", opts: &opts, replace_conflicting: true, + replacing: None, debug: false, }; let outcomes = write_with_conflict_handling(&client_for(&server), &req).await; @@ -267,12 +274,11 @@ async fn write_with_conflict_handling_replace_flag_deletes_then_retries_in_order // --- apply_replace ------------------------------------------------------- // -// `set`'s "replace" semantic is create-the-new-value-then-delete-the-old -// (v3 has no atomic single-record replace; see GH #136). These exercise: -// the happy path (create then delete, one "replaced" outcome), the create -// failing (delete must never be attempted — the old record stays intact), -// and the delete failing after a successful create (reported as a -// separate "cleanup" outcome that still fails the command). +// `set`'s "replace" is one in-place `PUT` of the paired record. These exercise: +// the happy path (a single PUT, one "replaced" outcome, no create or delete), +// the PUT failing, and the conflict handling a replace shares with a create. +// Pairings that need no change never reach `apply_replace`; the plan sets them +// aside (see `plan_set`). fn replace_req<'a>(opts: &'a RecordOptions, value: &'a str) -> WriteRequest<'a> { WriteRequest { @@ -282,227 +288,105 @@ fn replace_req<'a>(opts: &'a RecordOptions, value: &'a str) -> WriteRequest<'a> value, opts, replace_conflicting: false, + replacing: None, debug: false, } } -fn old_a_record(data: &str) -> types::DnsRecord { - types::DnsRecord { - certificate_data: None, - matching_type: None, - selector: None, - usage: None, - data: Some(data.to_owned()), - flag: None, - name: "www".to_owned(), - parameters: None, - port: None, - priority: None, - protocol: None, - record_id: Some("old-1".to_owned()), - service: None, - tag: None, - ttl: 3600, - type_: types::DnsRecordType("A".to_owned()), - weight: None, - } -} +const RECORD_PATH: &str = "/v3/domains/zones/example.com/dns-records"; -#[tokio::test] -async fn apply_replace_creates_then_deletes_the_old_record() { - let server = MockServer::start_async().await; +/// Mocks that fail the test if a replace falls back to a create or delete. +async fn no_create_or_delete<'a>( + server: &'a MockServer, +) -> (httpmock::Mock<'a>, httpmock::Mock<'a>) { let create = server .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); - then.status(201) - .json_body(json!({ "type": "A", "name": "www", "data": "9.9.9.9", "ttl": 3600 })); + when.method(POST).path(RECORD_PATH); + then.status(201).json_body(json!({})); }) .await; let delete = server .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); + when.method(DELETE).path(format!("{RECORD_PATH}/old-1")); then.status(204); }) .await; - - let opts = write_opts(); - let req = replace_req(&opts, "9.9.9.9"); - let old_record = old_a_record("1.2.3.4"); - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; - - create.assert_async().await; - delete.assert_async().await; - assert_eq!(outcomes.len(), 1); - assert_eq!(outcomes[0].kind, "replaced"); - assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); + (create, delete) } -/// The record being "replaced" already holds the desired value (e.g. a -/// re-run of the same `set`, or only some of several `--data` values -/// actually changed) — creating it again would hit v3's exact-duplicate -/// `DUPLICATE_RECORD` since the old record hasn't been deleted yet, so -/// this must short-circuit as a no-op success without any API calls. #[tokio::test] -async fn apply_replace_is_a_no_op_when_old_record_already_has_the_desired_value() { +async fn apply_replace_puts_the_new_value_onto_the_old_record() { let server = MockServer::start_async().await; - let create = server - .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); - then.status(201); - }) - .await; - let delete = server + let put = server .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); - then.status(204); + when.method(PUT) + .path(format!("{RECORD_PATH}/old-1")) + .json_body(json!({ "type": "A", "name": "www", "data": "9.9.9.9", "ttl": 3600 })); + then.status(200).json_body(json!({ + "recordId": "old-1", "type": "A", "name": "www", "data": "9.9.9.9", "ttl": 3600 + })); }) .await; + let (create, delete) = no_create_or_delete(&server).await; let opts = write_opts(); - let req = replace_req(&opts, "1.2.3.4"); - let old_record = old_a_record("1.2.3.4"); - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; - - assert_eq!( - create.calls_async().await, - 0, - "no create for a no-op replace" - ); - assert_eq!( - delete.calls_async().await, - 0, - "no delete for a no-op replace" - ); + let req = replace_req(&opts, "9.9.9.9"); + let outcomes = apply_replace(&client_for(&server), &req, "old-1", Some(3600)).await; + + put.assert_async().await; + assert_eq!(create.calls_async().await, 0, "a replace must not create"); + assert_eq!(delete.calls_async().await, 0, "a replace must not delete"); assert_eq!(outcomes.len(), 1); assert_eq!(outcomes[0].kind, "replaced"); - assert_eq!(outcomes[0].detail, "1.2.3.4"); assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); + let record = outcomes[0].record.as_ref().expect("the PUT's record"); + assert_eq!(record.record_id.as_deref(), Some("old-1")); + assert_eq!(record.data.as_deref(), Some("9.9.9.9")); } -/// `same_content` deliberately ignores `ttl`, so an explicit `--ttl` -/// change has to be checked separately — otherwise a `dns set` that only -/// changes the TTL would be silently skipped as a no-op. +/// A changed TTL on an otherwise identical record is one `PUT` — no +/// delete-then-create, and no window in which the value is missing. #[tokio::test] -async fn apply_replace_is_not_a_no_op_when_ttl_explicitly_changes() { +async fn apply_replace_changes_only_the_ttl_with_a_single_put() { let server = MockServer::start_async().await; - let create = server + let put = server .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); - then.status(201) + when.method(PUT) + .path(format!("{RECORD_PATH}/old-1")) .json_body(json!({ "type": "A", "name": "www", "data": "1.2.3.4", "ttl": 7200 })); + then.status(200).json_body(json!({ + "recordId": "old-1", "type": "A", "name": "www", "data": "1.2.3.4", "ttl": 7200 + })); }) .await; - let delete = server - .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); - then.status(204); - }) - .await; + let (create, delete) = no_create_or_delete(&server).await; let mut opts = write_opts(); opts.ttl = Some(7200); let req = replace_req(&opts, "1.2.3.4"); - let old_record = old_a_record("1.2.3.4"); // ttl: 3600 - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; - - create.assert_async().await; - delete.assert_async().await; - assert_eq!(outcomes.len(), 1); - assert_eq!(outcomes[0].kind, "replaced"); - assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); -} - -/// Omitting `--ttl` must not force a replace just because the CLI's -/// default (3600) differs from the existing record's actual TTL — only -/// an *explicit* `--ttl` counts as a real change. -#[tokio::test] -async fn apply_replace_is_still_a_no_op_when_ttl_is_omitted_even_if_existing_ttl_differs() { - let server = MockServer::start_async().await; - let create = server - .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); - then.status(201); - }) - .await; - let delete = server - .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); - then.status(204); - }) - .await; + let outcomes = apply_replace(&client_for(&server), &req, "old-1", Some(3600)).await; - let opts = write_opts(); // ttl: None — no explicit --ttl - let req = replace_req(&opts, "1.2.3.4"); - let old_record = types::DnsRecord { - ttl: 7200, // differs from v3_record's DEFAULT_TTL fallback (3600) - ..old_a_record("1.2.3.4") - }; - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; - - assert_eq!( - create.calls_async().await, - 0, - "no create for a no-op replace" - ); - assert_eq!( - delete.calls_async().await, - 0, - "no delete for a no-op replace" - ); + put.assert_async().await; + assert_eq!(create.calls_async().await, 0); + assert_eq!(delete.calls_async().await, 0); assert_eq!(outcomes.len(), 1); assert_eq!(outcomes[0].kind, "replaced"); assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); } -/// A TLSA record's identity spans `usage`/`selector`/`matchingType`, not -/// just its certificate data — keeping the same `--data` while changing -/// `--usage` is a real change, not a no-op, even though comparing only -/// the value string would say otherwise. #[tokio::test] -async fn apply_replace_is_not_a_no_op_when_only_a_sibling_tlsa_field_changes() { +async fn apply_replace_sends_the_changed_tlsa_fields_in_the_put_body() { let server = MockServer::start_async().await; let cert = "d2abde240d7cd3ee6b4b28c54df034b97983a1d16e8a410e4561cb106618e971"; - let create = server + let put = server .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); - then.status(201).json_body(json!({ + when.method(PUT) + .path(format!("{RECORD_PATH}/old-1")) + .json_body_includes( + json!({ "usage": 1, "selector": 0, "matchingType": 0 }).to_string(), + ); + then.status(200).json_body(json!({ + "recordId": "old-1", "type": "TLSA", "name": "www", "ttl": 3600, @@ -513,289 +397,138 @@ async fn apply_replace_is_not_a_no_op_when_only_a_sibling_tlsa_field_changes() { })); }) .await; - let delete = server - .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); - then.status(204); - }) - .await; let mut opts = write_opts(); opts.usage = Some(1); opts.selector = Some(0); opts.matching_type = Some(0); let req = WriteRequest { - domain: "example.com", - name: "www", record_type: "TLSA", value: cert, opts: &opts, - replace_conflicting: false, - debug: false, - }; - let old_record = types::DnsRecord { - certificate_data: Some(cert.to_owned()), - matching_type: Some(types::TlsaMatchingType(1)), - selector: Some(types::TlsaSelector(1)), - usage: Some(types::TlsaUsage(3)), - data: None, - flag: None, - name: "www".to_owned(), - parameters: None, - port: None, - priority: None, - protocol: None, - record_id: Some("old-1".to_owned()), - service: None, - tag: None, - ttl: 3600, - type_: types::DnsRecordType("TLSA".to_owned()), - weight: None, + ..replace_req(&opts, cert) }; - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "TLSA 3 1 1 ...", - Some(&old_record), - ) - .await; + let outcomes = apply_replace(&client_for(&server), &req, "old-1", Some(3600)).await; - create.assert_async().await; - delete.assert_async().await; + put.assert_async().await; assert_eq!(outcomes.len(), 1); assert_eq!(outcomes[0].kind, "replaced"); assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); } #[tokio::test] -async fn apply_replace_leaves_old_record_alone_when_create_fails() { +async fn apply_replace_reports_the_failure_and_touches_nothing_else_when_the_put_fails() { let server = MockServer::start_async().await; server .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); + when.method(PUT).path(format!("{RECORD_PATH}/old-1")); then.status(500); }) .await; - let delete = server - .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); - then.status(204); - }) - .await; + let (create, delete) = no_create_or_delete(&server).await; let opts = write_opts(); let req = replace_req(&opts, "9.9.9.9"); - let old_record = old_a_record("1.2.3.4"); - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; - - assert_eq!( - delete.calls_async().await, - 0, - "the old record must not be touched when the create fails" - ); - assert_eq!(outcomes.len(), 1); - assert_eq!(outcomes[0].kind, "replaced"); - assert!(outcomes[0].error.is_some()); -} - -// --- retime_record (value kept, explicit --ttl differs) ------------------- -// -// The old record is 1.2.3.4 @ ttl 3600; the set asks for 1.2.3.4 @ ttl 7200. -// The new-TTL create and the put-back of the old record are told apart by the -// `ttl` in the request body. - -fn retime_opts() -> RecordOptions { - let mut opts = write_opts(); - opts.ttl = Some(7200); - opts -} - -#[tokio::test] -async fn retime_does_not_create_when_the_old_record_cannot_be_deleted() { - let server = MockServer::start_async().await; - let create = server - .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); - then.status(201); - }) - .await; - server - .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); - then.status(500); - }) - .await; + let outcomes = apply_replace(&client_for(&server), &req, "old-1", Some(3600)).await; - let opts = retime_opts(); - let req = replace_req(&opts, "1.2.3.4"); - let old_record = old_a_record("1.2.3.4"); - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; - - // Delete-first is what avoids the duplicate create, so a failed delete - // has to stop everything before a create is attempted. assert_eq!(create.calls_async().await, 0); + assert_eq!(delete.calls_async().await, 0); assert_eq!(outcomes.len(), 1); assert_eq!(outcomes[0].kind, "replaced"); assert!(outcomes[0].error.is_some()); } +/// A replace that collides with a CNAME at the name gets the same +/// `--replace-conflicting-types` handling a create does: delete the +/// conflicting record, then retry the PUT once. #[tokio::test] -async fn retime_puts_the_old_record_back_when_the_new_ttl_cannot_be_created() { +async fn apply_replace_with_the_flag_deletes_a_conflicting_cname_then_retries_the_put() { let server = MockServer::start_async().await; - server + let first_put = server .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records") - .json_body_includes(r#"{"ttl":7200}"#); - then.status(500); + when.method(PUT).path(format!("{RECORD_PATH}/old-1")); + then.status(422).body(DUPLICATE_RECORD_BODY); }) .await; - let restore = server + server .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records") - .json_body_includes(r#"{"ttl":3600}"#); - then.status(201) - .json_body(json!({ "type": "A", "name": "www", "data": "1.2.3.4", "ttl": 3600 })); + when.method(GET).path(RECORD_PATH); + then.status(200).json_body(json!({ + "items": [ + { "recordId": "cn-1", "type": "CNAME", "name": "www", "data": "parkpage.godaddy.com", "ttl": 3600 }, + { "recordId": "old-1", "type": "AAAA", "name": "www", "data": "::1", "ttl": 3600 } + ], + "links": [] + })); }) .await; - let delete = server + let delete_conflict = server .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); + when.method(DELETE).path(format!("{RECORD_PATH}/cn-1")); then.status(204); }) .await; - let opts = retime_opts(); - let req = replace_req(&opts, "1.2.3.4"); - let old_record = old_a_record("1.2.3.4"); - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; + let opts = write_opts(); + let req = WriteRequest { + replace_conflicting: true, + ..replace_req(&opts, "1.2.3.4") + }; + let outcomes = apply_replace(&client_for(&server), &req, "old-1", Some(3600)).await; - delete.assert_async().await; - restore.assert_async().await; - assert_eq!(outcomes.len(), 1); - assert_eq!(outcomes[0].kind, "replaced"); - let err = outcomes[0] - .error - .as_deref() - .expect("create failure reported"); - assert!(err.contains("left as it was"), "{err}"); + // The retried PUT hits the same mocked conflict, so it reports failure, but + // the conflicting CNAME was deleted first and the PUT attempted twice. + delete_conflict.assert_async().await; + assert_eq!(first_put.calls_async().await, 2); + assert_eq!(outcomes.len(), 2); + assert_eq!(outcomes[0].kind, "deleted"); + assert_eq!(outcomes[1].kind, "replaced"); } +/// With no `--ttl`, a replaced record keeps the TTL it had instead of being +/// reset to the 3600 default. #[tokio::test] -async fn retime_reports_cleanup_when_the_old_record_cannot_be_put_back() { +async fn apply_replace_keeps_the_stored_ttl_when_none_is_given() { let server = MockServer::start_async().await; - server + let put = server .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); - then.status(500); - }) - .await; - server - .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); - then.status(204); + when.method(PUT) + .path(format!("{RECORD_PATH}/old-1")) + .json_body(json!({ "type": "A", "name": "www", "data": "9.9.9.9", "ttl": 600 })); + then.status(200).json_body(json!({ + "recordId": "old-1", "type": "A", "name": "www", "data": "9.9.9.9", "ttl": 600 + })); }) .await; - let opts = retime_opts(); - let req = replace_req(&opts, "1.2.3.4"); - let old_record = old_a_record("1.2.3.4"); - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; + let opts = write_opts(); + let req = replace_req(&opts, "9.9.9.9"); + let outcomes = apply_replace(&client_for(&server), &req, "old-1", Some(600)).await; - assert_eq!(outcomes.len(), 2); - assert_eq!(outcomes[0].kind, "replaced"); - assert!(outcomes[0].error.is_some()); - assert_eq!(outcomes[1].kind, "cleanup"); - let err = outcomes[1] - .error - .as_deref() - .expect("restore failure reported"); - assert!(err.contains("putting it back failed"), "{err}"); + put.assert_async().await; + assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); } +/// An explicit `--ttl` wins over the stored one. #[tokio::test] -async fn apply_replace_reports_cleanup_outcome_when_delete_of_old_record_fails() { +async fn apply_replace_uses_an_explicit_ttl_over_the_stored_one() { let server = MockServer::start_async().await; - let create = server - .mock_async(|when, then| { - when.method(POST) - .path("/v3/domains/zones/example.com/dns-records"); - then.status(201) - .json_body(json!({ "type": "A", "name": "www", "data": "9.9.9.9", "ttl": 3600 })); - }) - .await; - let delete = server + let put = server .mock_async(|when, then| { - when.method(DELETE) - .path("/v3/domains/zones/example.com/dns-records/old-1"); - then.status(404).json_body(json!({ - "correlationId": "c-1", - "message": "Record not found in DNS zone.", - "name": "RECORD_NOT_FOUND" + when.method(PUT) + .path(format!("{RECORD_PATH}/old-1")) + .json_body(json!({ "type": "A", "name": "www", "data": "9.9.9.9", "ttl": 900 })); + then.status(200).json_body(json!({ + "recordId": "old-1", "type": "A", "name": "www", "data": "9.9.9.9", "ttl": 900 })); }) .await; - let opts = write_opts(); + let mut opts = write_opts(); + opts.ttl = Some(900); let req = replace_req(&opts, "9.9.9.9"); - let old_record = old_a_record("1.2.3.4"); - let outcomes = apply_replace( - &client_for(&server), - &req, - "old-1", - "A 1.2.3.4", - Some(&old_record), - ) - .await; + let outcomes = apply_replace(&client_for(&server), &req, "old-1", Some(600)).await; - create.assert_async().await; - delete.assert_async().await; - assert_eq!(outcomes.len(), 2); - assert_eq!(outcomes[0].kind, "replaced"); + put.assert_async().await; assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); - assert_eq!(outcomes[1].kind, "cleanup"); - let err = outcomes[1] - .error - .as_deref() - .expect("cleanup failure reported"); - assert!(err.contains("A 1.2.3.4"), "{err}"); - assert!(err.contains("dns list"), "{err}"); } diff --git a/rust/tools/generate-api-catalog/src/domains_spec.rs b/rust/tools/generate-api-catalog/src/domains_spec.rs index a8d2083f..97a73815 100644 --- a/rust/tools/generate-api-catalog/src/domains_spec.rs +++ b/rust/tools/generate-api-catalog/src/domains_spec.rs @@ -387,10 +387,9 @@ fn rename_v1(_section: &str, name: &str) -> String { format!("V1{name}") } -/// Re-applies the two deliberate deviations from the literal upstream v3 -/// contract that `domains-client` needs — previously enforced by -/// `regenerate-spec.sh`'s `jq` patch step, now ported here so a fresh v3 -/// clone can't silently drop them: +/// Re-applies the deliberate deviation from the literal upstream v3 contract +/// that `domains-client` needs — previously enforced by `regenerate-spec.sh`'s +/// `jq` patch step, now ported here so a fresh v3 clone can't silently drop it: /// /// * `listDomains`'s `statuses` parameter: force `items` to a plain /// string. progenitor always seq-serializes an array-of-enum setter as @@ -399,12 +398,6 @@ fn rename_v1(_section: &str, name: &str) -> String { /// value the way a bare-string schema can. Losing this silently breaks /// `--status` with a live `400 MISMATCH_FORMAT` — pinned by /// `domains_client::tests::statuses_param_items_stay_a_plain_string`. -/// * `replaceDNSRecord`: drop the PUT entirely. Despite returning 200, it -/// silently replaces the entire dns-records collection instead of the -/// one record — see . Do not -/// remove this rule without a confirmed server-side fix and a fresh live -/// check against a real zone with unrelated records; pinned by -/// `domains_client::tests::replace_dns_record_stays_removed`. fn apply_deliberate_deviations(v3: &mut Value) { if let Some(params) = v3 .pointer_mut("/paths/~1v3~1domains~1domain-names/get/parameters") @@ -418,13 +411,6 @@ fn apply_deliberate_deviations(v3: &mut Value) { } } } - - if let Some(item) = v3 - .pointer_mut("/paths/~1v3~1domains~1zones~1{zone}~1dns-records~1{recordId}") - .and_then(Value::as_object_mut) - { - item.remove("put"); - } } // --------------------------------------------------------------------------- @@ -660,14 +646,14 @@ pub(crate) fn domains_client_oas3_path() -> PathBuf { mod tests { use super::*; - /// Guards the two deliberate deviations `apply_deliberate_deviations` - /// re-applies — both are silent no-ops on a typo'd JSON pointer (no + /// Guards the deliberate deviation `apply_deliberate_deviations` + /// re-applies — it is a silent no-op on a typo'd JSON pointer (no /// compile or runtime error), so this pins the exact shape the function /// expects post path-rewrite (`/v3/domains/...`, matching `merge`'s /// output) rather than relying on `domains-client`'s own regression /// tests to notice only after a fresh spec pull overwrites the file. #[test] - fn apply_deliberate_deviations_rewrites_statuses_and_drops_the_dns_put() { + fn apply_deliberate_deviations_rewrites_statuses_and_leaves_the_dns_put() { let mut v3 = serde_json::json!({ "paths": { "/v3/domains/domain-names": { @@ -700,7 +686,7 @@ mod tests { let dns_item = v3 .pointer("/paths/~1v3~1domains~1zones~1{zone}~1dns-records~1{recordId}") .expect("dns-records path item"); - assert!(dns_item.get("put").is_none(), "{dns_item:?}"); + assert!(dns_item.get("put").is_some(), "{dns_item:?}"); assert!(dns_item.get("get").is_some(), "{dns_item:?}"); assert!(dns_item.get("delete").is_some(), "{dns_item:?}"); } From 6c65cf244e743cc130bb83e805aa7a6c2f158766 Mon Sep 17 00:00:00 2001 From: Jacob Page Date: Tue, 3 Nov 2026 17:47:59 -0800 Subject: [PATCH 2/5] fix(dns): compare records the way the API stores them in dns set `dns set` now judges whether a record already matches, and whether the final read-back matches, using one comparison that follows how the API stores each field, so re-running `set` with `Example.COM` for a CNAME that is stored as `example.com.` reports it unchanged instead of replacing it again. - Hostnames (CNAME, MX, SRV, HTTPS, SVCB targets) and record names are compared without case or a trailing dot; CAA data and TLSA certificate hex are compared without case. - Values the API keeps as written are compared exactly: TXT text, AAAA addresses, HTTPS/SVCB parameters, and SRV service and protocol. A concurrent change in case there is now caught by the final check. - The records in the result come from the final read-back, so the IDs and TTLs shown are what is in the zone, not what each write returned. Co-Authored-By: Claude Sonnet 5.5 --- rust/src/dns/set/mod.rs | 34 +++++++++++------------ rust/src/dns/set/outcome.rs | 35 +----------------------- rust/src/dns/set/plan.rs | 15 +++++++++++ rust/src/dns/set/verify.rs | 40 +++++---------------------- rust/src/dns/set/verify_tests.rs | 46 ++++++++++++++++++++++++++++++-- rust/src/dns/set/write.rs | 12 ++++----- rust/src/dns/set/write_tests.rs | 5 ---- 7 files changed, 88 insertions(+), 99 deletions(-) diff --git a/rust/src/dns/set/mod.rs b/rust/src/dns/set/mod.rs index 3ca4a4e6..2c2237d2 100644 --- a/rust/src/dns/set/mod.rs +++ b/rust/src/dns/set/mod.rs @@ -7,6 +7,7 @@ use crate::domain::{api_error, make_client}; use crate::output_schema::output_schema; use crate::scopes::DOMAINS_DNS_UPDATE; +use super::list::build_list_output; use super::records::{ RecordOptions, RecordWriteArgs, fetch_records, v3_records, validate_caa_fields, validate_svcb_fields, validate_tlsa_fields, @@ -187,18 +188,9 @@ pub(super) fn command() -> RuntimeCommandSpec { outcomes.extend(apply_replace(&client, &req, &record_id, old_ttl).await); } SetAction::Unchanged { - record_id, data: value, - } => { - let mut outcome = SetOutcome::new("unchanged", value, None); - if let Some(record) = existing - .iter() - .find(|r| r.record_id.as_deref() == Some(record_id.as_str())) - { - outcome = outcome.with_record(record.clone()); - } - outcomes.push(outcome); - } + record_id: _, + } => outcomes.push(SetOutcome::new("unchanged", value, None)), SetAction::Create { data: value } => { let req = WriteRequest { domain: domain.as_str(), @@ -233,14 +225,10 @@ pub(super) fn command() -> RuntimeCommandSpec { let mut summary = summarize_set_outcomes(&domain, &record_type, &name, &outcomes) .map_err(super::mutate_failed)?; - if let Some(records) = summary.get_mut("records").and_then(Value::as_array_mut) { - for record in records { - domain_format.convert_fields(record, &["name"]); - } - } // The plan came from one earlier read, so confirm the type+name now - // holds exactly what was asked for before reporting success. - verify_final_state( + // holds exactly what was asked for before reporting success, and + // report the records as that read found them. + let now = verify_final_state( &client, domain.as_str(), &record_type, @@ -250,6 +238,16 @@ pub(super) fn command() -> RuntimeCommandSpec { debug, ) .await?; + let mut records = build_list_output(&now).map_err(|e| { + crate::error::GddyError::unexpected(format!( + "failed to serialize the resulting DNS records: {e}" + )) + .into_cli_error() + })?; + for record in &mut records { + domain_format.convert_fields(record, &["name"]); + } + summary["records"] = Value::Array(records); Ok(verified_result( domain_format, summary, diff --git a/rust/src/dns/set/outcome.rs b/rust/src/dns/set/outcome.rs index 7e01a3e4..477397bf 100644 --- a/rust/src/dns/set/outcome.rs +++ b/rust/src/dns/set/outcome.rs @@ -5,7 +5,6 @@ use domains_client::types; use serde_json::{Value, json}; -use super::super::list::build_list_output; use super::super::records::record_value; use super::plan::SetAction; @@ -17,9 +16,6 @@ pub(super) struct SetOutcome { pub(super) detail: String, /// `Some(msg)` if the call failed. pub(super) error: Option, - /// The record as the API returned it after a successful create or - /// replace, or as it already stood for a replace that needed no change. - pub(super) record: Option, } impl SetOutcome { @@ -28,19 +24,12 @@ impl SetOutcome { kind, detail, error, - record: None, } } - - pub(super) fn with_record(mut self, record: types::DnsRecord) -> Self { - self.record = Some(record); - self - } } /// Build the `set` result from the applied reconcile outcomes: `Ok(json)` with -/// replaced/created/deleted counts and the records now in place (as `dns list` -/// shows them) when every action succeeded, or `Err(message)` +/// replaced/unchanged/created/deleted counts when every action succeeded, or `Err(message)` /// — a non-zero exit — with a per-action ✓/✗ breakdown if any failed. Pure so the /// success/failure decision and tallies are unit-testable. pub(super) fn summarize_set_outcomes( @@ -80,10 +69,6 @@ pub(super) fn summarize_set_outcomes( )); } - let written: Vec = outcomes.iter().filter_map(|o| o.record.clone()).collect(); - let records = build_list_output(&written) - .map_err(|e| format!("failed to serialize the resulting DNS records: {e}"))?; - Ok(json!({ "domain": domain, "type": record_type, @@ -93,7 +78,6 @@ pub(super) fn summarize_set_outcomes( "created": created, "deleted": deleted, "action": "set", - "records": records, })) } @@ -217,23 +201,6 @@ mod tests { assert!(err.contains("✗ created 8.8.8.8 — 422 bad"), "{err}"); } - #[test] - fn summarize_set_lists_the_records_the_api_returned() { - let mut stored = tlsa_record("r1", "abc"); - stored.type_ = types::DnsRecordType("A".to_owned()); - stored.certificate_data = None; - stored.data = Some("9.9.9.9".to_owned()); - let outcomes = vec![ - SetOutcome::new("replaced", "9.9.9.9".into(), None).with_record(stored), - SetOutcome::new("deleted", "r3".into(), None), - ]; - let v = summarize_set_outcomes("example.com", "A", "www", &outcomes).expect("all ok"); - let records = v["records"].as_array().expect("records array"); - assert_eq!(records.len(), 1, "a delete leaves no record behind: {v}"); - assert_eq!(records[0]["data"], "9.9.9.9"); - assert_eq!(records[0]["recordId"], "r1"); - } - #[test] fn dry_run_set_preview_matches_the_plan_it_would_execute() { let plan = [ diff --git a/rust/src/dns/set/plan.rs b/rust/src/dns/set/plan.rs index c2753354..7107a029 100644 --- a/rust/src/dns/set/plan.rs +++ b/rust/src/dns/set/plan.rs @@ -367,6 +367,21 @@ mod tests { ); } + #[test] + fn plan_set_treats_an_api_normalized_record_as_unchanged() { + // `Example.COM` is stored as `example.com.`; asking for it again is a + // no-op, not another replace. + let existing = [stored("r1", "CNAME", "example.com.", &opts())]; + let desired = [wanted("CNAME", "Example.COM", &opts())]; + assert_eq!( + plan_set(&existing, &desired, None), + vec![SetAction::Unchanged { + record_id: "r1".into(), + data: "Example.COM".into() + }] + ); + } + fn srv_opts() -> RecordOptions { RecordOptions { priority: Some(1), diff --git a/rust/src/dns/set/verify.rs b/rust/src/dns/set/verify.rs index 6cf726bc..c972843b 100644 --- a/rust/src/dns/set/verify.rs +++ b/rust/src/dns/set/verify.rs @@ -5,9 +5,8 @@ use cli_engine::CliCoreError; use domains_client::types; -use serde_json::Value; -use crate::dns::records::{fetch_records, record_value}; +use crate::dns::records::{comparable, fetch_records, record_value}; /// What differs between the records asked for and the records now present. #[derive(Debug, PartialEq)] @@ -18,33 +17,6 @@ pub(super) struct Mismatch { pub(super) unexpected: Vec, } -/// The comparable content of a record: everything but its id and its type and -/// name (every record compared was fetched or built for the same type+name), and -/// its TTL unless the caller set one. The API stores domain names lower-cased -/// with a trailing dot (`Example.COM` comes back as `example.com.`), so text -/// fields are compared in that form; TXT is left as written since its text is -/// case-sensitive. -fn comparable(record: &types::DnsRecord, compare_ttl: bool) -> Value { - let mut value = serde_json::to_value(record).expect("DnsRecord always serializes to JSON"); - let is_txt = record.type_.as_str() == "TXT"; - if let Some(fields) = value.as_object_mut() { - for key in ["recordId", "type", "name"] { - fields.remove(key); - } - if !compare_ttl { - fields.remove("ttl"); - } - if !is_txt { - for field in fields.values_mut() { - if let Value::String(text) = field { - *text = text.trim_end_matches('.').to_lowercase(); - } - } - } - } - value -} - /// A short human label for a record, including the fields that tell records /// with the same value apart (MX priority, CAA tag, TLSA usage, …). fn describe(record: &types::DnsRecord) -> String { @@ -83,7 +55,7 @@ pub(super) fn final_set_mismatch( actual: &[types::DnsRecord], compare_ttl: bool, ) -> Option { - let mut remaining: Vec<(Value, &types::DnsRecord)> = actual + let mut remaining: Vec<(serde_json::Value, &types::DnsRecord)> = actual .iter() .map(|r| (comparable(r, compare_ttl), r)) .collect(); @@ -108,8 +80,8 @@ pub(super) fn final_set_mismatch( } } -/// Read the type+name back and check it against `desired`. `Ok(())` when they -/// match; otherwise a non-zero error that lists what is extra and what is +/// Read the type+name back and check it against `desired`. `Ok` with the records +/// as they now stand when they match; otherwise a non-zero error that lists what is extra and what is /// missing and leaves the zone as it is — a record that appeared in the /// meantime may belong to someone else, so it is reported rather than removed. pub(super) async fn verify_final_state( @@ -120,7 +92,7 @@ pub(super) async fn verify_final_state( desired: &[types::DnsRecord], compare_ttl: bool, debug: bool, -) -> Result<(), CliCoreError> { +) -> Result, CliCoreError> { let review = format!("gddy dns list {domain} --type {record_type} --name {name}"); let actual = fetch_records(client, domain, Some(record_type), Some(name), debug) .await @@ -134,7 +106,7 @@ pub(super) async fn verify_final_state( })?; let Some(mismatch) = final_set_mismatch(desired, &actual, compare_ttl) else { - return Ok(()); + return Ok(actual); }; let list = |items: &[String]| { items diff --git a/rust/src/dns/set/verify_tests.rs b/rust/src/dns/set/verify_tests.rs index e774ec3e..a5225be0 100644 --- a/rust/src/dns/set/verify_tests.rs +++ b/rust/src/dns/set/verify_tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::dns::records::{RecordOptions, v3_record}; use httpmock::prelude::*; -use serde_json::json; +use serde_json::{Value, json}; fn opts() -> RecordOptions { RecordOptions { @@ -102,6 +102,45 @@ fn txt_text_is_compared_exactly() { assert!(final_set_mismatch(&desired, &actual, false).is_some()); } +#[test] +fn case_sensitive_values_are_compared_exactly() { + let mut caa_opts = opts(); + caa_opts.flag = Some(0); + caa_opts.tag = Some("iodef".to_owned()); + // The API lower-cases CAA data, so a different case is not a different record... + let desired = [v3_record( + "@", + "CAA", + "https://Example.com/Report", + &caa_opts, + )]; + let stored_caa = [stored( + v3_record("@", "CAA", "https://example.com/report", &caa_opts), + "r1", + )]; + assert_eq!(final_set_mismatch(&desired, &stored_caa, false), None); + + // ...but HTTPS/SVCB parameters, TXT text and AAAA text are kept as written, + // so a concurrent change in case there must not pass. + let mut ech = opts(); + ech.priority = Some(1); + ech.parameters = Some("ech=AbCd==".to_owned()); + let want = [v3_record("@", "HTTPS", "svc.example.com.", &ech)]; + ech.parameters = Some("ech=abcd==".to_owned()); + let have = [stored( + v3_record("@", "HTTPS", "svc.example.com.", &ech), + "r1", + )]; + assert!(final_set_mismatch(&want, &have, false).is_some()); + + let want = [v3_record("www", "AAAA", "2001:DB8::1", &opts())]; + let have = [stored( + v3_record("www", "AAAA", "2001:db8::1", &opts()), + "r1", + )]; + assert!(final_set_mismatch(&want, &have, false).is_some()); +} + #[test] fn records_that_differ_only_in_a_sibling_field_are_different() { let mut p10 = opts(); @@ -152,7 +191,7 @@ async fn verify_passes_when_the_zone_holds_exactly_the_requested_records() { &server, json!([{ "recordId": "r1", "type": "A", "name": "www", "data": "1.1.1.1", "ttl": 3600 }]), ); - verify_final_state( + let now = verify_final_state( &client_for(&server), "example.com", "A", @@ -163,6 +202,9 @@ async fn verify_passes_when_the_zone_holds_exactly_the_requested_records() { ) .await .expect("zone matches"); + // The records come back as the read found them, ids and all. + assert_eq!(now.len(), 1); + assert_eq!(now[0].record_id.as_deref(), Some("r1")); } #[tokio::test] diff --git a/rust/src/dns/set/write.rs b/rust/src/dns/set/write.rs index 268389ef..b027da90 100644 --- a/rust/src/dns/set/write.rs +++ b/rust/src/dns/set/write.rs @@ -30,12 +30,12 @@ pub(super) struct WriteRequest<'a> { } /// Send `body` as a create, or — when `req.replacing` names a record — as an -/// in-place replace of that record. Returns the record as the API stored it. +/// in-place replace of that record. async fn send_record( client: &domains_client::Client, req: &WriteRequest<'_>, body: types::DnsRecord, -) -> Result>> { +) -> Result<(), Box>> { match req.replacing { Some(record_id) => client .replace_dns_record() @@ -44,7 +44,7 @@ async fn send_record( .body(body) .send() .await - .map(|response| response.into_inner()) + .map(|_| ()) .map_err(Box::new), None => client .create_dns_record() @@ -52,7 +52,7 @@ async fn send_record( .body(body) .send() .await - .map(|response| response.into_inner()) + .map(|_| ()) .map_err(Box::new), } } @@ -129,7 +129,7 @@ pub(super) async fn write_with_conflict_handling( let body = v3_record(req.name, req.record_type, req.value, req.opts); let err = match send_record(client, req, body).await { - Ok(record) => return vec![outcome(None).with_record(record)], + Ok(()) => return vec![outcome(None)], Err(e) => *e, }; let domains_client::Error::UnexpectedResponse(resp) = err else { @@ -184,7 +184,7 @@ pub(super) async fn write_with_conflict_handling( let mut outcomes = delete_conflicts(client, req.domain, &conflicts, req.debug).await; let retry_body = v3_record(req.name, req.record_type, req.value, req.opts); let retried = match send_record(client, req, retry_body).await { - Ok(record) => outcome(None).with_record(record), + Ok(()) => outcome(None), Err(e) => outcome(Some(api_error(action, req.debug, *e).await.to_string())), }; outcomes.push(retried); diff --git a/rust/src/dns/set/write_tests.rs b/rust/src/dns/set/write_tests.rs index 37f245e5..6550dfd8 100644 --- a/rust/src/dns/set/write_tests.rs +++ b/rust/src/dns/set/write_tests.rs @@ -68,8 +68,6 @@ async fn write_with_conflict_handling_creates_without_conflict() { assert_eq!(outcomes.len(), 1); assert_eq!(outcomes[0].kind, "created"); assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); - let record = outcomes[0].record.as_ref().expect("the created record"); - assert_eq!(record.data.as_deref(), Some("1.2.3.4")); } #[tokio::test] @@ -339,9 +337,6 @@ async fn apply_replace_puts_the_new_value_onto_the_old_record() { assert_eq!(outcomes.len(), 1); assert_eq!(outcomes[0].kind, "replaced"); assert!(outcomes[0].error.is_none(), "{:?}", outcomes[0].error); - let record = outcomes[0].record.as_ref().expect("the PUT's record"); - assert_eq!(record.record_id.as_deref(), Some("old-1")); - assert_eq!(record.data.as_deref(), Some("9.9.9.9")); } /// A changed TTL on an otherwise identical record is one `PUT` — no From bcba4934f40294836838397f82ce04bddb0c200b Mon Sep 17 00:00:00 2001 From: Jacob Page Date: Tue, 3 Nov 2026 17:54:46 -0800 Subject: [PATCH 3/5] fix(dns): treat ALIAS targets as hostnames and show every differing field in dns set errors - An ALIAS record's target is compared the way a CNAME's is, without case or a trailing dot, so `set` leaves a matching ALIAS alone instead of replacing it on every run. - When the final check finds records that are not the ones requested, each one is labelled with its SRV service and protocol, and with its TTL when `--ttl` was given, so a TTL-only difference no longer shows two identical lines. Co-Authored-By: Claude Sonnet 5.5 --- rust/src/dns/records_tests.rs | 1 + rust/src/dns/set/verify.rs | 26 ++++++++++++++++++++------ rust/src/dns/set/verify_tests.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/rust/src/dns/records_tests.rs b/rust/src/dns/records_tests.rs index 9651f2fb..2b7c3c3a 100644 --- a/rust/src/dns/records_tests.rs +++ b/rust/src/dns/records_tests.rs @@ -555,6 +555,7 @@ fn same_content_follows_how_the_api_stores_each_field() { // Hostnames: case and a trailing dot are not differences. assert!(same("CNAME", "Example.COM", "example.com.")); assert!(same("ALIAS", "Example.COM", "example.com.")); + assert!(same("ALIAS", "Example.COM", "example.com.")); assert!(same("MX", "Mail.Example.com", "mail.example.com.")); // CAA data and TLSA hex are case-insensitive. assert!(same("CAA", "Letsencrypt.org", "letsencrypt.org")); diff --git a/rust/src/dns/set/verify.rs b/rust/src/dns/set/verify.rs index c972843b..1aaaf64b 100644 --- a/rust/src/dns/set/verify.rs +++ b/rust/src/dns/set/verify.rs @@ -18,8 +18,10 @@ pub(super) struct Mismatch { } /// A short human label for a record, including the fields that tell records -/// with the same value apart (MX priority, CAA tag, TLSA usage, …). -fn describe(record: &types::DnsRecord) -> String { +/// with the same value apart (MX priority, CAA tag, TLSA usage, SRV service, …), +/// and its TTL when the TTL is part of what was compared — otherwise two records +/// that differ only in TTL would get the same label. +fn describe(record: &types::DnsRecord, compare_ttl: bool) -> String { let mut parts = vec![record.type_.as_str().to_owned()]; let numbers = [ ("priority", record.priority.map(u32::from)), @@ -38,13 +40,22 @@ fn describe(record: &types::DnsRecord) -> String { parts.push(format!("{label} {number}")); } } - if let Some(tag) = &record.tag { - parts.push(format!("tag {tag}")); + for (label, text) in [ + ("tag", &record.tag), + ("service", &record.service), + ("protocol", &record.protocol), + ] { + if let Some(text) = text { + parts.push(format!("{label} {text}")); + } } parts.push(record_value(record).unwrap_or("(no data)").to_owned()); if let Some(parameters) = &record.parameters { parts.push(format!("parameters {parameters}")); } + if compare_ttl { + parts.push(format!("ttl {}", record.ttl)); + } parts.join(" ") } @@ -66,10 +77,13 @@ pub(super) fn final_set_mismatch( Some(i) => { remaining.remove(i); } - None => missing.push(describe(want)), + None => missing.push(describe(want, compare_ttl)), } } - let unexpected: Vec = remaining.iter().map(|(_, r)| describe(r)).collect(); + let unexpected: Vec = remaining + .iter() + .map(|(_, r)| describe(r, compare_ttl)) + .collect(); if missing.is_empty() && unexpected.is_empty() { None } else { diff --git a/rust/src/dns/set/verify_tests.rs b/rust/src/dns/set/verify_tests.rs index a5225be0..752fc443 100644 --- a/rust/src/dns/set/verify_tests.rs +++ b/rust/src/dns/set/verify_tests.rs @@ -141,6 +141,35 @@ fn case_sensitive_values_are_compared_exactly() { assert!(final_set_mismatch(&want, &have, false).is_some()); } +#[test] +fn a_ttl_mismatch_names_both_ttls() { + let mut slow = opts(); + slow.ttl = Some(900); + let desired = [v3_record("www", "A", "1.1.1.1", &slow)]; + let actual = [stored(a("1.1.1.1"), "r1")]; // stored at the 3600 default + let mismatch = final_set_mismatch(&desired, &actual, true).expect("ttl differs"); + assert_eq!(mismatch.missing, vec!["A 1.1.1.1 ttl 900".to_owned()]); + assert_eq!(mismatch.unexpected, vec!["A 1.1.1.1 ttl 3600".to_owned()]); +} + +#[test] +fn srv_service_and_protocol_appear_in_the_label() { + let mut srv = opts(); + srv.priority = Some(1); + srv.weight = Some(2); + srv.port = Some(443); + srv.service = Some("_sip".to_owned()); + srv.protocol = Some("_tcp".to_owned()); + let desired = [v3_record("@", "SRV", "t.example.com.", &srv)]; + let mismatch = final_set_mismatch(&desired, &[], false).expect("missing"); + assert_eq!( + mismatch.missing, + vec![ + "SRV priority 1 weight 2 port 443 service _sip protocol _tcp t.example.com.".to_owned() + ] + ); +} + #[test] fn records_that_differ_only_in_a_sibling_field_are_different() { let mut p10 = opts(); From dd6a70bd39d387d48d783121819be78395242370 Mon Sep 17 00:00:00 2001 From: Jacob Page Date: Tue, 3 Nov 2026 18:01:34 -0800 Subject: [PATCH 4/5] fix(dns): default the CAA flag to 0 in dns add and dns set The API requires a flag on every CAA record, but `--flag` was optional and left unset when omitted, so adding or setting a CAA record without it failed with "flag is required for CAA records". An omitted `--flag` now means 0 (non-critical), which is also what an existing record without an explicit flag is stored as, so running the same `set` again reports the record as unchanged. Co-Authored-By: Claude Sonnet 5.5 --- rust/src/dns/records.rs | 8 ++++++-- rust/src/dns/records_tests.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/rust/src/dns/records.rs b/rust/src/dns/records.rs index a0e5ec56..1a5abb46 100644 --- a/rust/src/dns/records.rs +++ b/rust/src/dns/records.rs @@ -178,7 +178,7 @@ pub(super) struct RecordWriteArgs { #[arg(long, value_name = "SERVICE")] pub(super) service: Option, - /// CAA flag byte, 0-255 (CAA only; 0 non-critical, 128 critical). + /// CAA flag byte, 0-255 (CAA only; 0 non-critical, 128 critical). Defaults to 0. #[arg(long, value_name = "N", value_parser = clap::value_parser!(i64).range(0..=255))] pub(super) flag: Option, @@ -290,7 +290,11 @@ pub(super) fn v3_record( .flatten() .map(types::TlsaUsage), data: (!is_tlsa).then(|| data.to_owned()), - flag: opts.flag.and_then(|n| u8::try_from(n).ok()), + // The API requires a flag on CAA records; 0 (non-critical) is the usual one. + flag: opts + .flag + .or((ty == "CAA").then_some(0)) + .and_then(|n| u8::try_from(n).ok()), name: name.to_owned(), parameters: opts.parameters.clone(), port: to_u16(opts.port), diff --git a/rust/src/dns/records_tests.rs b/rust/src/dns/records_tests.rs index 2b7c3c3a..4a77c712 100644 --- a/rust/src/dns/records_tests.rs +++ b/rust/src/dns/records_tests.rs @@ -544,6 +544,35 @@ fn merged_tlsa_data_falls_back_to_certificate_data_when_a_numeric_field_is_missi assert_eq!(merged_tlsa_data(&tlsa), ""); } +#[test] +fn a_caa_record_without_a_flag_is_non_critical() { + let mut caa = opts(); + caa.tag = Some("issue".to_owned()); + assert_eq!(v3_record("@", "CAA", "letsencrypt.org", &caa).flag, Some(0)); + // An explicit flag wins, and other types never get one. + caa.flag = Some(128); + assert_eq!( + v3_record("@", "CAA", "letsencrypt.org", &caa).flag, + Some(128) + ); + assert_eq!(v3_record("@", "A", "1.2.3.4", &opts()).flag, None); + + // So an omitted --flag matches a stored flag-0 record. + let mut stored = v3_record("@", "CAA", "letsencrypt.org", &{ + let mut o = opts(); + o.flag = Some(0); + o.tag = Some("issue".to_owned()); + o + }); + stored.record_id = Some("r1".to_owned()); + let mut no_flag = opts(); + no_flag.tag = Some("issue".to_owned()); + assert!(same_content( + &stored, + &v3_record("@", "CAA", "letsencrypt.org", &no_flag) + )); +} + #[test] fn same_content_follows_how_the_api_stores_each_field() { let same = |ty: &str, a: &str, b: &str| { From 0d3d8563268d0b1387b9567ab755076195039fe3 Mon Sep 17 00:00:00 2001 From: Jacob Page Date: Mon, 16 Nov 2026 13:14:33 -0800 Subject: [PATCH 5/5] fix(dns): reject full SRV and TLSA names in dns add and dns set, and check required flags up front For SRV and TLSA records the API composes the DNS name from the record's name and its service and protocol (or port and protocol). Giving `--name` as the full name (`_sip._tcp.chat`) could create a record at a nested name nobody asked for with `dns add`, or move an existing record with `dns set`. Both now reject it before any request and say which `--name` and flags to use. The flags each record type needs are now checked when the arguments are parsed, instead of after login with a 400 from the API: - MX, SRV, HTTPS and SVCB need `--priority`; SRV also needs `--weight`, `--port`, `--service` and `--protocol`; TLSA needs `--port` and `--protocol` in addition to its usage, selector and matching type. - `--service` and `--protocol` take the plain name (`sip`, `tcp`); the leading underscore DNS requires is added when it is left off, and a value that cannot be a label is rejected with an example. - Where they are shown (`--fields service,protocol`, or JSON) they appear in the underscore form, since that is the DNS name. The DNS guide describes the required flags per record type. Co-Authored-By: Claude Sonnet 5.5 --- rust/src/dns/add.rs | 6 +- rust/src/dns/guides/dns.md | 30 +++- rust/src/dns/records.rs | 121 +++++++++++++-- rust/src/dns/records_tests.rs | 281 +++++++++++++++++++++++++++++++++- rust/src/dns/set/mod.rs | 4 +- 5 files changed, 422 insertions(+), 20 deletions(-) diff --git a/rust/src/dns/add.rs b/rust/src/dns/add.rs index f2e92be9..7bb8f09e 100644 --- a/rust/src/dns/add.rs +++ b/rust/src/dns/add.rs @@ -9,8 +9,8 @@ use crate::scopes::DOMAINS_DNS_UPDATE; use super::conflicts::{WriteErrorContext, describe_write_error}; use super::records::{ - RecordOptions, RecordWriteArgs, v3_records, validate_caa_fields, validate_svcb_fields, - validate_tlsa_fields, verified_result, + RecordOptions, RecordWriteArgs, v3_records, validate_caa_fields, validate_record_name, + validate_svcb_fields, validate_tlsa_fields, verified_result, }; // `dns add` creates one v3 record per `--data` value; it reports each outcome @@ -125,6 +125,8 @@ pub(super) fn command() -> RuntimeCommandSpec { let record_type = args.record_type; let name = args.name; let domain_format = args.domain_format.form(&ctx)?; + validate_record_name(&record_type, &name) + .map_err(crate::error::GddyError::validation)?; validate_caa_fields(&record_type, &opts) .map_err(crate::error::GddyError::validation)?; validate_tlsa_fields(&record_type, &opts) diff --git a/rust/src/dns/guides/dns.md b/rust/src/dns/guides/dns.md index 479f835b..71735c84 100644 --- a/rust/src/dns/guides/dns.md +++ b/rust/src/dns/guides/dns.md @@ -53,6 +53,8 @@ gddy dns set example.com --type TXT --name @ --data "v=spf1 -all" --dry-run The dry-run preview lists the planned action per record so you can confirm it before it runs for real. +For `SRV` and `TLSA` records, give `add` and `set` the record's own name and the service and protocol (or port and protocol) as separate flags, e.g. `--name chat --service sip --protocol tcp`. + ## Deleting records `delete` removes every record matching a type+name pair: @@ -71,10 +73,28 @@ Domain names and record names can be typed either as Unicode (`münchen.de`) or ## Type-specific flags -Most of these only apply to certain record types — set them only when the type calls for it: +Some record types need extra flags: -| Flag | Applies to | Notes | +| Record type | Required flags | Optional | |---|---|---| -| `--priority` | `MX`, `SRV` | | -| `--port`, `--weight`, `--protocol`, `--service` | `SRV` | | -| `--flag`, `--tag` | `CAA` | `--tag` is required for CAA (e.g. `issue`, `issuewild`, `iodef`); `--data` carries the CA domain/value | +| `MX` | `--priority` | | +| `SRV` | `--priority`, `--weight`, `--port`, `--service`, `--protocol` | | +| `HTTPS`, `SVCB` | `--priority` (`0` means AliasMode) | `--parameters` | +| `TLSA` | `--usage`, `--selector`, `--matching-type`, `--port`, `--protocol` | | +| `CAA` | `--tag` (`issue`, `issuewild` or `iodef`); `--data` carries the CA domain or value | `--flag` (defaults to `0`) | + +`--service` and `--protocol` take the plain name, e.g. `--service sip --protocol tcp`. GoDaddy stores them with a leading underscore (`_sip._tcp`), which `gddy` adds for you; `--service _sip` works too. Any name made of letters, digits, `-` and `_` (up to 62 characters before the underscore) is accepted, so custom services work. Where they are shown (`--fields service,protocol`, or JSON), they appear in the underscore form, since that is the DNS name. + +Example SRV record: + +``` +gddy dns add example.com \ + --type SRV \ + --name chat \ + --data chat-server.example.com. \ + --priority 10 \ + --weight 5 \ + --port 5222 \ + --service xmpp \ + --protocol tcp +``` diff --git a/rust/src/dns/records.rs b/rust/src/dns/records.rs index 1a5abb46..81d575b8 100644 --- a/rust/src/dns/records.rs +++ b/rust/src/dns/records.rs @@ -73,6 +73,35 @@ pub(super) fn parse_list_type_arg(raw: &str) -> Result { } } +/// clap value-parser for `--service` and `--protocol` (SRV and TLSA). DNS and the +/// API both require these labels to start with an underscore (`_sip`, `_tcp`), so +/// the underscore says nothing the customer could have meant otherwise: `sip` and +/// `_sip` are accepted alike and the underscore is added when it is missing. The +/// result is checked the way the API checks it — letters, digits, `-` or `_` after +/// the underscore, at most 63 characters in all (a DNS label) — and nothing more; +/// any such name is accepted, so there is no list of known services. A bad value +/// would otherwise cost a login and a 400, so catch it here with an example. +pub(super) fn parse_underscore_label(raw: &str) -> Result { + let label = if raw.starts_with('_') { + raw.to_owned() + } else { + format!("_{raw}") + }; + let valid = label.len() > 1 + && label.len() <= 63 + && label[1..] + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'); + if valid { + Ok(label) + } else { + Err(format!( + "{raw:?} must be letters, digits, `-` or `_`, up to 62 characters (for example \ + `sip` or `tcp`)" + )) + } +} + /// Optional record fields shared by `add` and `set`, including the CAA-only /// `flag`/`tag`, the TLSA-only `usage`/`selector`/`matching_type`, and the /// HTTPS/SVCB-only `parameters` (SvcParams). @@ -116,6 +145,14 @@ impl RecordOptions { /// table by hand. Keep in sync with the attributes below. #[cfg_attr(not(feature = "dev-portal-spec"), allow(dead_code))] pub(crate) const CONDITIONALLY_REQUIRED_FLAGS: &[(&str, &str)] = &[ + ( + "priority", + "required when --type is MX, SRV, HTTPS, or SVCB", + ), + ("weight", "required when --type is SRV"), + ("port", "required when --type is SRV or TLSA"), + ("service", "required when --type is SRV"), + ("protocol", "required when --type is SRV or TLSA"), ("tag", "required when --type is CAA"), ("usage", "required when --type is TLSA"), ("selector", "required when --type is TLSA"), @@ -157,25 +194,57 @@ pub(super) struct RecordWriteArgs { #[arg(long, value_name = "SECONDS", value_parser = clap::value_parser!(i64).range(MIN_TTL..=MAX_TTL))] pub(super) ttl: Option, - /// Record priority (MX, SRV, HTTPS, and SVCB only). For HTTPS/SVCB, 0 - /// means AliasMode. - #[arg(long, value_name = "N", value_parser = clap::value_parser!(i64).range(0..=65535))] + /// Record priority (MX, SRV, HTTPS, and SVCB only; required for those). For + /// HTTPS/SVCB, 0 means AliasMode. + #[arg( + long, + value_name = "N", + value_parser = clap::value_parser!(i64).range(0..=65535), + required_if_eq_any([ + ("record_type", "MX"), + ("record_type", "SRV"), + ("record_type", "HTTPS"), + ("record_type", "SVCB"), + ]) + )] pub(super) priority: Option, - /// Service port (SRV and TLSA only). - #[arg(long, value_name = "PORT", value_parser = clap::value_parser!(i64).range(1..=65535))] + /// Service port (SRV and TLSA only; required for those). + #[arg( + long, + value_name = "PORT", + value_parser = clap::value_parser!(i64).range(1..=65535), + required_if_eq_any([("record_type", "SRV"), ("record_type", "TLSA")]) + )] pub(super) port: Option, - /// Record weight (SRV only). - #[arg(long, value_name = "N", value_parser = clap::value_parser!(i64).range(0..=65535))] + /// Record weight (SRV only; required for SRV). + #[arg( + long, + value_name = "N", + value_parser = clap::value_parser!(i64).range(0..=65535), + required_if_eq("record_type", "SRV") + )] pub(super) weight: Option, - /// Service protocol, e.g. _tcp (SRV and TLSA only). - #[arg(long, value_name = "PROTO")] + /// Service protocol, e.g. tcp or udp (SRV and TLSA only; required for those). + /// A leading underscore is added if you leave it off. + #[arg( + long, + value_name = "PROTO", + value_parser = parse_underscore_label, + required_if_eq_any([("record_type", "SRV"), ("record_type", "TLSA")]) + )] pub(super) protocol: Option, - /// Service type (SRV only). - #[arg(long, value_name = "SERVICE")] + /// Service name, e.g. sip or xmpp (SRV only; required for SRV). A leading + /// underscore is added if you leave it off. + #[arg( + long, + value_name = "SERVICE", + value_parser = parse_underscore_label, + required_if_eq("record_type", "SRV") + )] pub(super) service: Option, /// CAA flag byte, 0-255 (CAA only; 0 non-critical, 128 critical). Defaults to 0. @@ -232,6 +301,36 @@ pub(super) fn validate_caa_fields(record_type: &str, opts: &RecordOptions) -> Re Ok(()) } +/// `dns add` and `dns set` write the record under the `--name` they are given, so +/// for SRV and TLSA that must be the record's own name, not the full DNS name the +/// API also understands as a selector (`_sip._tcp.chat`, `_443._tcp.www`). Written +/// under the full name, a record whose prefix differs from its service and +/// protocol lands at a nested name nobody asked for (and `set` would move an +/// existing record there). Reject it up front and say what to type. Pure so it is +/// unit-testable and runs before any network call. +pub(super) fn validate_record_name(record_type: &str, name: &str) -> Result<(), String> { + if !COMPOSITE_NAME_TYPES.contains(&record_type) { + return Ok(()); + } + let mut labels = name.splitn(3, '.'); + let (Some(first), Some(second)) = (labels.next(), labels.next()) else { + return Ok(()); + }; + if !(first.starts_with('_') && second.starts_with('_')) { + return Ok(()); + } + let own_name = labels.next().unwrap_or("@"); + let flags = if record_type == "SRV" { + "--service/--protocol" + } else { + "--port/--protocol" + }; + Err(format!( + "use the record's own name, not the full DNS name: for {record_type} write \ + `--name {own_name}` and give {flags} ({first}.{second} here) separately" + )) +} + /// Validate the TLSA-specific fields against the record type. `--usage`/ /// `--selector`/`--matching-type` being present when `record_type` is TLSA is /// enforced by clap (`required_if_eq`, which covers a lower-case `--type` only diff --git a/rust/src/dns/records_tests.rs b/rust/src/dns/records_tests.rs index 4a77c712..d2bb2ab2 100644 --- a/rust/src/dns/records_tests.rs +++ b/rust/src/dns/records_tests.rs @@ -265,7 +265,7 @@ async fn fetch_records_keeps_server_side_filtering_everywhere_else() { assert_eq!(found.len(), 1, "no name given, nothing to filter out"); } -#[derive(clap::Parser)] +#[derive(Debug, clap::Parser)] struct WriteCli { #[command(flatten)] args: RecordWriteArgs, @@ -418,6 +418,285 @@ fn v3_record_carries_srv_and_caa_fields() { assert_eq!(caa.tag.as_deref(), Some("issue")); } +/// Every flag the API requires for a type, as `(type, flags, a complete set of +/// argv for it)`. The API answers a missing one with a 400 after login; these +/// must be caught when the arguments are parsed. +const REQUIRED_FLAGS_BY_TYPE: &[(&str, &[&str], &[&str])] = &[ + ("MX", &["--priority"], &["--priority", "10"]), + ( + "SRV", + &[ + "--priority", + "--weight", + "--port", + "--service", + "--protocol", + ], + &[ + "--priority", + "1", + "--weight", + "1", + "--port", + "80", + "--service", + "_sip", + "--protocol", + "_tcp", + ], + ), + ("HTTPS", &["--priority"], &["--priority", "1"]), + ("SVCB", &["--priority"], &["--priority", "1"]), + ( + "TLSA", + &[ + "--usage", + "--selector", + "--matching-type", + "--port", + "--protocol", + ], + &[ + "--usage", + "3", + "--selector", + "1", + "--matching-type", + "1", + "--port", + "443", + "--protocol", + "_tcp", + ], + ), + ("CAA", &["--tag"], &["--tag", "issue"]), +]; + +fn parse_type(record_type: &str, extra: &[&str]) -> Result { + use clap::Parser; + let mut argv = vec![ + "t", + "example.com", + "--type", + record_type, + "--name", + "n", + "--data", + "x", + ]; + argv.extend_from_slice(extra); + WriteCli::try_parse_from(argv) +} + +/// Drop `flag` and its value from a complete argv. +fn without(flag: &str, argv: &[&str]) -> Vec { + let mut out = Vec::new(); + let mut skip = false; + for (i, arg) in argv.iter().enumerate() { + if skip { + skip = false; + } else if *arg == flag { + skip = i + 1 < argv.len(); + } else { + out.push((*arg).to_owned()); + } + } + out +} + +#[test] +fn each_type_accepts_its_complete_set_of_flags() { + for (record_type, _, complete) in REQUIRED_FLAGS_BY_TYPE { + parse_type(record_type, complete).expect(record_type); + } +} + +#[test] +fn each_required_flag_is_reported_by_name_when_missing() { + for (record_type, required, complete) in REQUIRED_FLAGS_BY_TYPE { + for flag in *required { + let argv = without(flag, complete); + let refs: Vec<&str> = argv.iter().map(String::as_str).collect(); + let err = parse_type(record_type, &refs) + .expect_err(&format!("{record_type} without {flag} should not parse")); + let text = err.to_string(); + assert!(text.contains(flag), "{record_type} without {flag}: {text}"); + } + } +} + +#[test] +fn the_lower_case_type_requires_the_same_flags() { + // `ignore_case` on --type is what makes the conditions match `--type srv`. + let err = parse_type("srv", &["--priority", "1"]).expect_err("srv needs more"); + assert!(err.to_string().contains("--weight"), "{err}"); + let err = parse_type( + "tlsa", + &["--usage", "3", "--selector", "1", "--matching-type", "1"], + ) + .expect_err("tlsa needs port and protocol"); + assert!(err.to_string().contains("--port"), "{err}"); +} + +#[test] +fn types_that_need_none_of_them_still_parse_with_none() { + for record_type in ["A", "AAAA", "CNAME", "TXT"] { + parse_type(record_type, &[]).expect(record_type); + } +} + +#[test] +fn the_documented_requirements_match_what_clap_enforces() { + // spec_cmd reads CONDITIONALLY_REQUIRED_FLAGS by hand because clap cannot + // expose required_if_eq; a flag listed there must really be required for the + // types it names, and every flag clap requires must be listed. + let listed: std::collections::BTreeSet<&str> = CONDITIONALLY_REQUIRED_FLAGS + .iter() + .map(|(flag, _)| *flag) + .collect(); + let enforced: std::collections::BTreeSet<&str> = REQUIRED_FLAGS_BY_TYPE + .iter() + .flat_map(|(_, required, _)| required.iter().map(|f| f.trim_start_matches("--"))) + .collect(); + assert_eq!(listed, enforced); +} + +#[test] +fn service_and_protocol_gain_the_underscore_the_api_requires() { + // With or without it, the same label comes out. + for (given, want) in [ + ("sip", "_sip"), + ("_sip", "_sip"), + ("tcp", "_tcp"), + ("_tcp", "_tcp"), + ("x509", "_x509"), + ("a-b", "_a-b"), + ("a_b", "_a_b"), + ("SIP", "_SIP"), + ("_SIP", "_SIP"), + // A deliberate second underscore is the customer's own and is kept. + ("__sip", "__sip"), + ("sip_", "_sip_"), + ] { + assert_eq!( + parse_underscore_label(given).as_deref(), + Ok(want), + "{given}" + ); + } + // 63 characters in all is the longest label the API accepts, underscore + // included: 62 given characters become 63, and 63 given become 64. + let longest = "a".repeat(62); + assert_eq!( + parse_underscore_label(&longest).as_deref(), + Ok(format!("_{longest}").as_str()) + ); + assert!(parse_underscore_label(&format!("{longest}a")).is_err()); + assert!(parse_underscore_label(&format!("_{longest}a")).is_err()); + + for bad in ["", "_", " sip", "_ sip", "sip.x", "_sip.x", "é", "_é"] { + let err = parse_underscore_label(bad).expect_err(bad); + assert!(err.contains("sip") && err.contains("62"), "{bad}: {err}"); + } +} + +#[test] +fn service_and_protocol_are_normalized_when_the_arguments_are_parsed() { + use clap::Parser; + // The other flags SRV requires are always given, so only the value under + // test can make the parse fail. + let parse = |service: &str, protocol: &str| { + WriteCli::try_parse_from([ + "t", + "example.com", + "--type", + "SRV", + "--name", + "chat", + "--data", + "t.example.com.", + "--priority", + "1", + "--weight", + "1", + "--port", + "80", + "--service", + service, + "--protocol", + protocol, + ]) + }; + // Plain and underscored spellings are the same request. + for (service, protocol) in [ + ("sip", "tcp"), + ("_sip", "_tcp"), + ("sip", "_tcp"), + ("_sip", "tcp"), + ] { + let ok = parse(service, protocol).expect("valid"); + assert_eq!( + ok.args.service.as_deref(), + Some("_sip"), + "{service} {protocol}" + ); + assert_eq!( + ok.args.protocol.as_deref(), + Some("_tcp"), + "{service} {protocol}" + ); + } + + // A value that cannot be a label is still caught before any request. + for (flag, service, protocol) in [("--service", "si p", "tcp"), ("--protocol", "sip", "t.cp")] { + let err = parse(service, protocol).expect_err("not a label"); + let text = err.to_string(); + assert!( + text.contains(flag) && text.contains("letters"), + "{flag}: {text}" + ); + } +} + +#[test] +fn the_full_dns_name_is_rejected_for_srv_and_tlsa_and_the_message_says_what_to_use() { + let err = validate_record_name("SRV", "_sip._tcp.chat").expect_err("full name"); + assert!( + err.contains("--name chat") && err.contains("--service/--protocol"), + "{err}" + ); + assert!(err.contains("_sip._tcp"), "{err}"); + + // At the apex the record's own name is `@`. + let err = validate_record_name("SRV", "_sip._tcp").expect_err("apex full name"); + assert!(err.contains("--name @"), "{err}"); + + // A name with dots below the record keeps them. + let err = validate_record_name("SRV", "_sip._tcp.a.b").expect_err("nested"); + assert!(err.contains("--name a.b"), "{err}"); + + let err = validate_record_name("TLSA", "_443._tcp.www").expect_err("tlsa full name"); + assert!( + err.contains("--name www") && err.contains("--port/--protocol"), + "{err}" + ); +} + +#[test] +fn the_records_own_name_and_every_other_type_are_accepted() { + for name in ["chat", "@", "a.b", "_underscored", "_one.two"] { + assert!(validate_record_name("SRV", name).is_ok(), "{name}"); + assert!(validate_record_name("TLSA", name).is_ok(), "{name}"); + } + // Only SRV and TLSA have a composed name; an underscore name is ordinary elsewhere. + for ty in ["A", "TXT", "CNAME", "MX", "CAA"] { + assert!( + validate_record_name(ty, "_dmarc._tcp.example").is_ok(), + "{ty}" + ); + } +} + #[test] fn caa_fields_are_required_for_caa_and_rejected_otherwise() { // CAA without --tag → rejected. diff --git a/rust/src/dns/set/mod.rs b/rust/src/dns/set/mod.rs index 2c2237d2..ce9f1d2a 100644 --- a/rust/src/dns/set/mod.rs +++ b/rust/src/dns/set/mod.rs @@ -10,7 +10,7 @@ use crate::scopes::DOMAINS_DNS_UPDATE; use super::list::build_list_output; use super::records::{ RecordOptions, RecordWriteArgs, fetch_records, v3_records, validate_caa_fields, - validate_svcb_fields, validate_tlsa_fields, + validate_record_name, validate_svcb_fields, validate_tlsa_fields, }; use super::records::{ZONE_AND_NAME, verified_result}; @@ -116,6 +116,8 @@ pub(super) fn command() -> RuntimeCommandSpec { let name = args.write.name; let domain_format = args.write.domain_format.form(&ctx)?; let replace_conflicting = args.replace_conflicting_types; + validate_record_name(&record_type, &name) + .map_err(crate::error::GddyError::validation)?; validate_caa_fields(&record_type, &opts) .map_err(crate::error::GddyError::validation)?; validate_tlsa_fields(&record_type, &opts)