diff --git a/cmd/smoke/check.go b/cmd/smoke/check.go index 0558bc06a..2ef100f4e 100644 --- a/cmd/smoke/check.go +++ b/cmd/smoke/check.go @@ -47,6 +47,13 @@ type probe struct { // needs as the dhm.APIKeyParam query parameter (#1065); "" for none. // It is appended at send time, so the printed url never holds it. apiKey string + // clientKey is the config key of a browser key the request needs inside + // its URL (#1065 M6: Skærmkort, whose URL the browser builds with the + // key first); "" for none. The key is only ever in the sent URL: the + // printed one is built with a placeholder. + clientKey string + // urlKeyed builds the URL of a clientKey probe from the key. + urlKeyed func(key string) (string, error) // url builds the request URL with the client's own builder. url func() (string, error) // rng, when set, is sent as the Range header. @@ -113,14 +120,18 @@ func execute(ctx context.Context, hc *http.Client, p probe, toks tokens) result res.verdict, res.err = skip, p.skip return res } - for _, k := range []string{p.token, p.apiKey} { + for _, k := range []string{p.token, p.apiKey, p.clientKey} { if k != "" && toks[k] == "" { res.verdict, res.err = skip, "no "+k+" in the config" return res } } res.verdict = fail - target, err := p.url() + build := p.url + if p.clientKey != "" { + build = func() (string, error) { return p.urlKeyed(toks[p.clientKey]) } + } + target, err := build() var se skipError if errors.As(err, &se) { res.verdict, res.err = skip, se.Error() @@ -131,6 +142,13 @@ func execute(ctx context.Context, hc *http.Client, p probe, toks tokens) result return res } res.url = target + if p.clientKey != "" { + // The printed URL never holds the key, not even redacted. + if res.url, err = p.urlKeyed(redacted); err != nil { + res.err = "building the request: " + err.Error() + return res + } + } if p.apiKey != "" { target += "&" + dhm.APIKeyParam + "=" + url.QueryEscape(toks[p.apiKey]) } @@ -180,6 +198,8 @@ func execute(ctx context.Context, hc *http.Client, p probe, toks tokens) result // (#1065 M0 §5.4): which credential to check, never what upstream said. func refusalHint(p probe, status int) string { switch { + case p.clientKey != "": + return "Datafordeleren refused the browser key: " + p.clientKey + " is missing or invalid, younger than 15 minutes, or its IT-system lacks the Skærmkort WMS" case p.apiKey != "" && status == http.StatusUnauthorized: return "Datafordeleren refused the key: " + p.apiKey + " is missing or invalid, or younger than 15 minutes (a new key takes 15 minutes to become active)" case p.apiKey != "": diff --git a/cmd/smoke/config.go b/cmd/smoke/config.go index 69c135753..23df59df0 100644 --- a/cmd/smoke/config.go +++ b/cmd/smoke/config.go @@ -20,6 +20,11 @@ const tokenDHM = "map.dhm.token" // the apikey query parameter. const keyDatafordeler = "map.datafordeler.apiKey" +// keyClientSkaermkort is the config key of the browser key of the Skærmkort +// base maps (#1065 M6), a key of its own from a separate IT-system, never +// map.datafordeler.apiKey. The Skærmkort probe sends it as the browser does. +const keyClientSkaermkort = "map.tiles.providers.datafordeler.apiKey" + // tokens are the tokens read from the config, by config key; a missing // or blank one is "". type tokens map[string]string @@ -51,7 +56,7 @@ func loadTokens(path string) (tokens, error) { if err := json.Unmarshal(data, &doc); err != nil { return nil, fmt.Errorf("config %s: %s", path, describeDecodeError(err)) } - toks := tokens{tokenDHM: "", keyDatafordeler: ""} + toks := tokens{tokenDHM: "", keyDatafordeler: "", keyClientSkaermkort: clientSkaermkortKey(doc.Map["tiles"])} if raw, ok := doc.Map["datafordeler"]; ok { var d dhm.DatafordelerConfig if err := json.Unmarshal(raw, &d); err != nil { @@ -84,3 +89,20 @@ func describeDecodeError(err error) string { } return "it could not be decoded as JSON" } + +// clientSkaermkortKey is map.tiles.providers.datafordeler.apiKey in raw, trimmed; +// "" for anything missing or of another shape (the browser ignores such a +// block too, so it is a SKIP, not an error). +func clientSkaermkortKey(raw json.RawMessage) string { + var tiles struct { + Providers struct { + Datafordeler struct { + APIKey string `json:"apiKey"` + } `json:"datafordeler"` + } `json:"providers"` + } + if raw == nil || json.Unmarshal(raw, &tiles) != nil { + return "" + } + return strings.TrimSpace(tiles.Providers.Datafordeler.APIKey) +} diff --git a/cmd/smoke/probes.go b/cmd/smoke/probes.go index 03380898e..c4d3261bf 100644 --- a/cmd/smoke/probes.go +++ b/cmd/smoke/probes.go @@ -21,13 +21,6 @@ var site = dhm.LatLon{Lat: 55.6761, Lon: 12.5683} // overlay's range, contours (from zoom 14) included, and the ortho's. const siteZoom = 14 -// skaermkortSkip is why Skærmkort is not probed: #741 builds its request -// in the browser only, and the smoke check sends no hand-written URL. -const skaermkortSkip = "no Go request builder: the Skærmkort WMS URL is built in the browser " + - "(public/map-tile-providers.js, #741; on Datafordeleren since #1065 M6), with the browser key " + - "map.tiles.providers.datafordeler.apiKey; " + - "probe it here once a Go builder exists" - // naturSkip is why Natur- og Friluftskort is not probed, for the same // reason as Skærmkort (#741 M2). const naturSkip = "no Go request builder: the Natur- og Friluftskort WMS URL is built in the browser " + @@ -267,7 +260,17 @@ func buildProbes(s settings) []probe { check: checkRange(cdnRange, checkTIFF), }) - ps = append(ps, probe{name: "skaermkort-wms", skip: skaermkortSkip}) + // Skærmkort (#1065 M6): the browser's own request, with the browser key. + sk := siteTileAt(skaermkortZoom) + ps = append(ps, probe{ + name: "skaermkort-wms", + clientKey: keyClientSkaermkort, + urlKeyed: func(key string) (string, error) { + return skaermkortURL(key, skaermkortLayer, sk.Z, sk.X, sk.Y), nil + }, + status: http.StatusOK, + check: checkImage("png", skaermkortTileSize), + }) ps = append(ps, probe{name: "natur-friluft-wms", skip: naturSkip}) return ps } diff --git a/cmd/smoke/skaermkort.go b/cmd/smoke/skaermkort.go new file mode 100644 index 000000000..82903aa3f --- /dev/null +++ b/cmd/smoke/skaermkort.go @@ -0,0 +1,62 @@ +package main + +import ( + "math" + "net/url" + "strconv" + "strings" +) + +// The Skærmkort WMS request, as the browser builds it (#1065 M6, +// #1081 review F2): public/map-tile-providers.js gives Leaflet's WMS layer +// the base URL ?apikey=, the layer and 512 px tiles with +// zoomOffset -1, and Leaflet appends the GetMap parameters in its own +// order and the tile's EPSG:3857 box last. skaermkortURL reproduces that +// string exactly; test-fixtures/skaermkort-wms-url-1065.json holds what the +// browser requested, and both sides assert it, so the two cannot drift. + +// skaermkortService is the Datafordeleren WMS of the Skærmkort layers. +const skaermkortService = "https://wms.datafordeler.dk/Dkskaermkort/topo_skaermkort/1.0.0/wms" + +// skaermkortLayer is the standard Skærmkort; the grå and dæmpet variants +// are dtk_skaermkort_graa and dtk_skaermkort_daempet. +const skaermkortLayer = "dtk_skaermkort" + +// skaermkortZoom is the tile zoom of the probe: the browser's 512 px tiles +// have zoomOffset -1, so map zoom siteZoom asks tiles of zoom siteZoom-1. +const skaermkortZoom = siteZoom - 1 + +// skaermkortTileSize is the WMS tile edge in pixels. +const skaermkortTileSize = 512 + +// webMercatorHalfWorld is half the EPSG:3857 world width in metres +// (π × the WGS 84 radius). +const webMercatorHalfWorld = math.Pi * 6378137 + +// skaermkortURL is the GetMap URL of tile z/x/y (the browser's 512 px tile +// grid) of layer, with key as the apikey parameter. +func skaermkortURL(key, layer string, z, x, y int) string { + res := 2 * webMercatorHalfWorld / math.Exp2(float64(z)) + minX := -webMercatorHalfWorld + float64(x)*res + maxY := webMercatorHalfWorld - float64(y)*res + box := []string{formatMetres(minX), formatMetres(maxY - res), formatMetres(minX + res), formatMetres(maxY)} + edge := strconv.Itoa(skaermkortTileSize) + return skaermkortService + "?apikey=" + encodeURIComponent(key) + + "&service=WMS&request=GetMap&layers=" + encodeURIComponent(layer) + + "&styles=&format=image%2Fpng&transparent=FALSE&version=1.3.0" + + "&width=" + edge + "&height=" + edge + "&crs=EPSG%3A3857&bbox=" + strings.Join(box, ",") +} + +// formatMetres is the shortest decimal that parses back to v, like +// JavaScript's Number toString for these magnitudes. +func formatMetres(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) } + +// encodeURIComponent is JavaScript's: everything but A-Z a-z 0-9 - _ . ! ~ * ' ( ) +// is percent-escaped, a space as %20. +func encodeURIComponent(s string) string { + s = strings.ReplaceAll(url.QueryEscape(s), "+", "%20") + for _, r := range []struct{ from, to string }{{"%21", "!"}, {"%27", "'"}, {"%28", "("}, {"%29", ")"}, {"%2A", "*"}} { + s = strings.ReplaceAll(s, r.from, r.to) + } + return s +} diff --git a/cmd/smoke/skaermkort_1065_test.go b/cmd/smoke/skaermkort_1065_test.go new file mode 100644 index 000000000..937d71912 --- /dev/null +++ b/cmd/smoke/skaermkort_1065_test.go @@ -0,0 +1,241 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "math" + "net/http" + "net/url" + "os" + "strings" + "testing" + "time" +) + +// #1065 (#1081 review F2) — the Skærmkort WMS probe. Its URL is the one the +// browser builds (public/map-tile-providers.js + Leaflet's WMS layer), from +// the browser key map.tiles.providers.datafordeler.apiKey. + +const clientKeyConfigKey = "map.tiles.providers.datafordeler.apiKey" + +// clientKey is a dummy browser key, distinct from testAPIKey (the server's). +const clientKey = "SENTINEL-client/key+1065" + +func clientKeyConfig(t *testing.T) string { + return writeConfig(t, `{"map":{"datafordeler":{"apiKey":"`+testAPIKey+`"},"tiles":{"providers":{"datafordeler":{"enabled":true,"apiKey":" `+clientKey+` "}}}}}`) +} + +type skaermkortFixture struct { + APIKey string `json:"apiKey"` + Cases []struct { + Layer string `json:"layer"` + Z int `json:"z"` + X int `json:"x"` + Y int `json:"y"` + URL string `json:"url"` + } `json:"cases"` +} + +func loadSkaermkortFixture(t *testing.T) skaermkortFixture { + t.Helper() + data, err := os.ReadFile("../../test-fixtures/skaermkort-wms-url-1065.json") + if err != nil { + t.Fatal(err) + } + var fx skaermkortFixture + if err := json.Unmarshal(data, &fx); err != nil { + t.Fatal(err) + } + if len(fx.Cases) < 4 { + t.Fatalf("fixture has %d cases", len(fx.Cases)) + } + return fx +} + +// sameGetMap is whether two GetMap URLs are the same request: every byte up +// to the box equal, and each box edge equal within bboxToleranceM. Leaflet +// computes the box through a latitude/longitude round trip, which leaves +// float noise in the last digits (-20037508.34278071 for -20037508.342789244); +// the Go builder is exact, and a WMS does not see 0.1 mm (Leaflet clamps the latitude at 85.0511287798, 9e-6 m off the exact edge). +func sameGetMap(a, b string) bool { + ap, ab, aok := strings.Cut(a, "&bbox=") + bp, bb, bok := strings.Cut(b, "&bbox=") + if !aok || !bok || ap != bp { + return false + } + ae, be := strings.Split(ab, ","), strings.Split(bb, ",") + if len(ae) != 4 || len(be) != 4 { + return false + } + for i := range ae { + var x, y float64 + if _, err := fmt.Sscan(ae[i], &x); err != nil { + return false + } + if _, err := fmt.Sscan(be[i], &y); err != nil || math.Abs(x-y) > bboxToleranceM { + return false + } + } + return true +} + +const bboxToleranceM = 1e-4 + +// The Go builder returns the browser's request, what the browser requested for the +// same key, layer and tile. The same fixture is asserted against the real +// Leaflet layer in test-issue-1065-skaermkort-url-e2e.js, so the two +// builders cannot drift apart. +func TestSkaermkort1065_BuilderMatchesTheBrowserFixture(t *testing.T) { + fx := loadSkaermkortFixture(t) + layers := map[string]bool{} + for _, c := range fx.Cases { + layers[c.Layer] = true + got := skaermkortURL(fx.APIKey, c.Layer, c.Z, c.X, c.Y) + if !sameGetMap(got, c.URL) { + t.Errorf("%s %d/%d/%d\n got %s\nwant %s", c.Layer, c.Z, c.X, c.Y, got, c.URL) + } + } + for _, l := range []string{"dtk_skaermkort", "dtk_skaermkort_graa", "dtk_skaermkort_daempet"} { + if !layers[l] { + t.Errorf("fixture has no %s case", l) + } + } +} + +// With the client key the probe sends one GetMap for the tile over +// Copenhagen, with the browser's parameters and the key once, and passes on +// a 512 px PNG. The key is printed nowhere, not even redacted in a URL. +func TestSkaermkort1065_ProbeSendsTheBrowserRequestAndNeverPrintsTheKey(t *testing.T) { + f := newFake(t) + code, out := runSmoke(t, f, "-config", clientKeyConfig(t)) + if code != 0 { + t.Fatalf("exit %d\n%s", code, out) + } + l := resultLine(t, out, "skaermkort-wms") + if !strings.HasPrefix(l, "PASS") || !strings.Contains(l, "png 512x512") { + t.Fatalf("%q", l) + } + for _, k := range []string{clientKey, url.QueryEscape(clientKey), url.PathEscape(clientKey), testAPIKey} { + if strings.Contains(out, k) { + t.Fatalf("key printed:\n%s", out) + } + } + var n int + for _, s := range f.requests() { + if s.host != "wms.datafordeler.dk" || s.path != "/Dkskaermkort/topo_skaermkort/1.0.0/wms" { + continue + } + n++ + z, x, y := siteTileAt(skaermkortZoom).Z, siteTileAt(skaermkortZoom).X, siteTileAt(skaermkortZoom).Y + want := skaermkortURL(clientKey, "dtk_skaermkort", z, x, y) + if got := "https://" + s.host + s.path + "?" + s.rawQuery; got != want { + t.Errorf("request\n got %s\nwant %s", got, want) + } + q, _ := url.ParseQuery(s.rawQuery) + if len(q["apikey"]) != 1 || q.Get("apikey") != clientKey || q.Get("width") != "512" || q.Get("crs") != "EPSG:3857" || q.Get("version") != "1.3.0" { + t.Errorf("query %s", s.rawQuery) + } + if len(s.header.Values("Token")) != 0 { + t.Errorf("a token header was sent") + } + } + if n != 1 { + t.Fatalf("%d requests to the Skærmkort WMS, want 1", n) + } +} + +// The tile is over Denmark: its EPSG:3857 box contains the site. +func TestSkaermkort1065_TileIsOverDenmark(t *testing.T) { + k := siteTileAt(skaermkortZoom) + u, err := url.Parse(skaermkortURL("k", "dtk_skaermkort", k.Z, k.X, k.Y)) + if err != nil { + t.Fatal(err) + } + var b [4]float64 + parts := strings.Split(u.Query().Get("bbox"), ",") + if len(parts) != 4 { + t.Fatalf("bbox %q", u.Query().Get("bbox")) + } + for i, p := range parts { + if _, err := fmt.Sscan(p, &b[i]); err != nil { + t.Fatal(err) + } + } + // Copenhagen City Hall Square in EPSG:3857 metres, (1399097, 7494205). + if !(b[0] < 1399097 && 1399097 < b[2] && b[1] < 7494205 && 7494205 < b[3]) { + t.Fatalf("bbox %v does not hold Copenhagen", b) + } +} + +// Without a client key the probe is SKIP, naming the key, and nothing goes +// to the Skærmkort WMS; the server's map.datafordeler.apiKey and the +// Dataforsyningen token are not used in its place. +func TestSkaermkort1065_NoClientKeySkips(t *testing.T) { + for name, cfg := range map[string]string{ + "server key only": `{"map":{"datafordeler":{"apiKey":"` + testAPIKey + `"},"dhm":{"token":"` + testToken + `"}}}`, + "blank client key": `{"map":{"tiles":{"providers":{"datafordeler":{"apiKey":" "}}}}}`, + "no map.tiles": `{"map":{}}`, + "odd tiles type": `{"map":{"tiles":"x"}}`, + } { + f := newFake(t) + code, out := runSmoke(t, f, "-config", writeConfig(t, cfg)) + if code != 0 { + t.Fatalf("%s: exit %d\n%s", name, code, out) + } + l := resultLine(t, out, "skaermkort-wms") + if !strings.HasPrefix(l, "SKIP") || !strings.Contains(l, clientKeyConfigKey) || strings.Contains(l, "FAIL") { + t.Fatalf("%s: %q", name, l) + } + for _, s := range f.requests() { + if strings.Contains(s.path, "Dkskaermkort") { + t.Fatalf("%s: the Skærmkort WMS was requested", name) + } + } + } + // No config at all: SKIP too. + f := newFake(t) + if code, out := runSmoke(t, f); code != 0 || !strings.HasPrefix(resultLine(t, out, "skaermkort-wms"), "SKIP") { + t.Fatalf("exit %d\n%s", code, out) + } +} + +// A refused key fails the run like the other Datafordeleren probes, with the +// hint naming the config key, and prints no key. +func TestSkaermkort1065_RefusedKeyFails(t *testing.T) { + f := newFake(t) + f.override = func(w http.ResponseWriter, r *http.Request) bool { + if r.Host == "wms.datafordeler.dk" && strings.Contains(r.URL.Path, "Dkskaermkort") { + w.WriteHeader(http.StatusForbidden) + return true + } + return false + } + code, out := runSmoke(t, f, "-config", clientKeyConfig(t)) + l := resultLine(t, out, "skaermkort-wms") + if code != 1 || !strings.HasPrefix(l, "REFUSED") || !strings.Contains(l, clientKeyConfigKey) || strings.Contains(out, clientKey) { + t.Fatalf("exit %d: %q", code, l) + } +} + +// The result's own URL, before the output redactor, holds no key: the +// redactor is the second line of defence, not the first. +func TestSkaermkort1065_ResultURLHoldsNoKey(t *testing.T) { + var p probe + for _, c := range buildProbes(defaultSettings()) { + if c.name == "skaermkort-wms" { + p = c + } + } + f := newFake(t) + toks := tokens{keyClientSkaermkort: clientKey} + res := execute(context.Background(), newHTTPClient(f.transport(), time.Second), p, toks) + if res.verdict != pass { + t.Fatalf("%v: %s", res.verdict, res.err) + } + for _, k := range []string{clientKey, url.QueryEscape(clientKey), encodeURIComponent(clientKey)} { + if strings.Contains(res.url, k) || strings.Contains(res.String(), k) { + t.Fatalf("the result holds the key: %s", res.url) + } + } +} diff --git a/cmd/smoke/smoke_test.go b/cmd/smoke/smoke_test.go index 4d67c2843..3bf68d6bd 100644 --- a/cmd/smoke/smoke_test.go +++ b/cmd/smoke/smoke_test.go @@ -76,7 +76,11 @@ func (f *fake) requests() []seen { func tile(t testing.TB, format string) []byte { var buf bytes.Buffer - img := image.NewRGBA(image.Rect(0, 0, 256, 256)) + edge := 256 + if format == "png512" { // the Skærmkort WMS tile (#1065 M6) + edge, format = 512, "png" + } + img := image.NewRGBA(image.Rect(0, 0, edge, edge)) var err error if format == "png" { err = png.Encode(&buf, img) @@ -142,6 +146,12 @@ func (f *fake) serve(w http.ResponseWriter, r *http.Request) { case r.Host == "api.dataforsyningen.dk" && r.URL.Path == "/"+dhm.ExaggeratedWMSService, r.Host == "wms.datafordeler.dk" && r.URL.Path == "/"+dhm.WMSService: answer("image/png", tile(nil, "png")) + case r.Host == "wms.datafordeler.dk" && strings.HasPrefix(r.URL.Path, "/Dkskaermkort/"): // #1065 M6 Skærmkort + if r.URL.Query().Get(dhm.APIKeyParam) == "" { + w.WriteHeader(http.StatusUnauthorized) + return + } + answer("image/png", tile(nil, "png512")) case r.Host == "wmts.datafordeler.dk" && r.URL.Path == "/"+dhm.OrthoWMTSService: // #1065 M4: like the real WMTS, 401 without a key. if r.URL.Query().Get(dhm.APIKeyParam) == "" { @@ -616,28 +626,6 @@ func TestProbeURLsAreTheClientBuilders(t *testing.T) { } } -// Skærmkort has no Go request builder (#741 builds its WMS URL in the -// browser), so it is listed as SKIP with that reason, never as a -// hand-written URL. #741 is merged (#805), so the reason must not say it -// is pending. -func TestSkaermkortIsSkippedWithoutABuilder(t *testing.T) { - f := newFake(t) - code, out := runSmoke(t, f, "-config", writeConfig(t, `{"map":{"dhm":{"token":"`+testToken+`"}}}`)) - if code != 0 { - t.Fatalf("exit %d\n%s", code, out) - } - if l := resultLine(t, out, "skaermkort-wms"); !strings.HasPrefix(l, "SKIP") || !strings.Contains(l, "#741") || - !strings.Contains(l, "built in the browser") || strings.Contains(l, "not merged") || - !strings.Contains(l, "map.tiles.providers.datafordeler.apiKey") || strings.Contains(l, "dataforsyningen.token") { - t.Fatalf("%q", l) - } - for _, s := range f.requests() { - if strings.Contains(strings.ToLower(s.rawQuery), "skaermkort") { - t.Fatalf("Skærmkort requested: %s", s.rawQuery) - } - } -} - // Natur- og Friluftskort (#741 M2) is built in the browser too, so the // report lists it as SKIP with that reason rather than leaving it out // (v0.2.9 review nit, #821 N2). diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 643104ee2..a8716b2fc 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -251,6 +251,7 @@ {"file":"test-issue-728-esri-imagery-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":78.886,"measurementNote":"New suite; #728 M1 Esri World Imagery base map and the Esri opt-in gate on Map and Live with an intercepted map.tiles client-config block, every third-party tile stubbed and a stubbed /api/map/dhm/wms: no Esri entry, customizer option or arcgisonline request while Esri is off; an Esri darkDefault/lightDefault or stored choice while off falls back to OSM with a console warning; with Esri on the imagery is offered, not requested until selected, loads {z}/{y}/{x} tiles to z19 with the exact credit and no filter in either theme; the customizer choice persists across a reload on Map and Live; and the DHM hillshade loads above it with both credits. Review round 3 adds Live's base-map credit: shown with no overlay, through every on/off order of the hillshade and the protected monuments (stubbed agency WMS), after explicit base picks and in-place Auto provider/theme swaps, in one control that no Live panel covers at 390x844, 740x360, 844x390 and 768x1024. About 70s locally; no CI duration measured yet. Assigned to shard 2, the lightest by meanSeconds.","secondsByExecution":[74.131,84.448,81.362,83.565,73.238,76.569]}, {"file":"test-issue-741-skaermkort-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":181.906,"measurementNote":"New suite; #741 M1b Dataforsyningen Skaermkort base maps through WMS in EPSG:3857 on Map and Live, with an intercepted map.tiles client-config block and a dummy token, every api.dataforsyningen.dk request answered by a 512 px stub in the browser and every other third-party tile stubbed: off by default and for enabled-without-token and enabled-as-string (no layer-control or customizer entry, no request), a gated-off default falls back to OSM with a warning naming both switches; on, four styles offered and nothing requested until picked; every GetMap carries exactly the allow-listed parameters, 512x512, EPSG:3857, the dummy token once and a bbox of 512 px at the map zoom; the CC BY 4.0 credit with dataset and licence links; grey under the invert filter in dark; the DHM hillshade above it; Auto swaps WMS and OSM on a theme switch both ways; the customizer choice applies in place and after a reload; a 375x560 phone flow picks a style in the layer control and keeps it through a theme switch, a control rebuild and SPA navigation, with a reload back to Auto; nothing requested outside the bounds; at most 20 GetMap requests per 1920x1080 view. #741 M2 adds Natur- og Friluftskort (wms/natur_friluftskort, Natur_Friluft_basis) on the same gate and token: offered as a light style only (layer control and the customizer's light list), nothing requested until picked, 512 px EPSG:3857 GetMaps with the same dummy token, its own CC BY 4.0 credit, no filter in either theme, the same tiles as Skaermkort for one pick/pan/zoom script with 1.0 s stub responses and none twice, at most 20 GetMaps per 1920x1080 view against 256 px tiles, and a 375x560 cold-start phone flow through a theme switch and SPA navigation to Live and back. About 180s locally with M2 (179s measured); no CI duration measured yet. Assigned to shard 2, next to the #728 base-map suites.","secondsByExecution":[173.014,192.36,188.793,191.244,172.226,173.797]}, {"file":"test-issue-1065-skaermkort-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":76,"measurementNote":"New suite; #1065 M6 Skaermkort from the Datafordeleren WMS with its own browser key (map.tiles.providers.datafordeler.apiKey), with an intercepted map.tiles client-config block and dummy keys, and a fake WMS answering wms.datafordeler.dk and api.dataforsyningen.dk in the browser: with only the Dataforsyningen token no Skaermkort entry on Map, Live or in the customizer and no request to either Skaermkort host, and a saved Skaermkort choice falls back to OSM; each of the four variants picked (standard, graa, daempet in light, graa under the invert filter in dark) requests only GetMaps of its layer with apikey once, no token, EPSG:3857, WMS 1.3.0, 512x512, the tiles render and the credit links the Datafordeleren product page; Live the same for one variant; Natur keeps the Dataforsyningen token and never gets the key. 76s in one local run on an idle 4-CPU VM (172s with the machine loaded); no CI duration measured yet. Assigned to shard 3, next to the #741 Skaermkort suite."}, + {"file":"test-issue-1065-skaermkort-url-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":15,"measurementNote":"New suite; #1065 F2 from the #1081 review: real Leaflet builds the Skaermkort GetMap URLs of the three layers and the world corners, equal to test-fixtures/skaermkort-wms-url-1065.json (which cmd/smoke asserts the Go builder against). About 15s in one local run; no CI duration measured yet. Shard 3, next to the other Skaermkort suite."}, {"file":"test-issue-737-skraafoto-viewer-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":61.992,"measurementNote":"New suite; #737 M2 Skraafoto (oblique aerial photo) viewer with an intercepted skraafoto client-config block (and dhm with profile: true), stubbed /api/skraafoto/search and /api/skraafoto/preview/{collection}/{item} in the M1 shapes, canvas-drawn JPEG previews and every other host refused: the gate (no block, a node without a fix, the node list), the node page dialog (loading, newest year facing north, five directions, the year selector without 2017, date, privacy note, credit links, Full resolution), lazy previews, a year change, Escape and Close focus return, the hash deep link and a cold deep link, search 429/503/502 and preview 503, an empty answer, the side pane, the Path profile A/B/clicked chart point (#781 mapping) and an unmoved head and chart, and real taps from a cold start at 375x560 and 640x360 above the bottom nav. About 15s locally; no CI duration measured yet. Assigned to shard 2, the lightest by meanSeconds, next to the #733 credit suite. #737 M3c adds the marks to the same suite (stubbed search with frame/point/inFrame/approx/path and a stubbed ?zoom=1 crop with the marker and box headers): the crosshair on the point through a resize and a rotation, dashed when approximate, absent out of frame, the aria-pressed zoom toggle fetching the crop once, the line of sight from a profile and its side-view default direction, on desktop and from a cold start at 375x560 and 640x360 by taps; about 35s locally in all.","secondsByExecution":[54.722,69.682,66.673,69.133,53.91,57.831]}, {"file":"test-issue-680-dhm-terrain-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":53.417,"measurementNote":"New suite; #680 DHM terrain hillshade overlay on Map and Live with an intercepted dhm client-config block and a stubbed /api/map/dhm/wms: not offered unless enabled, off by default with zero terrain requests, toggle on/off (tiles, opacity, pane z-order, attribution, hash, storage), marker hit-tests, hash/storage round-trip across pages and reload, allow-listed request shape with no token, and no requests or console errors outside Denmark. About 45s locally; no CI duration measured yet. Assigned to shard 1, which runs the fewest suites.","secondsByExecution":[51.559,52.737,52.502,50.733,57.625,55.344]}, {"file":"test-issue-734-dhm-overlay-budget-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":39.286,"measurementNote":"New suite; #734 M2 DHM tile budget with two overlays (hillshade + contours) from z15 at 1920x1080: a normal and an aggressive session against the default map.dhm.tileRateLimitPerMin and the cold first view against the admission bound. About 45s locally; no CI duration measured yet. Assigned to shard 1 next to #681's budget suite.","secondsByExecution":[38.482,39.313,39.031,37.072,42.416,39.399]}, diff --git a/test-fixtures/skaermkort-wms-url-1065.json b/test-fixtures/skaermkort-wms-url-1065.json new file mode 100644 index 000000000..ba95ab798 --- /dev/null +++ b/test-fixtures/skaermkort-wms-url-1065.json @@ -0,0 +1,47 @@ +{ + "apiKey": "dummy key!/+1065()", + "cases": [ + { + "layer": "dtk_skaermkort", + "z": 13, + "x": 4381, + "y": 2564, + "url": "https://wms.datafordeler.dk/Dkskaermkort/topo_skaermkort/1.0.0/wms?apikey=dummy%20key!%2F%2B1065()&service=WMS&request=GetMap&layers=dtk_skaermkort&styles=&format=image%2Fpng&transparent=FALSE&version=1.3.0&width=512&height=512&crs=EPSG%3A3857&bbox=1394211.395921615,7489605.779494709,1399103.3657318663,7494497.749304961" + }, + { + "layer": "dtk_skaermkort_graa", + "z": 13, + "x": 4381, + "y": 2564, + "url": "https://wms.datafordeler.dk/Dkskaermkort/topo_skaermkort/1.0.0/wms?apikey=dummy%20key!%2F%2B1065()&service=WMS&request=GetMap&layers=dtk_skaermkort_graa&styles=&format=image%2Fpng&transparent=FALSE&version=1.3.0&width=512&height=512&crs=EPSG%3A3857&bbox=1394211.395921615,7489605.779494709,1399103.3657318663,7494497.749304961" + }, + { + "layer": "dtk_skaermkort_daempet", + "z": 13, + "x": 4381, + "y": 2564, + "url": "https://wms.datafordeler.dk/Dkskaermkort/topo_skaermkort/1.0.0/wms?apikey=dummy%20key!%2F%2B1065()&service=WMS&request=GetMap&layers=dtk_skaermkort_daempet&styles=&format=image%2Fpng&transparent=FALSE&version=1.3.0&width=512&height=512&crs=EPSG%3A3857&bbox=1394211.395921615,7489605.779494709,1399103.3657318663,7494497.749304961" + }, + { + "layer": "dtk_skaermkort", + "z": 5, + "x": 17, + "y": 10, + "url": "https://wms.datafordeler.dk/Dkskaermkort/topo_skaermkort/1.0.0/wms?apikey=dummy%20key!%2F%2B1065()&service=WMS&request=GetMap&layers=dtk_skaermkort&styles=&format=image%2Fpng&transparent=FALSE&version=1.3.0&width=512&height=512&crs=EPSG%3A3857&bbox=1252344.2714243277,6261721.357121641,2504688.5428486555,7514065.628545967" + }, + { + "layer": "dtk_skaermkort", + "z": 0, + "x": 0, + "y": 0, + "url": "https://wms.datafordeler.dk/Dkskaermkort/topo_skaermkort/1.0.0/wms?apikey=dummy%20key!%2F%2B1065()&service=WMS&request=GetMap&layers=dtk_skaermkort&styles=&format=image%2Fpng&transparent=FALSE&version=1.3.0&width=512&height=512&crs=EPSG%3A3857&bbox=-20037508.342789244,-20037508.34278071,20037508.342789244,20037508.34278071" + }, + { + "layer": "dtk_skaermkort", + "z": 1, + "x": 1, + "y": 1, + "url": "https://wms.datafordeler.dk/Dkskaermkort/topo_skaermkort/1.0.0/wms?apikey=dummy%20key!%2F%2B1065()&service=WMS&request=GetMap&layers=dtk_skaermkort&styles=&format=image%2Fpng&transparent=FALSE&version=1.3.0&width=512&height=512&crs=EPSG%3A3857&bbox=0,-20037508.34278071,20037508.342789244,0" + } + ] +} diff --git a/test-issue-1065-skaermkort-url-e2e.js b/test-issue-1065-skaermkort-url-e2e.js new file mode 100644 index 000000000..e88dcd100 --- /dev/null +++ b/test-issue-1065-skaermkort-url-e2e.js @@ -0,0 +1,151 @@ +/** + * E2E (#1065, #1081 review F2): + * + * F2 — the URL the browser builds for a Skærmkort tile, from real Leaflet + * and the real provider registry, equals the shared fixture + * test-fixtures/skaermkort-wms-url-1065.json, which cmd/smoke's Go + * builder is asserted against too (TestSkaermkort1065_BuilderMatches + * TheBrowserFixture), so the two cannot drift. UPDATE_FIXTURE=1 + * rewrites the fixture from the browser (review the diff). + * + * The CI server has no map.tiles config, so /api/config/client is given the + * block an operator would set, with a dummy key; every request to a Danish + * WMS host is answered by a fake PNG in the browser, nothing reaches either + * agency. + * + * Usage: + * BASE_URL=http://localhost:13581 node test-issue-1065-skaermkort-url-e2e.js + */ +'use strict'; +const { chromium } = require('playwright'); +const fs = require('fs'); +const path = require('path'); +const zlib = require('zlib'); + +const BASE = process.env.BASE_URL || 'http://localhost:13581'; +const FIXTURE = path.join(__dirname, 'test-fixtures', 'skaermkort-wms-url-1065.json'); +const KEY = 'dummy key!/+1065()'; +// The tiles the fixture pins, z being the 512 px grid zoom (the {z} of the +// tile, map zoom - 1; Leaflet's coords.z is the map zoom): three layers over Copenhagen at the probe's +// zoom, a coarse tile, and the corner tiles of the world. +const CASES = [ + { id: 'dataforsyningen-skaermkort', layer: 'dtk_skaermkort', z: 13, x: 4381, y: 2564 }, + { id: 'dataforsyningen-skaermkort-graa', layer: 'dtk_skaermkort_graa', z: 13, x: 4381, y: 2564 }, + { id: 'dataforsyningen-skaermkort-daempet', layer: 'dtk_skaermkort_daempet', z: 13, x: 4381, y: 2564 }, + { id: 'dataforsyningen-skaermkort', layer: 'dtk_skaermkort', z: 5, x: 17, y: 10 }, + { id: 'dataforsyningen-skaermkort', layer: 'dtk_skaermkort', z: 0, x: 0, y: 0 }, + { id: 'dataforsyningen-skaermkort', layer: 'dtk_skaermkort', z: 1, x: 1, y: 1 }, +]; + +const CRC = (() => { + const t = new Int32Array(256); + for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c; } + return t; +})(); +function crc32(buf) { let c = -1; for (const b of buf) c = CRC[(c ^ b) & 0xff] ^ (c >>> 8); return (c ^ -1) >>> 0; } +function chunk(type, data) { + const len = Buffer.alloc(4); len.writeUInt32BE(data.length); + const td = Buffer.concat([Buffer.from(type), data]); + const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(td)); + return Buffer.concat([len, td, crc]); +} +function png(size, rgb) { + const raw = Buffer.alloc((size * 3 + 1) * size); + for (let j = 0; j < size; j++) for (let i = 0; i < size; i++) rgb.forEach((v, k) => { raw[j * (size * 3 + 1) + 1 + i * 3 + k] = v; }); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); ihdr.writeUInt32BE(size, 4); ihdr[8] = 8; ihdr[9] = 2; + return Buffer.concat([Buffer.from('\x89PNG\r\n\x1a\n', 'binary'), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); +} +const WMS_TILE = png(512, [236, 233, 224]); +const OTHER_TILE = png(256, [210, 210, 210]); + +let passed = 0, failed = 0; +async function step(name, fn) { + try { await fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { failed++; console.error(' ✗ ' + name + ': ' + e.message); } +} +function assert(c, m) { if (!c) throw new Error(m || 'assertion failed'); } + +(async () => { + const browser = await chromium.launch({ + headless: true, + executablePath: process.env.CHROMIUM_PATH || undefined, + args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'], + }); + console.log(`\n=== #1065 Skærmkort URL parity against ${BASE} ===\n`); + + async function newCtx(viewport) { + const ctx = await browser.newContext({ viewport }); + const rec = { errors: [] }; + await ctx.route(BASE + '/api/config/client', async (route) => { + const response = await route.fetch(); + const config = await response.json(); + delete config.tiles; + config.map = Object.assign({}, config.map, { tiles: { providers: { datafordeler: { enabled: true, apiKey: KEY } } } }); + await route.fulfill({ response, json: config }); + }); + await ctx.route(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i, async (route) => { + const url = route.request().url(); + if (url.indexOf('https://wms.datafordeler.dk/') === 0) { await route.fulfill({ status: 200, contentType: 'image/png', body: WMS_TILE }); return; } + if (route.request().resourceType() !== 'image') { await route.abort(); return; } + await route.fulfill({ status: 200, contentType: 'image/png', body: OTHER_TILE }); + }); + await ctx.addInitScript(() => { + try { if (!sessionStorage.getItem('__e2e1065f')) { sessionStorage.setItem('__e2e1065f', '1'); localStorage.setItem('meshcore-theme', 'light'); } } catch (_) {} + }); + const page = await ctx.newPage(); + page.on('console', m => { if (m.type() === 'error') rec.errors.push(m.text()); }); + page.on('pageerror', e => rec.errors.push(String(e))); + return { ctx, page, rec }; + } + async function gotoMap(page) { + await page.goto(`${BASE}/#/map?lat=56.15&lon=10.2&zoom=12`, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('.leaflet-control-layers', { timeout: 20000 }); + await page.waitForFunction(() => window.MeshConfigReady !== undefined, null, { timeout: 10000 }); + await page.evaluate(() => window.MeshConfigReady).catch(() => {}); + await page.waitForTimeout(900); + } + async function selectBase(page, id) { + await page.evaluate((tid) => { + const input = document.querySelector('.leaflet-control-layers-base label[data-tile-id="' + tid + '"] input'); + if (!input) throw new Error('no base layer ' + tid); + input.click(); + }, id); + await page.waitForTimeout(1200); + } + + // F2 — the browser's own URL, from real Leaflet and the real registry. + await step('the Leaflet layer of each Skærmkort variant requests the fixture URLs', async () => { + const { ctx, page } = await newCtx({ width: 1100, height: 720 }); + try { + await gotoMap(page); + const got = await page.evaluate(({ cases }) => { + const div = document.createElement('div'); + div.style.cssText = 'position:fixed;left:0;top:0;width:600px;height:400px;visibility:hidden'; + document.body.appendChild(div); + const map = L.map(div, { center: [56, 10], zoom: 6 }); + const out = cases.map((c) => { + const layer = window.MC_createBaseLayer(window.MC_TILE_PROVIDERS[c.id]).addTo(map); + const url = (() => { const pt = L.point(c.x, c.y); pt.z = c.z + 1; return layer.getTileUrl(pt); })(); + map.removeLayer(layer); + return url; + }); + map.remove(); div.remove(); + return out; + }, { cases: CASES }); + const fixture = { apiKey: KEY, cases: CASES.map((c, i) => ({ layer: c.layer, z: c.z, x: c.x, y: c.y, url: got[i] })) }; + if (process.env.UPDATE_FIXTURE === '1') { + fs.writeFileSync(FIXTURE, JSON.stringify(fixture, null, 2) + '\n'); + console.log(' fixture written: ' + FIXTURE); + } + const want = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')); + assert(want.apiKey === KEY, 'fixture key ' + want.apiKey); + assert(JSON.stringify(want.cases) === JSON.stringify(fixture.cases), + 'the browser builds\n' + JSON.stringify(fixture.cases, null, 1) + '\nthe fixture holds\n' + JSON.stringify(want.cases, null, 1)); + } finally { await ctx.close(); } + }); + + await browser.close(); + console.log(`\n=== #1065 Skærmkort URL parity: ${passed} passed, ${failed} failed ===`); + process.exit(failed ? 1 : 0); +})().catch(e => { console.error(e); process.exit(1); });