Skip to content
Draft
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
5 changes: 3 additions & 2 deletions deploy/geo-demo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ How it behaves:
- `/geo` (no trailing slash) redirects to `/geo/` with status 307. The `Location` is a path only (`/geo/`, query string
kept), never an absolute URL, so it cannot carry the internal host name.
- The page builds every request URL from the prefix that the server injects into it (`const BASE = "/geo"`), so it
works at any depth. Its single link to the host's own root (`Enterprise plugins`) is written relative to the prefix
depth (`../enterprise-plugins` under `/geo`). With no prefix the page requests the same root paths as before.
works at any depth. Its two links to the marketing site (`Enterprise plugins`, `architecture`) are absolute
`https://redevops.io/...` URLs: the page used to link the host root (`../enterprise-plugins` under `/geo`), which does
not exist on `demo.redevops.app`, so the link 404ed there. With no prefix the page requests the same root paths as before.
- The app sets no cookies. If one is ever added it must use `Path=<prefix>`.
- The data and the zoning results are the same under every prefix; only the paths change.
- Health: the app answers health only at `<prefix>/healthz` when a prefix is set, and only at `/healthz` when it is not.
Expand Down
12 changes: 6 additions & 6 deletions deploy/geo-demo/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,17 +88,17 @@ def configured_base_path() -> str:
return validate_base_path(os.environ.get(ENV_BASE_PATH, ""))


# The page is a template: the two placeholders are filled once per app instance from the validated prefix.
# The page is a template: the one placeholder is filled once per app instance from the validated prefix.
_PAGE_TEMPLATE = (STATIC / "index.html").read_text(encoding="utf-8")
_PLACEHOLDERS = ("__BASE_PATH_JSON__", "__SITE_ROOT__")
_PLACEHOLDERS = ("__BASE_PATH_JSON__",)


def render_page(base_path: str) -> str:
"""The page with its URL prefix filled in. Every URL the page requests is built from `BASE` (the prefix as a
JSON string); the one link that points at the host's root rather than at this app is relative to the prefix
depth (`../` per segment), or the plain root path when there is no prefix."""
site_root = "../" * len(base_path.split("/")[1:]) if base_path else "/"
page = _PAGE_TEMPLATE.replace("__BASE_PATH_JSON__", json.dumps(base_path)).replace("__SITE_ROOT__", site_root)
JSON string). The page's links to the marketing site (Enterprise plugins, architecture) are absolute
`https://redevops.io/...` URLs: this app is served on hosts (demo.redevops.app) whose root does not have those pages,
so a host-relative link 404s there."""
page = _PAGE_TEMPLATE.replace("__BASE_PATH_JSON__", json.dumps(base_path))
assert not any(ph in page for ph in _PLACEHOLDERS)
return page

Expand Down
18 changes: 11 additions & 7 deletions deploy/geo-demo/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@
thead th{color:var(--teal);background:#17171a;position:sticky;top:0}
.scroll{max-height:340px;overflow:auto;border:1px solid var(--line);border-radius:10px}
.pill{display:inline-block;font-size:11px;font-weight:700;padding:2px 7px;border-radius:999px}
.PERMITTED{color:#0f0f12;background:var(--green)}.PROHIBITED{color:#fff;background:var(--red)}.UNKNOWN{color:#0f0f12;background:var(--amber)}
.PERMITTED{color:#0f0f12;background:var(--green)}.PROHIBITED{color:#0f0f12;background:var(--red)}.UNKNOWN{color:#0f0f12;background:var(--amber)}
.slo{font-size:20px;font-weight:800}.ok{color:var(--teal)}.mono{font-family:ui-monospace,monospace;font-size:12px;color:var(--muted)}
.grid2{display:grid;grid-template-columns:1fr;gap:16px}@media(min-width:760px){.grid2{grid-template-columns:1fr 1fr}}
.kv{display:flex;justify-content:space-between;border-bottom:1px solid var(--line);padding:6px 0;font-size:14px}
.badge{display:inline-block;border:1px solid var(--teal);color:var(--teal);border-radius:999px;font-size:12px;padding:2px 10px}
</style></head><body><div class="wrap">
a:focus-visible,.scroll:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.err{color:var(--amber);border:1px solid var(--amber);border-radius:10px;padding:10px 14px;margin:16px 0}
</style></head><body><main class="wrap" id="main">
<h1>Geospatial &middot; Zoning Intelligence</h1>
<p class="sub">Zoning as a Runtime capability: typed spatial evidence, a deterministic geometry engine, and a
fail-safe land-use resolver — over <b>real</b> parcels harvested from official ArcGIS sources.</p>
Expand All @@ -35,8 +38,8 @@ <h2>1 &middot; Nationwide land-use, computed</h2>
wherever the answer needs an ordinance use-table we have not parsed, it returns <b>UNKNOWN</b> and cites the
source — never a fabricated "permitted".</p>
<p id="slo" class="slo"></p>
<div class="scroll"><table id="ev"><thead><tr><th>parcel</th><th>zoning</th><th>jurisdiction</th>
<th>single&#8209;family</th><th>office</th><th>retail</th><th>warehouse</th><th>light&#8209;ind.</th></tr></thead>
<div class="scroll" tabindex="0" role="region" aria-label="Land-use disposition for each harvested parcel"><table id="ev"><caption class="sr">Disposition of each target use for each harvested parcel</caption><thead><tr><th scope="col">parcel</th><th scope="col">zoning</th><th scope="col">jurisdiction</th>
<th scope="col">single&#8209;family</th><th scope="col">office</th><th scope="col">retail</th><th scope="col">warehouse</th><th scope="col">light&#8209;ind.</th></tr></thead>
<tbody></tbody></table></div>
</div>

Expand All @@ -57,7 +60,7 @@ <h2>3 &middot; The cheapest sufficient evidence</h2>

<p class="sub" style="margin-top:26px">Data: parcels harvested by <b>zoning-sources-mcp</b> from official Census/ArcGIS
sources (a cross-country sample of the full sweep). Dispositions computed live by the deterministic-first resolver;
the geometry engine is dependency-free. <a href="__SITE_ROOT__enterprise-plugins">Enterprise plugins</a> &middot;
the geometry engine is dependency-free. <a href="https://redevops.io/enterprise-plugins/">Enterprise plugins</a> &middot;
<a href="https://redevops.io/architecture">architecture</a>.</p>

<script>
Expand Down Expand Up @@ -97,5 +100,6 @@ <h2>3 &middot; The cheapest sufficient evidence</h2>
<div class="kv"><span>centroid</span><span class="mono">${sp.centroid[0]}, ${sp.centroid[1]}</span></div>
<div class="kv"><span>canonical geometry id</span><span class="mono">${sp.geometry_id.slice(0,20)}…</span></div>`;
}
load();
</script></div></body></html>
load().catch(err=>{const d=document.createElement('p');d.className='err';d.setAttribute('role','alert');
d.textContent='The live sample could not be loaded ('+err+'). Reload to try again.';document.getElementById('stat').before(d);});
</script></main></body></html>
45 changes: 38 additions & 7 deletions tests/test_geo_demo_base_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,6 @@ def fetch(target: str, **kw) -> Resp:
if host == "redevops.io":
continue
u = urlsplit(u).path
if u == "/enterprise-plugins": # the one link to the host's root, not to this app
continue
assert u == base or u.startswith(base + "/"), f"outside the prefix: {u}"
r = fetch(u)
assert r.status == 200, (u, r.status)
Expand Down Expand Up @@ -245,7 +243,7 @@ def test_empty_prefix_serves_at_the_root_exactly_as_before():
assert get(app, "/geo/api/summary").status == 404
assert get(app, "/missing").status == 404
# the one link that leaves the app is the same root path it always was
assert 'href="/enterprise-plugins"' in page.text
assert 'href="https://redevops.io/enterprise-plugins/"' in page.text


def test_results_are_identical_under_every_prefix_and_deterministic():
Expand All @@ -270,13 +268,47 @@ def test_page_has_no_remaining_root_relative_url_when_a_prefix_is_set():
assert "__BASE_PATH_JSON__" not in page and "__SITE_ROOT__" not in page
for word in ("/api/summary", "/api/evaluate", "/api/spatial", "/static"):
assert f"'{word}" not in page and f'"{word}' not in page and f"`{word}" not in page
# the site-root link resolves to the host root whatever the prefix depth
href = re.search(r'href="([^"]*enterprise-plugins)"', page).group(1)
assert urlsplit(urljoin(f"http://h{base}/", href)).path == "/enterprise-plugins"
# the Enterprise plugins link is absolute, so it resolves the same whatever host or prefix serves the page
href = re.search(r'href="([^"]*enterprise-plugins[^"]*)"', page).group(1)
assert urljoin(f"http://h{base}/", href) == "https://redevops.io/enterprise-plugins/"
# the template itself holds no root-relative literal at all: everything is built from the injected base
assert scan_root_relative(INDEX_HTML.read_text(encoding="utf-8"), "") == []


def test_no_link_in_the_page_points_at_the_host_root_or_a_relative_path():
"""Regression: `Enterprise plugins` was `../enterprise-plugins` (-> https://demo.redevops.app/enterprise-plugins, a 404).
Every link in the page must be an absolute https URL or an in-page anchor."""
for base in PREFIXES:
page = get(load_module().create_app(base), base + "/").text
hrefs = re.findall(r"""<a\s[^>]*href\s*=\s*["']([^"']*)""", page)
assert hrefs and "https://redevops.io/enterprise-plugins/" in hrefs
assert all(h.startswith(("https://", "#")) for h in hrefs), hrefs


def test_page_has_a_main_landmark_a_labelled_focusable_scroll_region_and_aa_pill_colours():
page = INDEX_HTML.read_text(encoding="utf-8")
assert len(re.findall(r"<main\b", page)) == 1 and "</main>" in page
region = re.search(r'<div class="scroll"[^>]*>', page).group(0)
assert 'tabindex="0"' in region and 'role="region"' in region and "aria-label" in region
css = dict(re.findall(r"--([a-z]+):(#[0-9a-fA-F]{6})", page))

def lum(h):
c = [int(h[i:i + 2], 16) / 255 for i in (1, 3, 5)]
c = [x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4 for x in c]
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]

def ratio(a, b):
a, b = sorted((lum(a), lum(b)), reverse=True)
return (a + .05) / (b + .05)

for cls, var in (("PERMITTED", "green"), ("PROHIBITED", "red"), ("UNKNOWN", "amber")):
fg = re.search(r"\." + cls + r"\{color:(#[0-9a-fA-F]{6});", page).group(1)
assert ratio(fg, css[var]) >= 4.5, (cls, ratio(fg, css[var]))
for fg in ("muted", "teal", "amber"): # text tokens on the page and card surfaces
for bg in ("bg", "card"):
assert ratio(css[fg], css[bg]) >= 4.5, (fg, bg)


def test_the_scan_detects_what_it_is_meant_to_detect():
for bad in ('<script>fetch("/api/x")</script>', '<img src="/static/a.png">', '<a href="/healthz">', "x{background:url(/a.png)}",
"<script>fetch('/geo2/api/x')</script>", "<script>new EventSource(u)</script>", "<script>location.href=u</script>",
Expand Down Expand Up @@ -315,7 +347,6 @@ def _mutate(old: str, new: str) -> types.ModuleType:
"oauth redirect at the root": ('swagger_ui_oauth2_redirect_url=f"{base}/docs/oauth2-redirect"',
'swagger_ui_oauth2_redirect_url="/docs/oauth2-redirect"'),
"page built for the root": ("json.dumps(base_path)", 'json.dumps("")'),
"site-root link not adjusted": ('"../" * len(base_path.split("/")[1:]) if base_path else "/"', '"/"'),
}


Expand Down
Loading