Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
13 changes: 13 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Contributor instructions

## HLX6 compatibility

Every new feature or API endpoint must explicitly handle requests for projects
(`org/site`) backed by HLX6. Use the existing
[site-backend resolver](./src/utils/hlx6.js) and preserve authentication and ACL checks.

- Forward supported operations through the existing HLX6 compatibility bridge.
- Return HTTP `410 Gone` when the operation is unsupported on HLX6.
- Never fall back to legacy DA/R2 storage for an unsupported HLX6 operation or
after forwarding fails.
- Add focused tests for the chosen HLX6 behavior and preserve legacy DA behavior.
103 changes: 86 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,40 @@ Browse to `http://localhost:8787/list` to ensure you see the expected buckets.
1. You can make your own buckets tied to your own Cloudflare account or you can request a `.dev.vars` file.
2. Cloudflare KV, which is used for org properties and session login info is locally stored when developing locally. You will need to make your own local KVs to test against.

### Development requirements

Every new feature or API endpoint must follow the
[HLX6 compatibility requirements](./AGENTS.md#hlx6-compatibility): forward
supported calls for HLX6-backed projects or return `410 Gone` when unsupported.

### Helix 6 request handling

Sites listed in `HLX6_MIGRATED_SITES`, an array of `org/site` entries (or a
JSON-encoded array or comma/newline-separated string), use a synchronous
compatibility bridge to `AEM_API` (`https://api.aem.live` by default). The site
check is local; no network probe is made.
Both da-admin and da-content resolve sites through the shared `DA_SITE_BACKENDS`
KV binding. Keys are lowercase `org/site`; values are the strings `da` or `hlx6`
(case and surrounding whitespace are normalized when reading).
An `hlx6` site uses a synchronous compatibility bridge to `AEM_API`
(`https://api.aem.live` by default).

On a cache miss, the worker makes an unauthenticated GET to
`https://admin.hlx.page/ping/{org}/{site}` with a 3s timeout. Set `HLX_ADMIN`
to override the probe base URL per environment (for example in `.dev.vars` or
the Cloudflare dashboard); local integration tests use the mock server.
Presence of `x-api-upgrade-available` selects HLX6. This is a source-bus
configuration heuristic, including overlays, **not proof of completed cutover**.
Explicit registry entries override it. Successful responses without that header
select DA. Successful probe results persist without expiration; 404 results
expire after **300 seconds** so not-yet-created sites can be detected later.
Cache hits do not ping. Concurrent cold requests own their I/O independently;
KV does not guarantee a single probe globally.
Redirects, auth/rate-limit/server errors, timeouts, invalid registry values, and
KV read failures fail the request rather than assuming DA or writing legacy
storage. Failed KV writes are logged without discarding the known probe result.
Subsequent requests read KV again.

Site listings require read or readable-descendant permission before backend
detection. The 404 expiry limits retention, not traffic: signed-in users of open
orgs, and public da-content requests, can still generate cold probes. This is
not a rate limiter or an org-existence check.

The bridge supports:

Expand All @@ -58,9 +86,14 @@ The bridge supports:
filtering. HLX6 listings are unpaginated; a legacy continuation token on a
migrated site's listing is rejected.
- Org GET listings, merging legacy DA sites with the org's bridged HLX6 sites:
entries of `GET /{org}/source/` (caller token, 3s timeout) that are also in
`HLX6_MIGRATED_SITES`, filtered by DA ACLs. If the HLX6 listing fails
(outage, timeout, missing HLX6 role), the DA listing is still returned.
discovery runs only if the registry already contains a non-dual-writing HLX6
site for that org. The gate uses paginated KV listing and bulk reads of at most
100 keys, without pinging. Entries of `GET /{org}/source/` (caller token,
3s timeout) are filtered by DA ACLs before resolving their backends. Unknown
sites can then be discovered. An entirely uncached HLX6-only org requires a
direct site request or a seeded registry entry before discovery is enabled.
Failed individual lookups are logged and omitted while healthy sites remain;
if discovery is unavailable, the DA listing is still returned.
Only the first legacy page adds HLX6 sites; subsequent pages preserve the
DA continuation token without repeating them.
- Site editor-config GET and multipart PUT/POST (`config` field), converting
Expand Down Expand Up @@ -89,25 +122,61 @@ limits, and empty-document restore points are not identical to DA.

Org config, authentication, logout, and CORS preflight remain available locally.
The bridge does not change the HLX6 editor's org-config inheritance behavior.
Sites configured for dual write in `HLX6_DUAL_WRITES` retain normal DA behavior
during migration, even if they also appear in `HLX6_MIGRATED_SITES`.
In da-admin, sites configured for dual write in `HLX6_DUAL_WRITES` retain normal
DA behavior during migration, even if the registry identifies them as `hlx6`.
The dual-write override does not change the stored backend.

The companion da-content change routes migrated sites through its `daadmin`
binding before direct-R2 allowlists and asset opt-outs. Configure the same
migration variables on both workers, and deploy the da-admin bridge first.
binding before direct-R2 allowlists and asset opt-outs. It follows the shared
registry only and does not read `HLX6_DUAL_WRITES`. Deploy the da-admin bridge first.
Content path/cookie handling remains on the legacy host; no browser redirect
or Library URL rewrite is required for supported source reads.

### Helix 6 migration (dual write)
Sites listed in the `HLX6_DUAL_WRITES` env variable are being migrated to Helix 6. Every successful modification on those sites (source create/update/delete, folder creation, copy, move, version creation) is also propagated, in the background, to the Helix 6 source bus at `AEM_API` (`https://api.aem.live`) using the caller's IMS token. Failures are logged but do not affect the DA response.

Manage both `HLX6_MIGRATED_SITES` and `HLX6_DUAL_WRITES` in the Cloudflare dashboard.
Neither is declared in any `wrangler.toml` vars block: `keep_vars = true`
preserves dashboard values, but an explicit declaration would override them on
deployment. Local development can set these variables in `.dev.vars` as needed.
Manage `HLX6_DUAL_WRITES` in the Cloudflare dashboard.
It is not declared in any `wrangler.toml` vars block: `keep_vars = true`
preserves its dashboard value, but an explicit declaration would override it on
deployment. Local development can set this variable in `.dev.vars` as needed.
Rename the previous `HLX6_MIGRATION_SITES` dashboard variable to `HLX6_DUAL_WRITES`
when deploying this change. Moving a site out of dual write requires adding it
to `HLX6_MIGRATED_SITES` and removing its source entry from `HLX6_DUAL_WRITES`.
when deploying this change.

#### Site registry and cutover

Production uses the `DA_SITE_BACKENDS` namespace
(`90c6a793da054676b11134d647f0aeaf`). Stage and CI use
`DA_SITE_BACKENDS_STAGE` (`624b26551dcf4fe3bd31a08e70cda86f`).
Both workers bind the appropriate namespace as `DA_SITE_BACKENDS`. Local dev
and integration tests use emulated KV, not remote registry writes.

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

Before starting dual write, explicitly set the site's registry entry to `da`.
This keeps da-content on legacy routing even if a cold ping would identify the
site as HLX6. Manage `HLX6_DUAL_WRITES` only on da-admin.

To cut over a site, pause traffic for that site and drain in-flight requests
(including cold probes), then update its registry entry:

```sh
npx wrangler kv key put --binding DA_SITE_BACKENDS --env production --remote "owner/site" hlx6
```

Use `--env stage` for staging. Remove the site's source entry from
`HLX6_DUAL_WRITES` in da-admin when ending dual write. KV is eventually
consistent: cached values and cached misses can remain visible for 60 seconds
or more. Keep traffic paused until propagation and both workers' routing are
verified; do not treat a successful KV write as an instantaneous cutover.
Probes already in flight can overwrite a manual update, hence the drain step.
Setting a value to `da` explicitly selects legacy storage. Deleting a key
allows the next request to probe again.

Entries are either:
- `org/site`: the same org/site on Helix 6
Expand Down
19 changes: 9 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import headHandler from './handlers/head.js';
import getHandler from './handlers/get.js';
import postHandler from './handlers/post.js';
import deleteHandler from './handlers/delete.js';
import { hasHlx6Sites, initHlx6, isHlx6Site } from './utils/hlx6.js';
import { initHlx6, isHlx6Site } from './utils/hlx6.js';
import { hasDescendantPermission } from './utils/auth.js';
import hlx6Handler, { listHlx6Org } from './routes/hlx6.js';

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

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

// `key` is org-stripped (daCtx.key), so version storage appears as the
// segment `{repo}/.da-versions/...`, not a leading `.da-versions`. Block the
Expand All @@ -76,10 +75,10 @@ export default {
try {
// The key also identifies bare site roots, where daCtx.site is undefined.
const [site] = (key || '').split('/');
if (api !== 'login' && api !== 'logout' && isHlx6Site(env, org, site)) {
if (api !== 'login' && api !== 'logout' && await isHlx6Site(env, org, site)) {
return await hlx6Handler({ req, env, daCtx });
}
if (api === 'list' && org && !key && req.method === 'GET' && hasHlx6Sites(env, org)) {
if (api === 'list' && org && !key && req.method === 'GET') {
return await listHlx6Org({ req, env, daCtx });
}

Expand Down
2 changes: 1 addition & 1 deletion src/routes/copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default async function copyHandler({ req, env, daCtx }) {
if (details.error) return details.error;
if (!hasPermission(daCtx, details.source, 'read')
|| !hasPermission(daCtx, details.destination, 'write')) return { status: 403 };
if (isHlx6Site(env, daCtx.org, details.destination.split('/')[0])) return HLX6_GONE;
if (await isHlx6Site(env, daCtx.org, details.destination.split('/')[0])) return HLX6_GONE;
const resp = await copyObject(env, daCtx, details, false);
syncCopy({
req, env, daCtx, details, resp,
Expand Down
33 changes: 26 additions & 7 deletions src/routes/hlx6.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
* governing permissions and limitations under the License.
*/
import daResp from '../utils/daResp.js';
import { DEFAULT_AEM_API, HLX6_GONE, isHlx6Site } from '../utils/hlx6.js';
import {
DEFAULT_AEM_API, HLX6_GONE, hasHlx6Sites, isHlx6Site,
} from '../utils/hlx6.js';
import { hasDescendantPermission, hasPermission } from '../utils/auth.js';
import { FORM_TYPES } from '../utils/constants.js';
import { sourceRespObject } from '../helpers/source.js';
Expand Down Expand Up @@ -227,14 +229,21 @@ async function listSource({ req, env, daCtx }) {

/**
* Lists the org's bridged HLX6 sites: entries of `GET /{org}/source/` (caller token) that
* are also in HLX6_MIGRATED_SITES, so every listed site opens through the bridge.
* resolved as HLX6 in the shared site registry, so every listed site opens through the bridge.
* Best effort with a short timeout: failures yield no sites so DA org browsing keeps working.
* @param {Request} req Legacy request carrying the caller credentials.
* @param {Env} env Worker bindings and API base URL.
* @param {string} org DA organization name.
* @param {DaCtx} daCtx DA organization and listing permissions.
* @returns {Promise<string[]>} Lowercase bridged site names.
*/
async function fetchHlx6OrgSites(req, env, org) {
async function fetchHlx6OrgSites(req, env, daCtx) {
const { org } = daCtx;
try {
if (!await hasHlx6Sites(env, org)) return [];
} catch (e) {
console.error('[hlx6] Org site registry unavailable; using DA sites only', e.message);
return [];
}
const upstream = await requestHlx6(req, env, `${encodeURIComponent(org)}/source/`, {
method: 'GET', timeout: ORG_LIST_TIMEOUT,
});
Expand All @@ -246,11 +255,21 @@ async function fetchHlx6OrgSites(req, env, org) {
try {
const items = await upstream.json();
if (!Array.isArray(items)) throw new Error('Expected a source listing array');
return items
const sites = items
.map((item) => item?.name)
.filter((name) => typeof name === 'string' && /^[^/.]+\/$/.test(name))
.map((name) => name.slice(0, -1).toLowerCase())
.filter((site) => isHlx6Site(env, org, site));
.filter((site) => hasPermission(daCtx, site, 'read')
|| hasDescendantPermission(daCtx, site, 'read'));
const migrated = await Promise.allSettled(sites.map((site) => isHlx6Site(env, org, site)));
return sites.filter((site, index) => {
const result = migrated[index];
if (result.status === 'rejected') {
console.error('[hlx6] Org site lookup failed; omitting site', org, site, result.reason);
return false;
}
return result.value;
});
} catch (e) {
console.error('[hlx6] Invalid org source listing; using DA sites only', e.message);
return [];
Expand All @@ -267,7 +286,7 @@ async function fetchHlx6OrgSites(req, env, org) {
export async function listHlx6Org({ req, env, daCtx }) {
const legacy = await getList({ env, daCtx });
if (legacy.status !== 200) return daResp(legacy, daCtx);
const hlx6Sites = new Set(await fetchHlx6OrgSites(req, env, daCtx.org));
const hlx6Sites = new Set(await fetchHlx6OrgSites(req, env, daCtx));
let items = JSON.parse(legacy.body).filter((item) => item.ext || !hlx6Sites.has(item.name));
if (!daCtx.continuationToken) {
const sites = [...hlx6Sites].map((site) => ({ path: `/${daCtx.org}/${site}`, name: site }));
Expand Down
2 changes: 1 addition & 1 deletion src/routes/move.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default async function moveRoute({ req, env, daCtx }) {
if (details.error) return details.error;
if (!hasPermission(daCtx, details.source, 'write')
|| !hasPermission(daCtx, details.destination, 'write')) return { status: 403 };
if (isHlx6Site(env, daCtx.org, details.destination.split('/')[0])) return HLX6_GONE;
if (await isHlx6Site(env, daCtx.org, details.destination.split('/')[0])) return HLX6_GONE;
const resp = await moveObject(env, daCtx, details);
syncMove({
req, env, daCtx, details, resp,
Expand Down
Loading