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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,35 @@ carries `HOSTSHIFT_ARGS=--slug wt-a` and nothing more: the file is mounted into
the container and the proxy reads it directly, which it must, since a flat
canonical=variant list cannot carry aliases.

**Hostnames on the page that the map does not name.** `check` counts every
absolute-URL host in the pages it probes. A host with five or more references
that sits at or under a canonical's apex (the canonical minus one leading
`www.`) is either an alias the file forgot, which would leave live production
links in a preview, or a separate application on the client's domain: a login
app, a docs site. `check` asks the host which one it is, with one bounded
request each way (5 s, at most two same-host redirect hops, never followed off
the host). It is **this site** if its root redirects to a hostname the map
names, or if its `/wp-json/` index reports a `home` or `url` the map names.
Then `check` refuses and tells you to add it as an alias. Anything else (another
app, another WordPress, no answer) is treated as external: `check` prints a
note saying so, or that it could not reach the host, and carries on.

To skip that request and the note, list the host under the site's `external:`.
Its links are left alone either way; `external:` only makes that explicit and
offline. A host can't be both an alias and external, and the file is refused if
it is listed as both:

```yaml
- name: main
canonical: https://www.example.com
base: https://acme.ddev.site
external: [identity.example.com, docs.example.com]
```

`hostshift map --external-hosts` prints the list. The proxy reads this file
too, and a CLI or proxy image released before this key rejects it as an unknown
field. Add `external:` only once both are on a release that has it.

### Production-canonical — only for a pristine dump

The same engine pointed further: set `canonical` to the live production
Expand Down
10 changes: 10 additions & 0 deletions cmd/hostshift/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,8 @@ func cmdMap(args []string) (int, error) {
canon := fs.Bool("canonical-hosts", false, "emit every canonical-side hostname, aliases included, one per line")
ext := fs.Bool("external-canonical-hosts", false,
"emit the canonical hostnames that are not this project's own, one per line")
external := fs.Bool("external-hosts", false,
"emit the hostnames hostshift.yaml declares `external:`, one per line")
if describe(fs, args, "print the resolved map, and where it came from") {
return exitOK, nil
}
Expand Down Expand Up @@ -709,6 +711,14 @@ func cmdMap(args []string) (int, error) {
}
return exitOK, nil
}
// Hosts under the site's domain that are someone else's application. The
// add-on's `check` skips them instead of probing whether they are this site.
if *external {
for _, h := range res.External {
fmt.Println(h)
}
return exitOK, nil
}
if *pairs || *hosts {
for _, s := range res.Map.Sites {
if *pairs {
Expand Down
128 changes: 117 additions & 11 deletions ddev/commands/host/hostshift
Original file line number Diff line number Diff line change
Expand Up @@ -2702,10 +2702,87 @@ $extra_body"
others="$(printf '%s' "$probe_body" | hostshift origins 2>/dev/null || true)"
known_hosts=",$(printf '%s,%s,%s,' "$canon_list" "$variants" "${DDEV_HOSTNAME:-}" \
| tr -s ',' ','),"
# What hostshift.yaml says outright. `external:` hosts are someone else's
# application and are skipped without a probe or a note. The file's whole
# canonical side — aliases included, which a `--holds` flat map leaves out
# of $canon_list — is what a probe below may find a host redirecting to.
# From the file itself, not "${map_args[@]}": under --holds those are
# --from/--to, which carry neither. An older CLI without --external-hosts
# prints nothing here, and every related host is then probed as before.
external_hosts=","
site_hosts="$known_hosts"
if [ -f hostshift.yaml ]; then
external_hosts=",$(hostshift map --slug "$slug" --external-hosts 2>/dev/null \
| paste -sd, - || true),"
site_hosts="$site_hosts$(hostshift map --slug "$slug" --canonical-hosts 2>/dev/null \
| paste -sd, - || true),"
fi

# hs_probe_related asks a related host whether it is this WordPress, with
# one cheap look each way: does its root redirect to a hostname this map
# names, and does its /wp-json/ index report a home or url this map names.
# Sets hs_verdict to "site" (with hs_evidence), "unreachable" or "external".
#
# This is an outbound request to the live host, from this machine — the
# thing hs_fetch_local refuses to do by following redirects. It is bounded
# instead: two requests plus at most two same-host redirect hops, 5 s each,
# GETs only, and never followed onto another host. The redirect target is
# read from curl's `redirect_url`, not fetched.
#
# Why ask at all: a host under the canonical's apex is not necessarily this
# site. A customer login app, a docs site or an auction app on another
# server is the ordinary case, and the alias remedy below is actively wrong
# for it — it rewrites the links to that app onto the local site.
hs_probe_related() {
hs_verdict="external"; hs_evidence=""
_purl="https://$1/"; _phop=0
while :; do
_rc=0
_pout="$(curl -sk --noproxy '*' --connect-timeout 3 --max-time 5 \
-o /dev/null -w '%{http_code} %{redirect_url}' "$_purl" 2>/dev/null)" || _rc=$?
_pout="$(printf '%s\n' "$_pout" | sed -n '$p')"
_pcode="${_pout%% *}"
_ploc=""
case "$_pout" in *" "*) _ploc="${_pout#* }" ;; esac
if [ "$_rc" != 0 ] || [ "$_pcode" = 000 ] || [ -z "$_pcode" ]; then
# The root, not a later hop: a host that answered once is reachable.
if [ "$_phop" = 0 ]; then hs_verdict="unreachable"; return 0; fi
break
fi
case "$_pcode" in 30*) ;; *) break ;; esac
[ -n "$_ploc" ] || break
_plh="${_ploc#*://}"; _plh="${_plh%%/*}"; _plh="${_plh%%:*}"
case "$site_hosts" in
*",$_plh,"*)
hs_verdict="site"
hs_evidence="https://$1/ redirects to $_ploc"
return 0 ;;
esac
# Same host, another path (`/` to `/en/`): follow, a little.
[ "$_plh" = "$1" ] && [ "$_phop" -lt 2 ] || break
_phop=$((_phop + 1))
_purl="$_ploc"
done
_pjson="$(curl -sk --noproxy '*' --connect-timeout 3 --max-time 5 \
"https://$1/wp-json/" 2>/dev/null || true)"
for _pv in $(printf '%s' "$_pjson" \
| grep -oE '"(home|url)"[[:space:]]*:[[:space:]]*"[^"]*"' 2>/dev/null \
| sed -e 's/^[^:]*:[[:space:]]*"//' -e 's/"$//' -e 's|\\/|/|g' || true); do
_pvh="${_pv#*://}"; _pvh="${_pvh%%/*}"; _pvh="${_pvh%%:*}"
case "$site_hosts" in
*",$_pvh,"*)
hs_verdict="site"
hs_evidence="https://$1/wp-json/ is a WordPress whose home is $_pv"
return 0 ;;
esac
done
}

while read -r cnt host; do
[ -n "${host:-}" ] || continue
[ "${cnt:-0}" -ge 5 ] 2>/dev/null || continue
case "$known_hosts" in *",$host,"*) continue ;; esac
case "$external_hosts" in *",$host,"*) continue ;; esac
case "$host" in
localhost|*.localhost|*.test|127.*|*.ddev.site) continue ;;
esac
Expand Down Expand Up @@ -2739,18 +2816,47 @@ $extra_body"
[ "$host" = "$apex" ] && related=1 && break
case "$host" in *".$apex") related=1; break ;; esac
done
# Related is not the same as this site, so ask the host before refusing.
# Only evidence that it *is* this WordPress keeps the refusal; anything
# else — another app, another WordPress, no answer — is a note. Refusing
# on a separate app blocked every unattended `init` after a db pull, and
# its remedy proxied that app's links onto the local site.
if [ -n "$related" ]; then
echo "hostshift: refusing to call this healthy — $cnt reference(s) to" >&2
echo " $host across the pages probed, first seen on" >&2
echo " $(hs_page_carrying "$host")," >&2
echo " which this map does not name and which is at or under the same" >&2
echo " site as a hostname it does ($apex). They are not rewritten, so" >&2
echo " they are live production links in a preview." >&2
echo " Counted across:" >&2
for pu in ${probe_urls:-}; do echo " $pu" >&2; done
echo " Add $host to hostshift.yaml — as an alias of the canonical it" >&2
echo " belongs to — and \`ddev hostshift init && ddev restart\`." >&2
exit 2
hs_probe_related "$host"
if [ "$hs_verdict" = site ]; then
echo "hostshift: refusing to call this healthy — $cnt reference(s) to" >&2
echo " $host across the pages probed, first seen on" >&2
echo " $(hs_page_carrying "$host")," >&2
echo " which this map does not name and which is at or under the same" >&2
echo " site as a hostname it does ($apex). They are not rewritten, so" >&2
echo " they are live production links in a preview." >&2
echo " It is this site: $hs_evidence." >&2
echo " Counted across:" >&2
for pu in ${probe_urls:-}; do echo " $pu" >&2; done
echo " Add $host to hostshift.yaml — as an alias of the canonical it" >&2
echo " belongs to — and \`ddev hostshift init && ddev restart\`." >&2
case "$hs_evidence" in
*" redirects to "*)
echo " If it is a separate application that only redirects here," >&2
echo " list it under the site's \`external:\` instead." >&2 ;;
esac
exit 2
fi
if [ "$hs_verdict" = unreachable ]; then
why="could not reach it; treated as external"
else
why="it neither redirects to this site nor serves this WordPress's"
why="$why /wp-json/, so it is treated as external"
fi
echo "hostshift: note: $cnt reference(s) to $host across the pages" >&2
echo " probed, first seen on $(hs_page_carrying "$host")." >&2
echo " It is under the same site as $apex and this map does not name it," >&2
echo " so it was checked: $why — its links" >&2
echo " are left alone. If it is in fact this site, add it to" >&2
echo " hostshift.yaml as an alias of the canonical it belongs to and" >&2
echo " \`ddev hostshift init && ddev restart\`. If it is another" >&2
echo " application, list it under the site's \`external:\` to skip this." >&2
continue
fi
echo "hostshift: note: $(hs_page_carrying "$host")" >&2
echo " carries $cnt reference(s) to $host, which this map does not name" >&2
Expand Down
69 changes: 63 additions & 6 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ type SiteFile struct {
Base string `yaml:"base"`
Aliases []string `yaml:"aliases"`
Variant string `yaml:"variant"` // explicit override for the rare case
// External names hostnames under this site's domain that are *not* this
// WordPress — a login app, a docs site — so `ddev hostshift check` neither
// probes them nor asks for them to be aliased. Nothing is rewritten for them.
External []string `yaml:"external"`
}

// Flags are the CLI overrides. They win over every file (PLAN §5.3).
Expand Down Expand Up @@ -123,6 +127,10 @@ type Resolved struct {
// neither is.
DirectlyServed []string
ExternalCanonicals []string

// External is every site's `external:` hostnames from hostshift.yaml: hosts
// the file declares are someone else's application, not this WordPress.
External []string
}

// Load resolves the map for a project directory.
Expand Down Expand Up @@ -198,11 +206,12 @@ func resolve(dir string, f Flags) (*Resolved, error) {
}

var (
sites []origin.Site
up = f.Upstream
source string
layer string
pattern = DefaultVariantPattern
sites []origin.Site
up = f.Upstream
source string
layer string
pattern = DefaultVariantPattern
external []string
)

// Layer 1 of §5.3, and the only place the core knows DDEV exists: a project
Expand Down Expand Up @@ -237,6 +246,9 @@ func resolve(dir string, f Flags) (*Resolved, error) {
if sites, err = holdSide(sites, hf, f.Holds); err != nil {
return nil, err
}
if external, err = externalHosts(hf, sites); err != nil {
return nil, err
}
default:
if err := fileLayerOnly("the DDEV config"); err != nil {
return nil, err
Expand Down Expand Up @@ -266,7 +278,7 @@ func resolve(dir string, f Flags) (*Resolved, error) {
return nil, err
}
}
res := &Resolved{Map: m, Upstream: up, Source: source, Layer: layer}
res := &Resolved{Map: m, Upstream: up, Source: source, Layer: layer, External: external}

// A hostshift.yaml *replaces* the DDEV layer rather than merging with it:
// an explicit map is a statement about which hosts this project serves, and
Expand Down Expand Up @@ -509,6 +521,51 @@ func sitesFromFile(f *File, pattern, slug string) ([]origin.Site, error) {
return sites, nil
}

// externalHosts reads every site's `external:` list as hostnames, a bare host
// or a URL whose host is taken. A host the map also names — any site's
// canonical, base, alias or variant — is refused: it cannot be both this
// WordPress and someone else's application, and which one wins would decide
// whether its links are rewritten.
func externalHosts(f *File, sites []origin.Site) ([]string, error) {
named := map[string]string{}
for _, s := range sites {
for _, o := range s.CanonicalSet() {
named[o.Host] = s.Name
}
if s.Variant.Host != "" {
named[s.Variant.Host] = s.Name
}
}
var out []string
for i, s := range f.Sites {
name := sites[i].Name
for _, raw := range s.External {
var (
h string
err error
)
if strings.Contains(raw, "://") {
var o origin.Origin
if o, err = origin.Parse(raw); err == nil {
h = o.Host
}
} else {
h, err = origin.NormaliseHost(strings.TrimSpace(raw))
}
if err != nil || h == "" || strings.ContainsAny(h, "/ ") {
return nil, fmt.Errorf("site %q: external %q is not a hostname", name, raw)
}
if other, ok := named[h]; ok {
return nil, fmt.Errorf("site %q: external %q is also declared as a hostname of site %q — a host is either this site or external, not both", name, raw, other)
}
if !slices.Contains(out, h) {
out = append(out, h)
}
}
}
return out, nil
}

// holdSide makes each site's held origin its canonical (Flags.Holds), and the
// canonical it replaces one of its aliases. sites are sitesFromFile's, in the
// file's order.
Expand Down
74 changes: 74 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -443,3 +443,77 @@ func TestOwnHostnameIsNotReportedUncovered(t *testing.T) {
t.Errorf("Uncovered = %v, want just the undeclared hostname", res.Uncovered)
}
}

// TestExternalHosts: `external:` names hosts under the site's domain that are
// another application. They are hostnames, not part of the map, and a host
// cannot be both external and one the map names.
func TestExternalHosts(t *testing.T) {
dir := t.TempDir()
write(t, dir, "hostshift.yaml", `
sites:
- name: main
canonical: https://www.acme.example
base: https://acme.ddev.site
aliases: [https://acme.example]
external: [identity.acme.example, "https://Docs.acme.example/", identity.acme.example]
`)
res, err := Load(dir, Flags{Slug: "wt-a"})
if err != nil {
t.Fatal(err)
}
if got := strings.Join(res.External, ","); got != "identity.acme.example,docs.acme.example" {
t.Errorf("External = %q, want both hosts, normalised and deduplicated", got)
}
for _, s := range res.Map.Sites {
for _, o := range s.CanonicalSet() {
if strings.HasPrefix(o.Host, "identity.") || strings.HasPrefix(o.Host, "docs.") {
t.Errorf("external host %q leaked into the map", o.Host)
}
}
}

cases := []struct{ name, yaml, want string }{
{
name: "also an alias",
yaml: `
sites:
- {name: a, canonical: https://www.acme.example, base: https://a.ddev.site, aliases: [https://acme.example], external: [acme.example]}`,
want: "either this site or external",
},
{
name: "another site's canonical",
yaml: `
sites:
- {name: a, canonical: https://www.acme.example, base: https://a.ddev.site, external: [shop.acme.example]}
- {name: b, canonical: https://shop.acme.example, base: https://b.ddev.site}`,
want: "either this site or external",
},
{
name: "not a hostname",
yaml: `
sites:
- {name: a, canonical: https://www.acme.example, base: https://a.ddev.site, external: ["identity.acme.example/login"]}`,
want: "is not a hostname",
},
{
name: "misspelled key",
yaml: `
sites:
- {name: a, canonical: https://www.acme.example, base: https://a.ddev.site, externals: [identity.acme.example]}`,
want: "externals",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
dir := t.TempDir()
write(t, dir, "hostshift.yaml", c.yaml)
_, err := Load(dir, Flags{Slug: "wt-a"})
if err == nil {
t.Fatalf("Load accepted a config it must refuse")
}
if !strings.Contains(err.Error(), c.want) {
t.Errorf("error is %q, want it to mention %q", err, c.want)
}
})
}
}
Loading
Loading