Skip to content

Commit cf6aa44

Browse files
kptdobeCopilot
andcommitted
fix: harden site registry lookups
Expire negative probes and keep known routing results on cache write failures. Authorize listing probes and gate org discovery on cached HLX6 sites. Avoid sharing request-scoped I/O between Worker requests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 00f69c3 commit cf6aa44

8 files changed

Lines changed: 262 additions & 67 deletions

File tree

‎README.md‎

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -52,19 +52,31 @@ supported calls for HLX6-backed projects or return `410 Gone` when unsupported.
5252
### Helix 6 request handling
5353

5454
Both da-admin and da-content resolve sites through the shared `DA_SITE_BACKENDS`
55-
KV binding. Keys are lowercase `org/site`; values are the strings `da` or `hlx6`.
55+
KV binding. Keys are lowercase `org/site`; values are the strings `da` or `hlx6`
56+
(case and surrounding whitespace are normalized when reading).
5657
An `hlx6` site uses a synchronous compatibility bridge to `AEM_API`
5758
(`https://api.aem.live` by default).
5859

5960
On a cache miss, the worker makes an unauthenticated GET to
60-
`https://admin.hlx.page/ping/{org}/{site}` with a 3s timeout. Presence of
61-
`x-api-upgrade-available` identifies HLX6. Successful responses without that
62-
header, and 404s for unregistered sites, identify DA. Both results are persisted
63-
without expiration; cache hits do not ping. Concurrent lookups within one worker
64-
are coalesced, but KV does not guarantee a single probe globally.
61+
`https://admin.hlx.page/ping/{org}/{site}` with a 3s timeout. Set `HLX_ADMIN`
62+
to override the probe base URL per environment (for example in `.dev.vars` or
63+
the Cloudflare dashboard); local integration tests use the mock server.
64+
Presence of `x-api-upgrade-available` selects HLX6. This is a source-bus
65+
configuration heuristic, including overlays, **not proof of completed cutover**.
66+
Explicit registry entries override it. Successful responses without that header
67+
select DA. Successful probe results persist without expiration; 404 results
68+
expire after **300 seconds** so not-yet-created sites can be detected later.
69+
Cache hits do not ping. Concurrent cold requests own their I/O independently;
70+
KV does not guarantee a single probe globally.
6571
Redirects, auth/rate-limit/server errors, timeouts, invalid registry values, and
66-
KV failures fail the request rather than assuming DA or writing legacy storage.
67-
Only in-flight lookups are held in memory; subsequent requests read KV again.
72+
KV read failures fail the request rather than assuming DA or writing legacy
73+
storage. Failed KV writes are logged without discarding the known probe result.
74+
Subsequent requests read KV again.
75+
76+
Site listings require read or readable-descendant permission before backend
77+
detection. The 404 expiry limits retention, not traffic: signed-in users of open
78+
orgs, and public da-content requests, can still generate cold probes. This is
79+
not a rate limiter or an org-existence check.
6880

6981
The bridge supports:
7082

@@ -74,10 +86,14 @@ The bridge supports:
7486
filtering. HLX6 listings are unpaginated; a legacy continuation token on a
7587
migrated site's listing is rejected.
7688
- Org GET listings, merging legacy DA sites with the org's bridged HLX6 sites:
77-
entries of `GET /{org}/source/` (caller token, 3s timeout) resolved as HLX6
78-
through the registry, filtered by DA ACLs. Org listings also discover sites
79-
not yet cached. If the HLX6 listing or site resolution fails
80-
(outage, timeout, missing HLX6 role), the DA listing is still returned.
89+
discovery runs only if the registry already contains a non-dual-writing HLX6
90+
site for that org. The gate uses paginated KV listing and bulk reads of at most
91+
100 keys, without pinging. Entries of `GET /{org}/source/` (caller token,
92+
3s timeout) are filtered by DA ACLs before resolving their backends. Unknown
93+
sites can then be discovered. An entirely uncached HLX6-only org requires a
94+
direct site request or a seeded registry entry before discovery is enabled.
95+
Failed individual lookups are logged and omitted while healthy sites remain;
96+
if discovery is unavailable, the DA listing is still returned.
8197
Only the first legacy page adds HLX6 sites; subsequent pages preserve the
8298
DA continuation token without repeating them.
8399
- Site editor-config GET and multipart PUT/POST (`config` field), converting
@@ -134,9 +150,13 @@ Production uses the `DA_SITE_BACKENDS` namespace
134150
Both workers bind the appropriate namespace as `DA_SITE_BACKENDS`. Local dev
135151
and integration tests use emulated KV, not remote registry writes.
136152

137-
Before deploying, seed any existing `HLX6_MIGRATED_SITES` entries as `hlx6`
138-
in the corresponding namespace, then deploy da-admin before da-content.
139-
The old environment variable is no longer read.
153+
Before deploying, preload **all sites still served by DA** as `da`, including
154+
dual-write sites, and existing `HLX6_MIGRATED_SITES` entries as `hlx6` in the
155+
corresponding namespace. Do not blindly overwrite existing authoritative entries;
156+
resolve conflicting inventory first. Preloading DA sites avoids making rollout
157+
depend on successful cold pings and prevents an overlay header from triggering
158+
premature cutover. Then deploy da-admin before da-content. The old environment
159+
variable is no longer read. Manual entries have no expiration.
140160

141161
Before starting dual write, explicitly set the site's registry entry to `da`.
142162
This keeps da-content on legacy routing even if a cold ping would identify the

‎src/index.js‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import getHandler from './handlers/get.js';
1717
import postHandler from './handlers/post.js';
1818
import deleteHandler from './handlers/delete.js';
1919
import { initHlx6, isHlx6Site } from './utils/hlx6.js';
20+
import { hasDescendantPermission } from './utils/auth.js';
2021
import hlx6Handler, { listHlx6Org } from './routes/hlx6.js';
2122

2223
export default {
@@ -55,13 +56,11 @@ export default {
5556
const anon = users.some((user) => user.email === 'anonymous');
5657
if (anon) return daResp({ status: 401 });
5758

58-
// `authorized` only reflects permission on the exact requested path. A user
59-
// granted permission on some deeper descendant only (e.g. /folder2/a/b/c)
60-
// is not "authorized" for a listing of an ancestor folder by that measure,
61-
// but should still be able to list it to reach their descendant. The list
62-
// route itself knows how to fall back to descendant permission, so this
63-
// blanket gate must not shadow it.
64-
if (!authorized && api !== 'list') return daResp({ status: 403 });
59+
// Listings can traverse readable descendants, but must pass that permission
60+
// check before any backend lookup or probe.
61+
if (!authorized && (api !== 'list' || !hasDescendantPermission(daCtx, key, 'read'))) {
62+
return daResp({ status: 403 });
63+
}
6564

6665
// `key` is org-stripped (daCtx.key), so version storage appears as the
6766
// segment `{repo}/.da-versions/...`, not a leading `.da-versions`. Block the

‎src/routes/hlx6.js‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
* governing permissions and limitations under the License.
1111
*/
1212
import daResp from '../utils/daResp.js';
13-
import { DEFAULT_AEM_API, HLX6_GONE, isHlx6Site } from '../utils/hlx6.js';
13+
import {
14+
DEFAULT_AEM_API, HLX6_GONE, hasHlx6Sites, isHlx6Site,
15+
} from '../utils/hlx6.js';
1416
import { hasDescendantPermission, hasPermission } from '../utils/auth.js';
1517
import { FORM_TYPES } from '../utils/constants.js';
1618
import { sourceRespObject } from '../helpers/source.js';
@@ -231,10 +233,17 @@ async function listSource({ req, env, daCtx }) {
231233
* Best effort with a short timeout: failures yield no sites so DA org browsing keeps working.
232234
* @param {Request} req Legacy request carrying the caller credentials.
233235
* @param {Env} env Worker bindings and API base URL.
234-
* @param {string} org DA organization name.
236+
* @param {DaCtx} daCtx DA organization and listing permissions.
235237
* @returns {Promise<string[]>} Lowercase bridged site names.
236238
*/
237-
async function fetchHlx6OrgSites(req, env, org) {
239+
async function fetchHlx6OrgSites(req, env, daCtx) {
240+
const { org } = daCtx;
241+
try {
242+
if (!await hasHlx6Sites(env, org)) return [];
243+
} catch (e) {
244+
console.error('[hlx6] Org site registry unavailable; using DA sites only', e.message);
245+
return [];
246+
}
238247
const upstream = await requestHlx6(req, env, `${encodeURIComponent(org)}/source/`, {
239248
method: 'GET', timeout: ORG_LIST_TIMEOUT,
240249
});
@@ -249,9 +258,18 @@ async function fetchHlx6OrgSites(req, env, org) {
249258
const sites = items
250259
.map((item) => item?.name)
251260
.filter((name) => typeof name === 'string' && /^[^/.]+\/$/.test(name))
252-
.map((name) => name.slice(0, -1).toLowerCase());
253-
const migrated = await Promise.all(sites.map((site) => isHlx6Site(env, org, site)));
254-
return sites.filter((site, index) => migrated[index]);
261+
.map((name) => name.slice(0, -1).toLowerCase())
262+
.filter((site) => hasPermission(daCtx, site, 'read')
263+
|| hasDescendantPermission(daCtx, site, 'read'));
264+
const migrated = await Promise.allSettled(sites.map((site) => isHlx6Site(env, org, site)));
265+
return sites.filter((site, index) => {
266+
const result = migrated[index];
267+
if (result.status === 'rejected') {
268+
console.error('[hlx6] Org site lookup failed; omitting site', org, site, result.reason);
269+
return false;
270+
}
271+
return result.value;
272+
});
255273
} catch (e) {
256274
console.error('[hlx6] Invalid org source listing; using DA sites only', e.message);
257275
return [];
@@ -268,7 +286,7 @@ async function fetchHlx6OrgSites(req, env, org) {
268286
export async function listHlx6Org({ req, env, daCtx }) {
269287
const legacy = await getList({ env, daCtx });
270288
if (legacy.status !== 200) return daResp(legacy, daCtx);
271-
const hlx6Sites = new Set(await fetchHlx6OrgSites(req, env, daCtx.org));
289+
const hlx6Sites = new Set(await fetchHlx6OrgSites(req, env, daCtx));
272290
let items = JSON.parse(legacy.body).filter((item) => item.ext || !hlx6Sites.has(item.name));
273291
if (!daCtx.continuationToken) {
274292
const sites = [...hlx6Sites].map((site) => ({ path: `/${daCtx.org}/${site}`, name: site }));

‎src/utils/hlx6.js‎

Lines changed: 45 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,6 @@ export function parseDualWrites(value) {
9797
}
9898

9999
let dualWriteCache = { key: undefined, map: new Map() };
100-
const siteLookups = new WeakMap();
101100

102101
function getDualWrites(env) {
103102
const value = env?.HLX6_DUAL_WRITES;
@@ -114,22 +113,32 @@ function getDualWrites(env) {
114113
return dualWriteCache.map;
115114
}
116115

117-
async function detectHlx6Site(namespace, key) {
118-
const cached = await namespace.get(key);
119-
if (cached === 'hlx6' || cached === 'da') return cached === 'hlx6';
120-
if (cached !== null) throw new Error(`Invalid site backend for ${key}`);
116+
function parseBackend(value, key) {
117+
if (value === null) return undefined;
118+
const backend = value.trim().toLowerCase();
119+
if (backend === 'hlx6' || backend === 'da') return backend;
120+
throw new Error(`Invalid site backend for ${key}`);
121+
}
121122

123+
async function detectHlx6Site(namespace, key, hlxAdmin) {
124+
const cached = parseBackend(await namespace.get(key), key);
125+
if (cached !== undefined) return cached === 'hlx6';
126+
const base = (hlxAdmin || 'https://admin.hlx.page').replace(/\/+$/, '');
122127
const path = key.split('/').map(encodeURIComponent).join('/');
123-
const resp = await fetch(`https://admin.hlx.page/ping/${path}`, {
128+
const resp = await fetch(`${base}/ping/${path}`, {
124129
method: 'GET', redirect: 'manual', signal: AbortSignal.timeout(3000),
125130
});
126131
await resp.body?.cancel();
127-
// Unregistered DA sites return 404; transport/auth/server errors are not DA results.
132+
// Unregistered sites may be created later, so their DA result is short-lived.
128133
if (!resp.ok && resp.status !== 404) {
129134
throw new Error(`Site backend probe failed for ${key}: ${resp.status}`);
130135
}
131136
const migrated = resp.headers.has('x-api-upgrade-available');
132-
await namespace.put(key, migrated ? 'hlx6' : 'da');
137+
try {
138+
await namespace.put(key, migrated ? 'hlx6' : 'da', resp.status === 404 ? { expirationTtl: 300 } : undefined);
139+
} catch (e) {
140+
console.error('[hlx6] Failed to cache site backend', key, e.message);
141+
}
133142
return migrated;
134143
}
135144

@@ -152,7 +161,7 @@ export function getHlx6Target(env, org, site) {
152161

153162
/**
154163
* Resolves the shared site registry, probing only missing entries and excluding dual writes.
155-
* Only in-flight lookups are memoized so manual KV updates are not hidden by isolate caches.
164+
* Request-scoped I/O is never shared between Worker requests.
156165
* @returns {Promise<boolean>} Whether this site must use HLX6 instead of DA storage.
157166
*/
158167
export async function isHlx6Site(env, org, site) {
@@ -161,17 +170,33 @@ export async function isHlx6Site(env, org, site) {
161170
const namespace = env.DA_SITE_BACKENDS;
162171
if (!namespace) throw new Error('Missing DA_SITE_BACKENDS binding');
163172
const key = `${org}/${site}`.toLowerCase();
164-
let pending = siteLookups.get(namespace);
165-
if (!pending) {
166-
pending = new Map();
167-
siteLookups.set(namespace, pending);
168-
}
169-
if (!pending.has(key)) pending.set(key, detectHlx6Site(namespace, key));
170-
try {
171-
return await pending.get(key);
172-
} finally {
173-
pending.delete(key);
174-
}
173+
return detectHlx6Site(namespace, key, env.HLX_ADMIN);
174+
}
175+
176+
/**
177+
* Checks cached entries only; org browsing must not probe unknown sites to open its gate.
178+
* @returns {Promise<boolean>} Whether this org has a cached, non-dual-writing HLX6 site.
179+
*/
180+
export async function hasHlx6Sites(env, org) {
181+
if (!org) return false;
182+
const namespace = env.DA_SITE_BACKENDS;
183+
if (!namespace) throw new Error('Missing DA_SITE_BACKENDS binding');
184+
const prefix = `${org.toLowerCase()}/`;
185+
let cursor;
186+
do {
187+
// KV bulk reads accept at most 100 keys.
188+
// eslint-disable-next-line no-await-in-loop
189+
const page = await namespace.list({ prefix, limit: 100, cursor });
190+
const keys = page.keys.map(({ name }) => name);
191+
if (keys.length) {
192+
// eslint-disable-next-line no-await-in-loop
193+
const values = await namespace.get(keys);
194+
if ([...values].some(([key, value]) => parseBackend(value, key) === 'hlx6'
195+
&& !getHlx6Target(env, org, key.slice(prefix.length)))) return true;
196+
}
197+
cursor = page.list_complete ? undefined : page.cursor;
198+
} while (cursor);
199+
return false;
175200
}
176201

177202
/**

‎test/index.test.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,10 @@ describe('fetch', () => {
119119
api: 'list',
120120
org: 'kptdobe',
121121
key: '',
122+
aclCtx: {
123+
actionSet: new Set(),
124+
pathLookup: new Map([['acapt@adobe.com', [{ path: '/site/docs/**', actions: ['read'] }]]]),
125+
},
122126
}),
123127
},
124128
'../src/handlers/get.js': {
@@ -399,6 +403,31 @@ describe('Helix 6 request routing', () => {
399403
assert(dispatch.notCalled);
400404
});
401405

406+
it('rejects listings without read or descendant permission before checking the registry', async () => {
407+
env.DA_CONFIG = {
408+
get: async () => ({
409+
permissions: { data: [{ path: '/allowed/**', actions: 'read', groups: 'test@example.com' }] },
410+
}),
411+
};
412+
const resp = await hnd.fetch(request('/list/org/site'), env);
413+
assert.strictEqual(resp.status, 403);
414+
assert(env.DA_SITE_BACKENDS.get.notCalled);
415+
assert(bridge.notCalled);
416+
assert(dispatch.notCalled);
417+
});
418+
419+
it('allows readable descendants before resolving a migrated listing', async () => {
420+
env.DA_CONFIG = {
421+
get: async () => ({
422+
permissions: { data: [{ path: '/site/docs/**', actions: 'read', groups: 'test@example.com' }] },
423+
}),
424+
};
425+
const resp = await hnd.fetch(request('/list/org/site'), env);
426+
assert.strictEqual(resp.status, 200);
427+
assert(bridge.calledOnce);
428+
assert(env.DA_SITE_BACKENDS.get.calledWith('org/site'));
429+
});
430+
402431
it('serves sites cached as DA', async () => {
403432
const req = request('/source/org/site/file.html');
404433
env.DA_SITE_BACKENDS.get.withArgs('org/site').resolves('da');

‎test/routes/hlx6.test.js‎

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,12 @@ describe('Helix 6 compatibility bridge', () => {
2929
env = {
3030
AEM_API: 'https://api.example.com',
3131
DA_CONTENT: 'https://content.da.live',
32-
DA_SITE_BACKENDS: { get: sinon.stub().resolves('da') },
32+
DA_SITE_BACKENDS: {
33+
get: sinon.stub().callsFake(async (key) => (Array.isArray(key)
34+
? new Map(key.map((name) => [name, name === 'org/site' ? 'hlx6' : 'da']))
35+
: 'da')),
36+
list: sinon.stub().resolves({ keys: [{ name: 'org/site' }], list_complete: true }),
37+
},
3338
};
3439
env.DA_SITE_BACKENDS.get.withArgs('org/site').resolves('hlx6');
3540
fetchStub = sinon.stub(globalThis, 'fetch');
@@ -494,11 +499,14 @@ describe('Helix 6 compatibility bridge', () => {
494499
});
495500
});
496501

497-
it('discovers and caches a cold HLX6 site while listing an org', async () => {
498-
const values = new Map();
502+
it('discovers uncached sites once the org has a cached HLX6 site', async () => {
503+
const values = new Map([['org/known', 'hlx6']]);
499504
env.DA_SITE_BACKENDS = {
500-
get: async (key) => values.get(key) ?? null,
505+
get: async (key) => (Array.isArray(key)
506+
? new Map(key.map((name) => [name, values.get(name) ?? null]))
507+
: values.get(key) ?? null),
501508
put: async (key, value) => { values.set(key, value); },
509+
list: async () => ({ keys: [{ name: 'org/known' }], list_complete: true }),
502510
};
503511
const module = await esmock('../../src/routes/hlx6.js', {
504512
'../../src/routes/list.js': { default: async () => ({ status: 200, body: '[]' }) },
@@ -514,6 +522,38 @@ describe('Helix 6 compatibility bridge', () => {
514522
assert.strictEqual(values.get('org/newsite'), 'hlx6');
515523
});
516524

525+
it('does not call HLX6 for an org with no cached HLX6 sites', async () => {
526+
env.DA_SITE_BACKENDS.get.withArgs(['org/site']).resolves(new Map([['org/site', 'da']]));
527+
const module = await esmock('../../src/routes/hlx6.js', {
528+
'../../src/routes/list.js': { default: async () => ({ status: 200, body: '[]' }) },
529+
});
530+
const resp = await call('/list/org', {}, module.listHlx6Org);
531+
assert.deepStrictEqual(await resp.json(), []);
532+
assert(fetchStub.notCalled);
533+
});
534+
535+
it('keeps the DA listing when the registry gate is unavailable', async () => {
536+
env.DA_SITE_BACKENDS.list.rejects(new Error('KV unavailable'));
537+
const module = await esmock('../../src/routes/hlx6.js', {
538+
'../../src/routes/list.js': { default: async () => ({ status: 200, body: '[]' }) },
539+
});
540+
const resp = await call('/list/org', {}, module.listHlx6Org);
541+
assert.deepStrictEqual(await resp.json(), []);
542+
assert(fetchStub.notCalled);
543+
assert(console.error.called);
544+
});
545+
546+
it('keeps healthy HLX6 sites when another site lookup fails', async () => {
547+
env.DA_SITE_BACKENDS.get.withArgs('org/broken').rejects(new Error('Site lookup unavailable'));
548+
const module = await esmock('../../src/routes/hlx6.js', {
549+
'../../src/routes/list.js': { default: async () => ({ status: 200, body: '[]' }) },
550+
});
551+
fetchStub.resolves(new Response(JSON.stringify([{ name: 'site/' }, { name: 'broken/' }])));
552+
const resp = await call('/list/org', {}, module.listHlx6Org);
553+
assert.deepStrictEqual(await resp.json(), [{ path: '/org/site', name: 'site' }]);
554+
assert(console.error.called);
555+
});
556+
517557
it('filters HLX6 org sites by DA ACLs for descendant-only org readers', async () => {
518558
env.DA_CONFIG = {
519559
get: async () => ({
@@ -530,6 +570,7 @@ describe('Helix 6 compatibility bridge', () => {
530570
fetchStub.resolves(new Response(JSON.stringify([{ name: 'site/' }, { name: 'hlx6only/' }])));
531571
const resp = await call('/list/org', {}, module.listHlx6Org);
532572
assert.deepStrictEqual(await resp.json(), [{ path: '/org/site', name: 'site' }]);
573+
assert(!env.DA_SITE_BACKENDS.get.calledWith('org/hlx6only'));
533574
});
534575

535576
it('denies folder listings without read or descendant permission', async () => {

0 commit comments

Comments
 (0)