Skip to content

Commit 2da04b6

Browse files
kptdobeCopilot
andauthored
fix: route migrated content through the DA compatibility bridge (#34)
* fix: route migrated content through DA admin Prevent allowlists and image opt-outs from reading stale R2. Preserve legacy URL/auth handling and conditional metadata. Deploy the da-admin bridge first and synchronize migration lists. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * docs: document HLX6 content routing helpers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: harden HLX6 routing and restore 100% test coverage Normalize percent-encoded and dot path segments before migration checks, cache parsed migration lists, preserve CORS headers on error responses, only forward upstream content-length on HEAD, and cover all branches. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 388b90a commit 2da04b6

9 files changed

Lines changed: 470 additions & 19 deletions

File tree

‎README.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# DA Content
2+
3+
## Helix 6 compatibility
4+
5+
Configure `HLX6_MIGRATED_SITES` in the Cloudflare dashboard with the same
6+
`org/site` entries used by da-admin. Arrays, JSON-encoded arrays, and
7+
comma/newline-separated strings are accepted. Keep `HLX6_DUAL_WRITES` in sync
8+
as well: a dual-writing source site still uses normal DA routing.
9+
Malformed migration-variable JSON fails closed with `503` across the worker
10+
instead of risking fallback reads from R2.
11+
12+
For migrated sites, requests use the `daadmin` service binding before any
13+
direct-R2 allowlist or image opt-out. Deploy the da-admin read/save bridge
14+
first; this worker does not forward directly to api.aem.live or substitute a
15+
service credential.
16+
17+
Legacy content URLs retain lowercase/document/index normalization,
18+
`auth_token` cookie, Authorization header, query-token handling, and the local
19+
`.gimme_cookie` endpoint. GET/HEAD responses stream through the binding,
20+
preserving ETag, Last-Modified, cache controls and upstream errors. Conditional
21+
headers are forwarded. SVG download behavior and CORS remain on the DA host.
22+
23+
Unauthenticated requests can still fail: bypassing old public-R2 paths does
24+
not grant permission to read HLX6 authoring content. A failure never retries
25+
against R2. Source/config saves belong to da-admin; content-host mutations
26+
remain unsupported.
27+
28+
Neither migration variable is declared in the Wrangler vars block;
29+
`keep_vars = true` preserves dashboard values during deployment.
30+
31+
## Validation
32+
33+
Run `npm test` and `npm run lint`.

‎src/index.js‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { getCookie } from './cookie.js';
1616
import { get404, daResp, getRobots } from './responses/index.js';
1717
import getFromAdmin from './storage/admin.js';
1818
import { isEmbeddableAsset } from './storage/utils.js';
19+
import isHlx6Site from './utils/hlx6.js';
1920

2021
// https://www.aem.live/docs/security#backends-with-ip-filtering
2122
const HELIX_ADMIN_IP = '3.227.118.73';
@@ -49,23 +50,62 @@ function shouldGetFromStorage(env, req, pathname, org) {
4950
}
5051

5152
export default {
53+
/**
54+
* Routes migrated sites through admin before legacy R2 bypasses, keeping cookie endpoints local.
55+
* @param {Request} req Incoming content request.
56+
* @param {Object} env Worker bindings, storage settings and migration configuration.
57+
* @returns {Promise<Response>} Content response or explicit routing/configuration error.
58+
*/
5259
async fetch(req, env) {
5360
const url = new URL(req.url);
5461
const { pathname } = url;
5562

5663
if (pathname === '/favicon.ico') return get404();
5764
if (pathname === '/robots.txt') return getRobots();
5865

59-
const [, org, site, root] = url.pathname.split('/');
66+
let decodedPathname;
67+
try {
68+
decodedPathname = decodeURIComponent(pathname);
69+
} catch {
70+
return get404();
71+
}
72+
73+
const parts = decodedPathname.split('/').filter((part) => part !== '' && part !== '.');
74+
if (parts.includes('..')) return get404();
75+
76+
const [org, site, root] = parts;
6077

6178
if (root === '.gimme_cookie') {
6279
return getCookie(req);
6380
}
6481

6582
if (!org || !site) return get404();
6683

67-
if (shouldGetFromStorage(env, req, pathname, org)) {
68-
return getFromStorage(pathname, env);
84+
let migrated;
85+
try {
86+
migrated = isHlx6Site(env, org, site);
87+
} catch (e) {
88+
// eslint-disable-next-line no-console
89+
console.error('[hlx6] Migration routing configuration error', e.message);
90+
const msg = 'Migration routing configuration error';
91+
const resp = daResp({
92+
status: 503,
93+
body: req.method === 'HEAD' ? undefined : msg,
94+
contentType: 'text/plain',
95+
});
96+
resp.headers.set('x-error', msg);
97+
resp.headers.set('access-control-expose-headers', 'x-error');
98+
resp.headers.set('cache-control', 'private, no-store');
99+
return resp;
100+
}
101+
102+
if (migrated) return getFromAdmin(req, env);
103+
104+
const normalizedOrg = org.toLowerCase();
105+
const normalizedPath = `/${parts.join('/')}${decodedPathname.endsWith('/') ? '/' : ''}`;
106+
107+
if (shouldGetFromStorage(env, req, normalizedPath.toLowerCase(), normalizedOrg)) {
108+
return getFromStorage(normalizedPath, env);
69109
}
70110

71111
return getFromAdmin(req, env);

‎src/responses/index.js‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ function isSvgContentType(contentType) {
1818
export function daResp({ body, status, contentType }) {
1919
const headers = new Headers();
2020
headers.append('Access-Control-Allow-Origin', '*');
21-
headers.append('Access-Control-Allow-Methods', 'GET, OPTIONS');
22-
headers.append('Access-Control-Allow-Headers', 'authorization');
21+
headers.append('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
22+
headers.append('Access-Control-Allow-Headers', 'authorization, if-match, if-none-match');
2323

2424
if (contentType) headers.append('Content-Type', contentType);
2525
if (isSvgContentType(contentType)) headers.append('Content-Disposition', 'attachment');
2626

27-
return new Response(body, { status, headers });
27+
return new Response(status === 204 || status === 304 ? undefined : body, { status, headers });
2828
}
2929

3030
export function get404() {

‎src/storage/admin.js‎

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,29 @@ function canonicalizePathname(pathname) {
7272
return canonicalized;
7373
}
7474

75+
/**
76+
* Canonicalizes legacy content URLs and streams GET/HEAD through the daadmin service binding.
77+
* Preserves caller cookie/header/query-token auth, conditions, metadata, errors and SVG handling.
78+
* OPTIONS remains local; transport failures return 503 without falling back to R2.
79+
* @param {Request} req Legacy content request.
80+
* @param {{daadmin: {fetch: typeof fetch}}} env Admin service binding.
81+
* @returns {Promise<Response>} Legacy-host content/metadata response or explicit error.
82+
*/
7583
export default async function getFromAdmin(req, env) {
7684
if (req.method === 'OPTIONS') {
7785
return daResp({ body: '', status: 200 });
7886
}
7987

80-
if (req.method !== 'GET') {
81-
return new Response('', { status: 405 });
88+
if (req.method !== 'GET' && req.method !== 'HEAD') {
89+
return daResp({ body: '', status: 405 });
8290
}
8391

8492
let { pathname } = new URL(req.url);
93+
try {
94+
pathname = decodeURIComponent(pathname);
95+
} catch {
96+
return daResp({ body: '', status: 404 });
97+
}
8598
pathname = canonicalizePathname(pathname);
8699

87100
// construct request to admin
@@ -92,22 +105,30 @@ export default async function getFromAdmin(req, env) {
92105
if (authHeader) {
93106
reqHeaders.set('authorization', authHeader);
94107
}
108+
['if-match', 'if-none-match'].forEach((name) => {
109+
if (req.headers.has(name)) reqHeaders.set(name, req.headers.get(name));
110+
});
95111

96112
try {
97113
const resp = await env.daadmin.fetch(url, {
114+
method: req.method,
98115
headers: reqHeaders,
99116
});
100117
const { status, headers } = resp;
101118
const contentType = headers.get('content-type');
102-
return daResp({ body: resp.body, status, contentType });
119+
const result = daResp({ body: req.method === 'HEAD' ? undefined : resp.body, status, contentType });
120+
const forwardedHeaders = ['etag', 'last-modified', 'cache-control', 'x-error', 'x-error-code', 'retry-after'];
121+
if (req.method === 'HEAD') forwardedHeaders.push('content-length');
122+
forwardedHeaders.forEach((name) => {
123+
if (headers.has(name)) result.headers.set(name, headers.get(name));
124+
});
125+
result.headers.set('access-control-expose-headers', 'ETag, Last-Modified, x-error, x-error-code, Retry-After');
126+
return result;
103127
} catch (e) {
104128
const msg = 'Failed to fetch from admin';
105-
return new Response(
106-
'',
107-
{
108-
status: 503,
109-
headers: { 'x-error': msg },
110-
},
111-
);
129+
const resp = daResp({ body: '', status: 503 });
130+
resp.headers.set('x-error', msg);
131+
resp.headers.set('access-control-expose-headers', 'x-error');
132+
return resp;
112133
}
113134
}

‎src/utils/hlx6.js‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/*
2+
* Copyright 2026 Adobe. All rights reserved.
3+
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License. You may obtain a copy
5+
* of the License at http://www.apache.org/licenses/LICENSE-2.0
6+
*
7+
* Unless required by applicable law or agreed to in writing, software distributed under
8+
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9+
* OF ANY KIND, either express or implied. See the License for the specific language
10+
* governing permissions and limitations under the License.
11+
*/
12+
/**
13+
* Parses dashboard arrays, JSON arrays or comma/newline-separated migration entries.
14+
* @param {string[]|string|undefined} value Migration-variable value.
15+
* @param {string} name Variable name used in configuration errors.
16+
* @returns {unknown[]} Parsed entries, or an empty array for an unset variable.
17+
* @throws {Error} If a provided value has an unsupported type or malformed JSON array.
18+
*/
19+
function entries(value, name) {
20+
if (!value) return [];
21+
if (Array.isArray(value)) return value;
22+
if (typeof value !== 'string') {
23+
throw new Error(`Invalid ${name}`);
24+
}
25+
const trimmed = value.trim();
26+
if (trimmed.startsWith('{')) {
27+
throw new Error(`Invalid ${name}`);
28+
}
29+
if (!trimmed.startsWith('[')) return value.split(/[,\n]/);
30+
try {
31+
return JSON.parse(trimmed);
32+
} catch {
33+
throw new Error(`Invalid JSON in ${name}`);
34+
}
35+
}
36+
37+
/**
38+
* Normalizes a single org/site entry, ignoring values that do not identify exactly two segments.
39+
* @param {string} value Candidate org/site entry.
40+
* @returns {string|undefined} Lowercase org/site key, or undefined for an invalid entry.
41+
*/
42+
function orgSite(value) {
43+
const parts = value.trim().toLowerCase().split('/').filter(Boolean);
44+
return parts.length === 2 ? parts.join('/') : undefined;
45+
}
46+
47+
let migratedCache = { raw: undefined, sites: new Set() };
48+
let dualWriteCache = { raw: undefined, sources: new Set() };
49+
50+
/**
51+
* Parses and caches migrated org/site entries keyed by the raw configuration value.
52+
* @param {string[]|string|undefined} raw Raw HLX6_MIGRATED_SITES configuration.
53+
* @returns {Set<string>} Normalized migrated org/site keys.
54+
* @throws {Error} If HLX6_MIGRATED_SITES cannot be parsed.
55+
*/
56+
function getMigratedSites(raw) {
57+
if (migratedCache.raw === raw) return migratedCache.sites;
58+
const sites = new Set();
59+
entries(raw, 'HLX6_MIGRATED_SITES').forEach((entry) => {
60+
if (typeof entry === 'string' && !entry.includes('->')) {
61+
const parsed = orgSite(entry);
62+
if (parsed) sites.add(parsed);
63+
}
64+
});
65+
migratedCache = { raw, sites };
66+
return sites;
67+
}
68+
69+
/**
70+
* Parses and caches valid dual-write source entries keyed by the raw configuration value.
71+
* @param {string[]|string|undefined} raw Raw HLX6_DUAL_WRITES configuration.
72+
* @returns {Set<string>} Normalized dual-write source org/site keys.
73+
* @throws {Error} If HLX6_DUAL_WRITES cannot be parsed.
74+
*/
75+
function getDualWriteSources(raw) {
76+
if (dualWriteCache.raw === raw) return dualWriteCache.sources;
77+
const sources = new Set();
78+
entries(raw, 'HLX6_DUAL_WRITES').forEach((entry) => {
79+
if (typeof entry !== 'string') return;
80+
const [from, to, ...rest] = entry.split('->');
81+
const source = orgSite(from);
82+
if (!rest.length && source && (to === undefined || !!orgSite(to))) {
83+
sources.add(source);
84+
}
85+
});
86+
dualWriteCache = { raw, sources };
87+
return sources;
88+
}
89+
90+
/**
91+
* Selects migrated sources for admin routing while excluding valid dual-write source entries.
92+
* A mapped dual-write target does not exempt that target from migrated routing.
93+
* @param {Object} env Worker migration configuration.
94+
* @param {string[]|string} [env.HLX6_MIGRATED_SITES] Migrated org/site entries.
95+
* @param {string[]|string} [env.HLX6_DUAL_WRITES] Source entries with optional target mappings.
96+
* @param {string} org Content organization.
97+
* @param {string} site Content site.
98+
* @returns {boolean} Whether requests must use admin rather than direct R2.
99+
* @throws {Error} If either configured migration list cannot be parsed.
100+
*/
101+
export default function isHlx6Site(env, org, site) {
102+
const key = `${org}/${site}`.toLowerCase();
103+
const migrated = getMigratedSites(env.HLX6_MIGRATED_SITES);
104+
const dualWrite = getDualWriteSources(env.HLX6_DUAL_WRITES);
105+
return migrated.has(key) && !dualWrite.has(key);
106+
}

0 commit comments

Comments
 (0)