Skip to content

Commit de21170

Browse files
committed
Manage proxied application DNS and support explicit record adoption
1 parent f6264ef commit de21170

14 files changed

Lines changed: 640 additions & 34 deletions

File tree

‎README.md‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,6 @@ once:
476476
- host: www.bigconfig.online
477477
image: ghcr.io/pocketcontext/pocketcontext-website:latest
478478
github: pocketcontext/pocketcontext-website
479-
manage-dns: true
480479
auto_update: false
481480
deploy-strategy: rolling
482481
smtp: true
@@ -507,8 +506,22 @@ privately in SQLite and transmitted to the host via SSH stdin.
507506
The first implementation supports one Cloudflare zone and one sending domain per
508507
deployment. Existing unowned DNS records, Resend domains and GitHub environments
509508
require explicit recovery/ownership resolution; matching names never authorize
510-
adoption. Website records are DNS-only to allow origin TLS verification. Domain
511-
verification has its own DAG stage. For a domain that is not yet verified, it
509+
adoption. With Cloudflare enabled, every application host defaults to a managed
510+
proxied A record (Auto TTL, `1`); explicit `manage-dns: false` excludes a host.
511+
The A record targets the deployment's verified public IPv4. SMTP records remain
512+
DNS-only with TTL `300`. With `provider-dns: no-infra`, application DNS remains
513+
externally managed; an explicit `manage-dns: true` requires Cloudflare.
514+
515+
After applications are ready, HTTPS verification connects to the recorded origin
516+
IP while retaining the application hostname for SNI and certificate validation.
517+
It then checks public HTTPS through Cloudflare with a unique query and
518+
`Cache-Control: no-cache, no-store`. Both checks require a successful response;
519+
origin redirects stay on the same HTTPS hostname. Configure health endpoints to
520+
bypass custom cache rules. PocketDeploy does not change zone-wide TLS settings,
521+
WAF rules or cache rules; preserve Full (strict) for the origin connection.
522+
GitHub applications with externally managed DNS also receive both checks.
523+
524+
Domain verification has its own DAG stage. For a domain that is not yet verified, it
512525
triggers verification once, then polls the recorded domain every ten seconds
513526
until verified. Already verified domains skip the trigger and polling. Convergence continues
514527
automatically without repeating compute, host setup or DNS reconciliation.
@@ -675,3 +688,34 @@ local token expiry before invoking OCI. An expired token fails with a safe
675688
renewal instruction instead of waiting for a provider request. This local check
676689
does not prove a token is otherwise valid; OCI may still reject revoked or
677690
invalid credentials. `init` and Vault workflows do not require OCI credentials.
691+
692+
### Explicit DNS ownership transfer
693+
694+
`adopt-dns` transfers one existing application A record to this deployment.
695+
Configure Cloudflare and the managed application first. Disable and drain the
696+
previous DNS manager, checkpoint its state, and obtain the exact zone ID, record
697+
ID and current IPv4. The address must match this deployment's recorded owned
698+
compute. Multiple A records or AAAA/CNAME conflicts are refused.
699+
700+
Use `pocketdeploy dns-evidence --dns-host app.example.com --json` to obtain
701+
the allowlisted current record evidence without changing state or providers.
702+
703+
The `--dns-settings-sha256` fingerprint is computed from the current record's allowlisted fields
704+
`type`, `name`, `content`, `proxied`, `ttl`, and `comment` (missing comment is null):
705+
SHA-256 of UTF-8 JSON with sorted keys and separators `(',', ':')`. Filter provider
706+
responses inside the inspecting process; never print raw provider metadata.
707+
708+
```sh
709+
pocketdeploy adopt-dns --dns-host app.example.com \
710+
--dns-zone-id EXACT_ZONE_ID --dns-record-id EXACT_RECORD_ID \
711+
--dns-ipv4 CURRENT_OWNED_IPV4 --dns-settings-sha256 EXACT_FINGERPRINT \
712+
--previous-dns-manager-disabled
713+
```
714+
715+
The command journals exact evidence before changing only the record's ownership
716+
comment. It preserves record identity, address, proxy setting and TTL. Retry an
717+
interrupted transfer with the original evidence; do not clear its journal or
718+
manually edit SQLite. Ordinary convergence and deletion refuse an incomplete
719+
transfer. After adoption, `plan` and `converge` apply the normal proxied-A policy.
720+
Keep the previous manager disabled and save a new Vault checkpoint before
721+
removing its obsolete local state.

‎scripts/test-launcher.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def main():
4343
# A regression must fail locally before it can invoke deployment tools.
4444
marker = root / 'unexpected-external-command'
4545
guard = f'#!/bin/sh\nprintf blocked > "{marker}"\nexit 99\n'
46-
for command in ('oci', 'ssh', 'scp', 'vaultcontext'):
46+
for command in ('oci', 'ssh', 'scp', 'vaultcontext', 'cf', 'resend', 'gh'):
4747
stub = launcher.parent / command
4848
stub.write_text(guard)
4949
stub.chmod(0o700)
@@ -148,6 +148,13 @@ def invoke(directory, *arguments, expected=None, successful=False):
148148
'--volume', 'data:/storage', '--settings-sha256', 'c' * 64,
149149
'--previous-delivery-disabled', expected=STATE_REQUIRED)
150150
assert not list(application.glob('.colors.sqlite*')), 'Application adoption created identity.'
151+
# An omitted DNS flag stays local with no-infra, and Cloudflare's default
152+
# host selection must still respect the missing-state guard before reads.
153+
invoke(application, 'plan', expected=STATE_REQUIRED)
154+
application_config.write_text(application_config.read_text() +
155+
'\nprovider-dns: cloudflare\ncloudflare-zone-id: ' + 'a' * 32 + '\n')
156+
invoke(application, 'plan', expected=STATE_REQUIRED)
157+
assert not list(application.glob('.colors.sqlite*')), 'DNS defaults created identity.'
151158
application_config.write_text(application_config.read_text().replace('deploy-ready-timeout: 900',
152159
'deploy-ready-timeout: 0'))
153160
invoke(application, 'status', expected='Ready timeout must be between 1 and 3600 seconds.')
@@ -241,7 +248,7 @@ def invoke(directory, *arguments, expected=None, successful=False):
241248
assert token.read_text() not in expired_run.stdout + expired_run.stderr
242249
print(f'Expired synthetic OCI token rejected locally in {elapsed:.2f}s; OCI was not invoked.')
243250

244-
print('Portable launcher: 34 checks passed (no cloud access).')
251+
print('Portable launcher: 36 checks passed (no cloud access).')
245252

246253

247254
if __name__ == '__main__':

‎skills/pocketdeploy/SKILL.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,3 +282,19 @@ ownership failures. Inspect the failing stage and rerun `delete` to reconcile an
282282
resume. Recreation starts with fresh keys and application storage. No automatic
283283
backup or restoration is performed. Successful output lists removed and retained
284284
resources.
285+
286+
## Existing application DNS ownership
287+
288+
Use `adopt-dns` for an exact existing A record after disabling and draining its
289+
previous DNS manager. Read the README's explicit DNS transfer procedure. Obtain safe evidence using
290+
`dns-evidence --dns-host HOST --json`. Supply
291+
`--dns-host`, `--dns-zone-id`, `--dns-record-id`, `--dns-ipv4`,
292+
`--dns-settings-sha256`, and `--previous-dns-manager-disabled`. The IPv4 must match
293+
recorded owned compute. The settings fingerprint covers only type/name/content/
294+
proxied/ttl/comment; filter provider metadata before any output. Adoption changes
295+
only the ownership comment and durably journals before mutation. Retry interrupted
296+
adoption with the original exact evidence; never clear journals or edit SQLite.
297+
Then converge to the default proxied A record and Auto TTL. Cloudflare manages
298+
every configured application host unless explicitly excluded by `manage-dns: false`.
299+
Origin TLS verification preserves hostname/SNI; public checks bypass caches. Save
300+
recovery evidence before retiring the prior manager's private state.

‎skills/pocketdeploy/references/configuration.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,8 +187,16 @@ support and use the selected mode. Fizzy defaults to STARTTLS; implicit TLS
187187
requires its documented `SMTP_TLS=true` environment setting. Certificate checks
188188
stay enabled. A host probe does not verify application mail configuration.
189189

190-
Applications opt into `manage-dns: true`, `smtp: true` and
191-
`github: owner/repository`. GitHub images must belong to that repository on GHCR;
190+
With `provider-dns: cloudflare`, every application host defaults to managed DNS;
191+
`manage-dns: false` explicitly excludes a host. Application A records use proxy
192+
enabled and Auto TTL (`1`), targeting the verified deployment IPv4; SMTP records
193+
remain unproxied with TTL `300`. With `provider-dns: no-infra`, DNS remains
194+
externally managed unless explicitly requested, which fails validation.
195+
Convergence checks direct-origin HTTPS with hostname/SNI certificate validation,
196+
then public HTTPS with a unique query and cache-control headers. Keep health
197+
endpoints outside custom cache rules. Shared zone TLS/WAF/cache settings remain
198+
externally managed; preserve Full (strict). Applications opt into
199+
`smtp: true` and `github: owner/repository`. GitHub images must belong to that repository on GHCR;
192200
one app per repository is supported. The environment equals `profile`, and an
193201
explicit `github-environment` may only repeat that exact profile. TLS must remain
194202
enabled for GitHub and managed website DNS. The profile is durable, not a tool

‎src/pocketdeploy/cli.py‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ def parser():
4242
ssh Open SSH or run --ssh-command; preserve remote output and exit
4343
delete Delete owned resources, subject to destruction protection
4444
smtp-test Send one explicit SMTP test using --to
45+
dns-evidence Inspect safe exact application DNS adoption evidence
46+
adopt-dns Transfer one exact existing application A record
4547
adopt-app Transfer a verified existing application after draining prior delivery
4648
adopt Recover an existing instance with matching deployment UUID tags
4749
rotate-host-key Finish bootstrap host-key migration without application changes
@@ -60,7 +62,7 @@ def parser():
6062
6163
Configuration defaults to colors.yml in the current working directory.
6264
Use -f to select a deployment. Run without arguments to show this help.''')
63-
p.add_argument('command', metavar='COMMAND', choices=['init', 'plan', 'converge', 'status', 'ssh', 'delete', 'adopt', 'adopt-app', 'smtp-test', 'rotate-host-key', 'vault-save', 'vault-restore'], help='Deployment or Vault command listed below')
65+
p.add_argument('command', metavar='COMMAND', choices=['init', 'plan', 'converge', 'status', 'ssh', 'delete', 'adopt', 'adopt-app', 'adopt-dns', 'dns-evidence', 'smtp-test', 'rotate-host-key', 'vault-save', 'vault-restore'], help='Deployment or Vault command listed below')
6466
p.add_argument('-f', '--file', help='Configuration file (default: ./colors.yml in the current working directory)')
6567
p.add_argument('--json', action='store_true', help='Emit one versioned JSON result on stdout')
6668
p.add_argument('--verbose', action='store_true', help='Show safe request timings and waiting progress on stderr')
@@ -73,6 +75,9 @@ def parser():
7375
p.add_argument('--volume', action='append', help='Exact existing named volume and mount destination, NAME:/PATH (repeatable)')
7476
p.add_argument('--settings-sha256', help='Existing ONCE settings fingerprint from status')
7577
p.add_argument('--previous-delivery-disabled', action='store_true', help='Assert previous delivery authority is disabled and drained')
78+
for flag in ('dns-host', 'dns-zone-id', 'dns-record-id', 'dns-ipv4', 'dns-settings-sha256'):
79+
p.add_argument('--' + flag, help='Exact existing DNS evidence for adopt-dns')
80+
p.add_argument('--previous-dns-manager-disabled', action='store_true', help='Assert previous DNS authority is disabled and drained')
7681
p.add_argument('--document', help='Vault state document to restore')
7782
p.add_argument('--version', help='Exact Vault state version to restore')
7883
p.add_argument('--destination', help='Recovery directory containing matching Git configuration')
@@ -190,7 +195,7 @@ def applications(opts):
190195
def verify(opts):
191196
results['status'] = host.status(results['connection'])
192197
from .health import verify as verify_https
193-
verify_https(config)
198+
verify_https(config, results['connection'])
194199
return dict(opts)
195200

196201
steps = {'preflight': [preflight, 'keys'], 'keys': [keys, 'compute'], 'compute': [compute, 'host'],
@@ -240,6 +245,23 @@ def execute(args, reporter=None):
240245

241246
def _execute(args, reporter=None):
242247
reporter = reporter or Reporter(quiet=getattr(args, "quiet", False), command=args.command)
248+
dns_options = ('dns_host', 'dns_zone_id', 'dns_record_id', 'dns_ipv4', 'dns_settings_sha256', 'previous_dns_manager_disabled')
249+
if args.command == 'dns-evidence' and (not getattr(args, 'dns_host', None) or any(getattr(args, key, None) for key in dns_options[1:])):
250+
raise DeployError('dns-evidence requires only --dns-host.', code='invalid_usage')
251+
if args.command not in ('adopt-dns', 'dns-evidence') and any(getattr(args, key, None) for key in dns_options):
252+
raise DeployError('DNS adoption options require adopt-dns.', code='invalid_usage')
253+
if args.command == 'adopt-dns':
254+
import re
255+
import ipaddress
256+
try:
257+
valid_ip = bool(ipaddress.IPv4Address(args.dns_ipv4))
258+
except (ValueError, TypeError):
259+
valid_ip = False
260+
if (not all(getattr(args, key, None) for key in dns_options) or not valid_ip
261+
or not re.fullmatch(r'[0-9a-f]{32}', args.dns_zone_id or '')
262+
or not re.fullmatch(r'[0-9a-f]{32}', args.dns_record_id or '')
263+
or not re.fullmatch(r'[0-9a-f]{64}', args.dns_settings_sha256 or '')):
264+
raise DeployError('adopt-dns requires exact host, zone/record IDs, IPv4, settings fingerprint and disabled previous DNS manager.', code='invalid_usage')
243265
adoption_options = ('app_host', 'container_id', 'image_id', 'volume', 'settings_sha256', 'previous_delivery_disabled')
244266
if args.command != 'adopt-app' and any(getattr(args, key, None) for key in adoption_options):
245267
raise DeployError('Application adoption options require adopt-app.', code='invalid_usage')
@@ -269,7 +291,7 @@ def _execute(args, reporter=None):
269291
if smtp_timeout is not None and (args.command != 'converge' or args.dry_run
270292
or not 0 <= smtp_timeout <= 3600):
271293
raise DeployError('--smtp-verification-timeout requires converge without --dry-run and 0–3600 seconds.', code='invalid_usage')
272-
read_only = args.command in ('plan', 'status') or args.dry_run
294+
read_only = args.command in ('plan', 'status', 'dns-evidence') or args.dry_run
273295
config_file = args.file if args.file is not None else 'colors.yml'
274296
if args.file is None and not Path(config_file).exists():
275297
raise DeployError('No colors.yml found in the current directory; use -f to select a configuration.')
@@ -306,6 +328,9 @@ def _execute(args, reporter=None):
306328
cloud_type = OCI if config['provider-compute'] == 'oci' else provider_class(config['provider-compute'])
307329
cloud = cloud_type(config, state)
308330
if read_only:
331+
if args.command == 'dns-evidence':
332+
from .dns_adoption import inspect
333+
return inspect(config, state, cloud.connection(), args.dns_host)
309334
if args.command == 'status':
310335
observed = cloud.inspect()
311336
result = {'profile': config['profile'], 'state': state.safe_status(), 'resources': observed}
@@ -364,6 +389,12 @@ def _execute(args, reporter=None):
364389
if config.get('provider-smtp') != 'resend':
365390
raise DeployError('smtp-test requires provider-smtp: resend.')
366391
result = host.smtp_test(cloud.connection(), Services(config, state).smtp_settings(), args.to)
392+
elif args.command == 'adopt-dns':
393+
from .dns_adoption import adopt
394+
result = adopt(config, state, cloud.connection(), operation, {
395+
'host': args.dns_host, 'zone': args.dns_zone_id, 'record_id': args.dns_record_id,
396+
'ipv4': args.dns_ipv4, 'settings_sha256': args.dns_settings_sha256,
397+
'previous_dns_manager_disabled': True})
367398
elif args.command == 'adopt-app':
368399
recorded = state.get_resource('compute')
369400
if not recorded or not recorded['owned']:

‎src/pocketdeploy/config.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@
1111
from .common import DeployError, local_path
1212
from .smtp import smtp_transport
1313

14+
def manages_dns(config, app):
15+
"""Cloudflare manages declared application hosts unless explicitly excluded."""
16+
return app.get('manage-dns', config.get('provider-dns') == 'cloudflare')
17+
18+
1419
DEFAULTS = {
1520
'schema-version': 1, 'provider-compute': 'oci', 'workdir': '.colors',
1621
'state-file': '.colors.sqlite', 'oci-auth': 'security_token',
@@ -203,7 +208,7 @@ def validate(c):
203208
raise DeployError('Application smtp and manage-dns flags must be booleans.')
204209
if app.get('smtp') and c['provider-smtp'] != 'resend':
205210
raise DeployError('smtp: true requires provider-smtp: resend.')
206-
if app.get('manage-dns') and app.get('disable_tls'):
211+
if manages_dns(c, app) and app.get('disable_tls'):
207212
raise DeployError('Managed website DNS requires TLS enabled.')
208213
if app.get('manage-dns') and c['provider-dns'] != 'cloudflare':
209214
raise DeployError('manage-dns: true requires provider-dns: cloudflare.')

0 commit comments

Comments
 (0)