diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 4688d27b..9477dca9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -45,3 +45,7 @@ contain. - Kubernetes/IaC security coverage remains a follow-up design lane for any future `infra/` or container packaging surface. +- Clearfolio artifact redirects trust only the configured provider origin + unless `CLEARFOLIO_ARTIFACT_ORIGINS` lists additional exact HTTPS origins. + Cross-origin `artifactToken` values stay on the returned origin and are + never transplanted into the Clearfolio viewer. diff --git a/CHANGELOG.md b/CHANGELOG.md index 665009f3..50c87de3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,12 +29,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 and rejected cross-origin, credential-bearing, or fragmented artifact links until an explicit reviewed artifact-origin allowlist is configured by a later slice. +- Restricted hosted Clearfolio artifact redirects to the provider origin by + default; optional `CLEARFOLIO_ARTIFACT_ORIGINS` entries must be exact HTTPS + origins (`URL.origin` or that origin plus `/`), so scheme/host/port changes, + credentials, fragments, protocol-relative lookalikes, and unapproved + cross-origin links fail closed while approved cross-origin tokens remain bound + to the origin that issued them. - Bounded hosted Clearfolio calls to non-redirecting 15-second requests and 256 KiB streamed JSON responses, composed caller cancellation with the provider budget, and validated document metadata/bytes and provider job IDs before allocation, persistence, or URL construction. -- Preserved Clearfolio provider timeouts that occur while streaming a status - response so attachment-refresh timeout metrics remain accurate. - Made `SCOPEWEAVE_JWT_SECRET` mandatory at startup and rejected weak or unexpanded placeholder values so production deployments fail closed. - Neutralized audit-log CSV formulas even when executable prefixes are hidden diff --git a/README.md b/README.md index 6340c1f4..8b8085e7 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,10 @@ Docker: set a **persistent** `SCOPEWEAVE_JWT_SECRET` first, then run `docker com | `OIDC_ISSUER/CLIENT_ID/CLIENT_SECRET/REDIRECT_URI` | Real SSO IdP (mock when unset) | | `STRIPE_SECRET_KEY` | Real checkout (mock URL when unset) | | `SCOPEWEAVE_RATE_LIMIT_MAX` (+`_WINDOW_MS`) | Opt-in per-IP rate limiting | -| `SCOPEWEAVE_DEV=1` | Dev-only endpoints (activate-pro) | +| `SCOPEWEAVE_DEV=1` | Dev-only endpoints (activate-pro, loopback Clearfolio HTTP, in-memory Clearfolio adapter when no provider URL exists). Never set in production. | +| `CLEARFOLIO_URL` | Production 산출물 viewer origin (HTTPS). Unset fails closed unless `SCOPEWEAVE_DEV=1`. | +| `CLEARFOLIO_HMAC_SECRET` | Tenant-claim HMAC secret (at least 32 non-whitespace characters) when a provider URL is set. | +| `CLEARFOLIO_ARTIFACT_ORIGINS` | Optional comma-separated exact HTTPS artifact origins. Unset trusts only `CLEARFOLIO_URL`. Empty or malformed values fail closed. | ## Verification diff --git a/docs/api.md b/docs/api.md index 1c668425..b3d51d31 100644 --- a/docs/api.md +++ b/docs/api.md @@ -90,8 +90,10 @@ credentials never reach the browser. HWP/HWPX are rejected (Clearfolio policy). | `GET` | `/api/projects/:id/attachments/:aid/view` | 302 → signed artifact URL (`?token=` for new-tab opens) | | `DELETE` | `/api/projects/:id/attachments/:aid` | Uploader or manage | -Env: `CLEARFOLIO_URL` (+ optional `CLEARFOLIO_HMAC_SECRET` for gateway-signed -tenant claims). Unset → a built-in mock converter (dev/test only). +Env: `CLEARFOLIO_URL` plus `CLEARFOLIO_HMAC_SECRET` for production conversion. +Optional `CLEARFOLIO_ARTIFACT_ORIGINS` adds reviewed HTTPS CDN/object-store +origins; unset trusts only the Clearfolio origin. An unset URL is not a +successful converter: the in-memory mock exists only with `SCOPEWEAVE_DEV=1`. ## Comments (코멘트) diff --git a/docs/deploy.md b/docs/deploy.md index cd08ca9a..690ee4f3 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -41,6 +41,7 @@ persists the database in the `scopeweave-data` volume. | `ORCHESTRATOR_TOKEN` | with URL | Required bearer token for the configured contextual-orchestrator service (`CONTEXTUAL_ORCHESTRATOR_TOKEN`). | | `CLEARFOLIO_URL` | for production 산출물 viewer | Root Clearfolio service origin. Production requires HTTPS and rejects credentials, paths, query strings, and fragments. When absent in production, document conversion/viewing is unavailable rather than simulated. | | `CLEARFOLIO_HMAC_SECRET` | with URL | Required tenant-claim HMAC secret; must contain at least 32 non-whitespace characters and match Clearfolio's configured verifier secret. | +| `CLEARFOLIO_ARTIFACT_ORIGINS` | optional with URL | Comma-separated exact HTTPS artifact origins (scheme, host, optional non-default port). Leave unset to trust only `CLEARFOLIO_URL`. Empty, whitespace-only, HTTP, credentialed, path, query, fragment, or non-canonical entries fail closed before any provider call. | | `SCOPEWEAVE_ATTACHMENT_STATUS_CONCURRENCY` | no (default 8, maximum 32) | Maximum concurrent Clearfolio status lookups during one attachment-list request. Invalid values fall back to 8; values above 32 are clamped. | | `SCOPEWEAVE_ATTACHMENT_STATUS_TIMEOUT_MS` | no (default 3000, maximum 30000) | Hard caller-side timeout for each Clearfolio status lookup. The AbortSignal is also forwarded downstream. | | `SCOPEWEAVE_ATTACHMENT_STATUS_BUDGET_MS` | no (default 5000, maximum 60000) | Wall-clock budget for the entire best-effort refresh pass. Work not started before the deadline is deferred to a later list request. | @@ -61,6 +62,14 @@ Keep credentials in the dedicated HMAC secret setting rather than URL userinfo, and do not configure a path, query string, or fragment. The adapter constructs its own versioned API paths from the validated origin. +Artifact links returned by Clearfolio are untrusted until they match the +provider origin or an origin listed in `CLEARFOLIO_ARTIFACT_ORIGINS`. If +Clearfolio serves files from a reviewed CDN or object store, add only that +origin, for example `https://artifacts.example.com`. Do not put signed paths, +object keys, or tokens in the setting. Unset keeps the least-privilege default: +only the Clearfolio origin is trusted, and a cross-origin `artifactToken` is +never copied into the viewer URL. + Every hosted Clearfolio request is non-redirecting and has a hard 15-second adapter budget; attachment status lookups compose that budget with the caller's own cancellation signal. Successful provider responses must be diff --git a/docs/doctoring/clearfolio-artifact-origin-trust.md b/docs/doctoring/clearfolio-artifact-origin-trust.md new file mode 100644 index 00000000..a48bf8cc --- /dev/null +++ b/docs/doctoring/clearfolio-artifact-origin-trust.md @@ -0,0 +1,58 @@ +# Clearfolio artifact-origin trust boundary + +## Decision + +ScopeWeave treats every artifact link returned by Clearfolio as untrusted provider data. The configured `CLEARFOLIO_URL` origin is the default artifact trust boundary. A production operator may add reviewed CDN or object-storage origins through `CLEARFOLIO_ARTIFACT_ORIGINS`, but each entry must be an origin only: HTTPS scheme, host, and optional non-default port, with no credentials, path, query, fragment, or empty comma-separated entry. + +This slice is deliberately narrower than the complete Clearfolio production-adapter program in issue #489. It does not claim that provider DNS/IP authorization, artifact content validation, retention, or all operational acceptance work is complete. It closes the redirect-origin and token-confusion boundary on top of the provider-response controls owned by the parent PR. + +## Why exact origins + +RFC 6454 defines an origin around scheme, host, and port. Comparing canonical URL origins therefore keeps `https://cdn.example`, `https://cdn.example:8443`, and HTTP variants in distinct trust domains instead of relying on string-prefix matching. The WHATWG URL Standard supplies the parser and serialization semantics used by Node's `URL` implementation, including explicit username/password and fragment components. + +The adapter uses a positive allowlist rather than accepting any syntactically valid HTTPS URL. OWASP's SSRF guidance recommends allowlisting known destinations and disabling or tightly validating redirects when the intended service set is known. Although ScopeWeave is redirecting a browser to a provider-selected artifact rather than issuing a second server-side fetch, the same positive-trust principle prevents an untrusted provider response from turning the application into an arbitrary external redirector. + +## Runtime contract + +1. `CLEARFOLIO_ARTIFACT_ORIGINS` is optional. When absent, only the validated Clearfolio provider origin is trusted. +2. When present, the value is a comma-separated list of canonical HTTPS origins. Whitespace around entries is ignored. Empty values, whitespace-only values, and empty comma-separated entries are rejected. After parsing, each trimmed entry must equal `URL.origin` or that origin plus a single trailing `/`, so default-port `:443`, empty fragments, empty userinfo, and path-normalized lookalikes cannot sneak in. +3. Any malformed entry, HTTP entry, URL credential, path, query, fragment, or non-canonical origin produces `ClearfolioConfigurationError` with stable code `clearfolio_artifact_origins_invalid` before the artifact-link provider request is sent. +4. Provider-returned artifact URLs must still satisfy the existing HTTP/HTTPS and downgrade rules, must contain no credentials or fragment, and must resolve to the provider origin or an explicitly configured artifact origin. Protocol-relative links, backslash-normalized protocol-relative paths, and userinfo-as-host URLs inherit a foreign origin and are rejected unless that origin is explicitly allowlisted. +5. A same-origin `artifactToken` may be translated into the trusted Clearfolio viewer route. A token on an approved cross-origin artifact URL remains on that returned URL; ScopeWeave never transplants it into the provider-origin viewer. +6. Exact origin comparison includes the effective port. Approving `https://cdn.example:8443` does not approve `https://cdn.example`. + +## Operator action + +If Clearfolio returns artifacts from a separate reviewed CDN or object-storage service, configure only that service origin, for example: + +```text +CLEARFOLIO_ARTIFACT_ORIGINS=https://artifacts.example.com,https://archive.example.com:8443 +``` + +Do not place signed paths, object keys, tokens, credentials, query strings, or fragments in this setting. If no cross-origin artifact service is required, leave the variable unset; the provider origin remains the least-privilege default. + +## Verification contract + +`tests/unit/clearfolio-artifact-origin.test.mjs` exercises the production adapter with real `URL` parsing and a bounded mocked provider response. It proves: + +- cross-origin HTTPS artifacts fail by default; +- protocol-relative, backslash-normalized, and userinfo-as-host links do not inherit the provider origin; +- same-origin relative artifacts continue to resolve against the provider; +- an explicitly approved origin succeeds only for the same scheme/host/port identity; +- approved cross-origin `artifactToken` values remain on the approved origin; +- credentials and fragments are rejected on provider and approved origins; +- malformed, HTTP, credentialed, path-, query-, fragment-bearing, non-canonical, empty, and whitespace-only configuration fails before any provider transport. + +The test is registered in both the normal unit suite and the production coverage cases so changes to this boundary cannot silently bypass repository coverage evidence. + +## Failure and rollback + +Configuration failure is fail-closed and limited to the artifact-link capability; it does not broaden trust or silently fall back to arbitrary URLs. Rollback removes the additional-origin feature and returns to provider-origin-only artifact redirects. Do not roll back by permitting arbitrary HTTPS destinations or by moving cross-origin tokens into a trusted same-origin viewer URL. + +## References + +Barth, A. (2011). *The web origin concept* (RFC 6454). Internet Engineering Task Force. https://doi.org/10.17487/RFC6454 + +Open Worldwide Application Security Project. (n.d.). *Server side request forgery prevention cheat sheet*. OWASP Cheat Sheet Series. Retrieved August 15, 2026, from https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html + +WHATWG. (2026). *URL standard*. https://url.spec.whatwg.org/ diff --git a/docs/doctoring/clearfolio-production-configuration.md b/docs/doctoring/clearfolio-production-configuration.md index 764a9f7e..8c727230 100644 --- a/docs/doctoring/clearfolio-production-configuration.md +++ b/docs/doctoring/clearfolio-production-configuration.md @@ -12,9 +12,11 @@ This boundary prevents configuration text from becoming an arbitrary downstream Every tenant-signed submit, status, and artifact-link fetch uses `redirect: "error"`. A provider redirect therefore becomes the existing sanitized transport failure instead of allowing the runtime to replay tenant HMAC headers onto an untrusted `Location` target. -Artifact links returned by this root configuration slice must resolve to the configured Clearfolio origin, must contain no URL credentials, and must contain no fragment. Protocol-relative or absolute foreign-host links fail closed, including token-free links that would otherwise become the browser's attachment-view redirect target. If a same-origin link contains an `artifactToken`, ScopeWeave rewrites that token into the trusted Clearfolio viewer route. A token is never transplanted into another origin. +Artifact links are default-deny outside the configured Clearfolio origin. They must contain no URL credentials or fragment. Protocol-relative or absolute foreign-host links therefore fail closed unless the foreign origin has been explicitly admitted by the reviewed `CLEARFOLIO_ARTIFACT_ORIGINS` policy described in `docs/doctoring/clearfolio-artifact-origin-trust.md`. Allowlist entries themselves must be canonical origin values so ambiguous path, credential, fragment, and serialization variants cannot silently broaden authority. -This root slice deliberately does not invent a cross-origin artifact-host allowlist. A later reviewed policy may admit explicitly configured canonical origins, but until that policy is present the secure default is same-origin only. Issue #489 remains open after this slice. Subsequent bounded work must still add the reviewed artifact-origin allowlist if cross-origin delivery is required, streaming response-size/media-type limits, a provider-wide request budget, and the remaining resource/lifecycle acceptance criteria before the Clearfolio adapter can be described as fully production-complete. +If a same-origin link contains an `artifactToken`, ScopeWeave rewrites that token into the trusted Clearfolio viewer route. A token is never transplanted from one origin into another. When a reviewed cross-origin artifact origin is explicitly allowed, its token-bearing URL remains bound to that issuing origin rather than being rewritten into the Clearfolio viewer. + +Issue #489 remains open after this stack. The provider-response parent owns bounded request time, response media type/size, streamed JSON parsing, and response-body cleanup. Remaining work includes capability readiness, broader persistence/lifecycle and incident/recovery evidence, plus destination DNS/IP authorization and any stronger signed-artifact URL-shape restrictions required for allowlisted origins. ## Executable evidence @@ -26,21 +28,21 @@ This root slice deliberately does not invent a cross-origin artifact-host allowl - loopback HTTP is accepted only under explicit development mode; and - signed tenant headers retain the documented canonical HMAC contract. -`tests/unit/clearfolio-status-signal.test.mjs` exercises sanitized transport/HTTP/JSON/status/artifact failures and now requires all three tenant-signed fetch paths to disable redirects. It rejects token-free CDN links, protocol-relative foreign links, credential-bearing same-origin links, fragmented same-origin links, and cross-origin token-bearing links while retaining same-origin relative links and the trusted viewer rewrite. `tests/api/attachment-status.test.mjs` makes its test-only in-memory provider explicit instead of relying on an unset production URL. +`tests/unit/clearfolio-status-signal.test.mjs` preserves the parent transport/HTTP/JSON/status/artifact regressions and requires all three tenant-signed fetch paths to disable redirects. With no artifact-origin allowlist it rejects token-free foreign HTTPS links, protocol-relative foreign links, credential-bearing same-origin links, fragmented same-origin links, and cross-origin token-bearing links while retaining same-origin relative links and the trusted viewer rewrite. With an explicit canonical `CLEARFOLIO_ARTIFACT_ORIGINS` entry it permits that exact foreign origin and leaves a foreign-origin token bound to its issuing URL. `tests/api/attachment-status.test.mjs` keeps its test-only in-memory provider explicit instead of relying on an unset production URL. -The shipped `server/clearfolio.mjs` remains in the canonical c8 production coverage target, so the new configuration branches execute under the repository coverage gate rather than a documentation-only path. +The shipped `server/clearfolio.mjs` remains in the canonical c8 production coverage target, so the configuration, provider-response, and allowlist branches execute under the repository coverage gate rather than a documentation-only path. ## Standards and threat rationale -The WHATWG URL Standard defines URL components, including credentials, queries, and fragments, and provides the common parsing model used by the JavaScript `URL` API. ScopeWeave parses first and then applies component-level policy instead of relying on string-prefix validation. +The WHATWG URL Standard defines URL components, credentials, origins, queries, fragments, and serialization behavior used by the JavaScript `URL` API. ScopeWeave parses first and then applies component-level and canonical-origin policy instead of relying on string-prefix validation. -OWASP's SSRF Prevention guidance recommends strict allowlisting and warns that redirects and attacker-controlled complete URLs can bypass URL validation. This slice narrows operator configuration to a provider origin, disables redirect following for tenant-signed calls, and keeps browser redirect authority same-origin until an explicit reviewed allowlist exists. +OWASP's SSRF Prevention guidance recommends strict allowlisting and warns that redirects and attacker-controlled complete URLs can bypass URL validation. ScopeWeave narrows operator configuration to a provider origin, disables redirect following for tenant-signed calls, defaults artifact redirects to the provider origin, and admits a foreign artifact origin only through explicit canonical allowlisting. DNS/IP destination authorization remains a separately tracked defense-in-depth boundary rather than being implied by hostname allowlisting. NIST SSDF 1.1 recommends identifying and maintaining software security requirements and producing well-secured software through repeatable verification. The fail-closed configuration contract, executable negative tests, and explicit remaining-gap statement provide acquisition-review evidence without claiming certification. ## Rollback -Rollback reverts the Clearfolio configuration parser, explicit development-mode tests, redirect prohibition, same-origin artifact rule, deployment text, this doctoring record, and the corresponding CHANGELOG entry together. No database schema or persisted attachment representation changes in this slice. +Rolling back the artifact-origin child removes its allowlist parsing, allowlist-specific tests/docs/deployment text, and child CHANGELOG entries while retaining the parent provider-configuration, redirect prohibition, same-origin default, bounded-response, and request-budget controls. No database schema or persisted attachment representation changes in this slice. ## References @@ -48,4 +50,4 @@ National Institute of Standards and Technology. (2022). *Secure Software Develop OWASP Foundation. (n.d.). *Server Side Request Forgery Prevention Cheat Sheet*. OWASP Cheat Sheet Series. https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html -WHATWG. (2026). *URL Standard*. https://url.spec.whatwg.org/ \ No newline at end of file +WHATWG. (2026). *URL Standard*. https://url.spec.whatwg.org/ diff --git a/docs/doctoring/clearfolio-provider-response-boundary.md b/docs/doctoring/clearfolio-provider-response-boundary.md index d8928c46..58f8ed18 100644 --- a/docs/doctoring/clearfolio-provider-response-boundary.md +++ b/docs/doctoring/clearfolio-provider-response-boundary.md @@ -15,8 +15,7 @@ Hosted provider requests: 3. use Fetch `redirect: "error"` so a redirect is a transport failure rather than a credential-forwarding opportunity; 4. carry a hard 15,000 ms total-request `AbortSignal`; 5. compose a caller cancellation signal with that hard budget for status refreshes; and -6. collapse network, redirect, timeout, and cancellation details into fixed operation-level errors before they can reach browser or diagnostic payloads; and -7. preserve the timeout category when the hard budget aborts an in-progress status response body, so refresh metrics distinguish timeouts from malformed responses. +6. collapse network, redirect, timeout, and cancellation details into fixed operation-level errors before they can reach browser or diagnostic payloads. ScopeWeave does not retry provider calls in this slice. Retry eligibility, idempotency keys, backoff, cancellation recovery, and persisted operation lifecycle remain explicit follow-up work rather than being guessed at the transport layer. @@ -42,7 +41,7 @@ The 10 MiB limit matches the current ScopeWeave attachment API ceiling, so the d The preceding slice already prevents a cross-origin `artifactToken` from being transplanted into the trusted Clearfolio viewer origin. This slice bounds and media-validates the artifact-link response itself and disables redirects on the request. -It **does not yet approve arbitrary cross-origin artifact URLs**. Issue #489 still owns the reviewed artifact-origin allowlist and the remaining URL rules for returned links, including credential and fragment rejection. Until that later slice integrates, cross-origin artifact URLs retain the narrower predecessor behavior and must not be represented as a fully qualified production CDN/object-storage policy. +Reviewed cross-origin artifact hosts are not implied here. They are owned by the later `CLEARFOLIO_ARTIFACT_ORIGINS` allowlist in `docs/doctoring/clearfolio-artifact-origin-trust.md`, which also rejects credentials and fragments on returned links. Until that allowlist is configured, only the provider origin is trusted. Issue #489 still owns destination DNS/IP authorization, signed-artifact URL shape, and the remaining lifecycle/acceptance work. ## Verification contract diff --git a/package.json b/package.json index e55546ef..d1fa6a07 100644 --- a/package.json +++ b/package.json @@ -13,9 +13,9 @@ "coverage": "npm run test:coverage", "server": "node server/server.mjs", "test:api": "node tests/api/auth-secret.test.mjs && node tests/api/smoke.mjs && node tests/api/ratelimit.test.mjs && node tests/api/attachment-status.test.mjs && node tests/api/session-revocation.test.mjs && node tests/api/orchestrator-attribution.test.mjs", - "test:unit": "node tests/unit/opencode-config.test.mjs && node tests/unit/changelog-release-notes.test.mjs && node tests/unit/analytics.test.mjs && node tests/unit/cpm.test.mjs && node tests/unit/baseline-compare.test.mjs && node tests/unit/workload.test.mjs && node tests/unit/cost-evm.test.mjs && node tests/unit/msproject.test.mjs && node tests/unit/auth-password.test.mjs && node tests/unit/editor-unsaved.test.mjs && node tests/unit/static-coverage-evidence.test.mjs && node tests/unit/dep-types.test.mjs && node tests/unit/weekly-report.test.mjs && node tests/unit/clearfolio.test.mjs && node tests/unit/clearfolio-adapter-mock-hmac.test.mjs && node tests/unit/clearfolio-provider-boundary.test.mjs && node tests/unit/orchestrator.test.mjs && node tests/unit/orchestrator-coverage.test.mjs && node tests/unit/orchestrator-attribution.test.mjs && node tests/unit/sprint-stats.test.mjs && node tests/unit/burndown.test.mjs && node tests/unit/pm-analysis.test.mjs && node tests/unit/cloud-sync-security.test.mjs && node tests/unit/attachment-status.test.mjs && node tests/unit/clearfolio-refresh-timeout.test.mjs && node tests/unit/clearfolio-status-signal.test.mjs && node tests/unit/coverage-script-contract.test.mjs && node tests/unit/toast-accessibility.test.mjs", + "test:unit": "node tests/unit/opencode-config.test.mjs && node tests/unit/changelog-release-notes.test.mjs && node tests/unit/analytics.test.mjs && node tests/unit/cpm.test.mjs && node tests/unit/baseline-compare.test.mjs && node tests/unit/workload.test.mjs && node tests/unit/cost-evm.test.mjs && node tests/unit/msproject.test.mjs && node tests/unit/auth-password.test.mjs && node tests/unit/editor-unsaved.test.mjs && node tests/unit/static-coverage-evidence.test.mjs && node tests/unit/dep-types.test.mjs && node tests/unit/weekly-report.test.mjs && node tests/unit/clearfolio.test.mjs && node tests/unit/clearfolio-adapter-mock-hmac.test.mjs && node tests/unit/clearfolio-provider-boundary.test.mjs && node tests/unit/clearfolio-artifact-origin.test.mjs && node tests/unit/orchestrator.test.mjs && node tests/unit/orchestrator-coverage.test.mjs && node tests/unit/orchestrator-attribution.test.mjs && node tests/unit/sprint-stats.test.mjs && node tests/unit/burndown.test.mjs && node tests/unit/pm-analysis.test.mjs && node tests/unit/cloud-sync-security.test.mjs && node tests/unit/attachment-status.test.mjs && node tests/unit/clearfolio-refresh-timeout.test.mjs && node tests/unit/clearfolio-status-signal.test.mjs && node tests/unit/coverage-script-contract.test.mjs && node tests/unit/toast-accessibility.test.mjs", "test:coverage": "c8 --all --include=app.js --include=cloud-sync.js --include=scripts/ci/static_coverage_evidence.mjs --include=server/attachment_status.mjs --include=server/app.mjs --include=server/auth.mjs --include=server/clearfolio.mjs --include=server/orchestrator.mjs --reporter=json --reporter=json-summary npm run test:coverage:cases", - "test:coverage:cases": "node tests/unit/coverage-script-contract.test.mjs && node tests/unit/attachment-status.test.mjs && node tests/unit/clearfolio-refresh-timeout.test.mjs && node tests/unit/clearfolio-status-signal.test.mjs && node tests/unit/clearfolio-adapter-mock-hmac.test.mjs && node tests/unit/clearfolio-provider-boundary.test.mjs && node tests/unit/orchestrator.test.mjs && node tests/unit/orchestrator-coverage.test.mjs && node tests/unit/orchestrator-attribution.test.mjs && node tests/unit/msproject.test.mjs && node tests/unit/auth-password.test.mjs && node tests/unit/editor-unsaved.test.mjs && node tests/unit/static-coverage-evidence.test.mjs && npm run test:api", + "test:coverage:cases": "node tests/unit/coverage-script-contract.test.mjs && node tests/unit/attachment-status.test.mjs && node tests/unit/clearfolio-refresh-timeout.test.mjs && node tests/unit/clearfolio-status-signal.test.mjs && node tests/unit/clearfolio-adapter-mock-hmac.test.mjs && node tests/unit/clearfolio-provider-boundary.test.mjs && node tests/unit/clearfolio-artifact-origin.test.mjs && node tests/unit/orchestrator.test.mjs && node tests/unit/orchestrator-coverage.test.mjs && node tests/unit/orchestrator-attribution.test.mjs && node tests/unit/msproject.test.mjs && node tests/unit/auth-password.test.mjs && node tests/unit/editor-unsaved.test.mjs && node tests/unit/static-coverage-evidence.test.mjs && npm run test:api", "test:e2e": "playwright test", "test:e2e:headed": "playwright test --headed", "test:e2e:cloud": "playwright install chromium && playwright test tests/e2e/cloud.spec.js tests/e2e/toast-accessibility.spec.js", diff --git a/server/clearfolio.mjs b/server/clearfolio.mjs index 686d8991..2635f492 100644 --- a/server/clearfolio.mjs +++ b/server/clearfolio.mjs @@ -122,6 +122,60 @@ function clearfolioConfiguration() { }; } +/** + * Build the exact set of origins trusted to host Clearfolio artifacts. + * + * The configured Clearfolio origin is always trusted. Additional origins are + * optional and must be comma-separated HTTPS origins with no credentials, + * path, query, or fragment. Canonical URL origins preserve exact scheme, host, + * and effective port identity while preventing string-prefix allowlist bypasses. + * + * @param {string} baseUrl - Validated Clearfolio provider origin. + * @returns {Set} Canonical origins accepted for artifact redirects. + * @throws {ClearfolioConfigurationError} If the optional allowlist is malformed or unsafe. + */ +function clearfolioArtifactOrigins(baseUrl) { + const trustedOrigins = new Set([new URL(baseUrl).origin]); + const configuredOrigins = process.env.CLEARFOLIO_ARTIFACT_ORIGINS; + if (configuredOrigins === undefined) return trustedOrigins; + + const entries = String(configuredOrigins).split(','); + if (entries.some((entry) => entry.trim().length === 0)) { + throw new ClearfolioConfigurationError( + 'clearfolio_artifact_origins_invalid', + 'CLEARFOLIO_ARTIFACT_ORIGINS must contain only comma-separated HTTPS origins.', + ); + } + + for (const entry of entries) { + const canonical = entry.trim(); + let url; + try { + url = new URL(canonical); + } catch { + throw new ClearfolioConfigurationError( + 'clearfolio_artifact_origins_invalid', + 'CLEARFOLIO_ARTIFACT_ORIGINS must contain only comma-separated HTTPS origins.', + ); + } + if ( + url.protocol !== 'https:' + || Boolean(url.username + url.password) + || url.pathname !== '/' + || Boolean(url.search) + || Boolean(url.hash) + || (canonical !== url.origin && canonical !== `${url.origin}/`) + ) { + throw new ClearfolioConfigurationError( + 'clearfolio_artifact_origins_invalid', + 'CLEARFOLIO_ARTIFACT_ORIGINS must contain only comma-separated HTTPS origins.', + ); + } + trustedOrigins.add(url.origin); + } + return trustedOrigins; +} + /** * Sign tenant claims using the Clearfolio HMAC interoperability contract. * @@ -518,12 +572,9 @@ export async function jobStatus(orgId, userId, jobId, { signal } = {}) { /** * Issue a viewable artifact URL for a completed Clearfolio job. * - * All browser redirect authority remains bound to the configured Clearfolio - * origin in this transport slice. Cross-origin artifact hosts stay fail-closed - * until the separately reviewed artifact-origin allowlist lands. Credentials - * and fragments are rejected for both token-bearing and tokenless links. - * Same-origin `artifactToken` values may be translated into the trusted viewer - * route without exposing the token to an unreviewed host. + * Same-origin `artifactToken` values may be translated into the local viewer + * route. A token returned on another origin remains bound to that origin and is + * never transplanted into the trusted Clearfolio viewer URL. * * @param {string|number} orgId - ScopeWeave organization identifier. * @param {string|number} userId - Requesting ScopeWeave user identifier. @@ -535,6 +586,7 @@ export async function artifactUrl(orgId, userId, jobId) { const canonicalJobId = validateJobId(jobId); const configuration = clearfolioConfiguration(); if (configuration.mock) return `/api/mock-clearfolio/${encodeURIComponent(canonicalJobId)}`; + const trustedArtifactOrigins = clearfolioArtifactOrigins(configuration.baseUrl); const request = providerSignal(); try { let res; @@ -569,20 +621,19 @@ export async function artifactUrl(orgId, userId, jobId) { throw new Error('clearfolio artifact-link response invalid'); } if ( - url.origin !== clearfolioUrl.origin - || url.username - || url.password - || url.hash + Boolean(url.username + url.password) + || Boolean(url.hash) + || !trustedArtifactOrigins.has(url.origin) ) { throw new Error('clearfolio artifact-link response invalid'); } const token = url.searchParams.get('artifactToken'); - if (token) { + if (token && url.origin === clearfolioUrl.origin) { return `${configuration.baseUrl}/viewer/${encodeURIComponent(canonicalJobId)}?artifactToken=${encodeURIComponent(token)}`; } return url.href; } finally { request.dispose(); } -} +} \ No newline at end of file diff --git a/tests/unit/clearfolio-artifact-origin.test.mjs b/tests/unit/clearfolio-artifact-origin.test.mjs new file mode 100644 index 00000000..3dcf7559 --- /dev/null +++ b/tests/unit/clearfolio-artifact-origin.test.mjs @@ -0,0 +1,138 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +const HMAC_SECRET = 'clearfolio-shared-secret-32-bytes!!'; +const originalFetch = globalThis.fetch; +let importSequence = 0; +let fetchCalls = 0; +let artifactPayload = { artifactUrl: 'https://clearfolio.example/file.pdf' }; + +globalThis.fetch = async () => { + fetchCalls += 1; + return new Response(JSON.stringify(artifactPayload), { + status: 200, + headers: { 'content-type': 'application/json; charset=utf-8' }, + }); +}; + +async function loadAdapter(artifactOrigins) { + process.env.CLEARFOLIO_URL = 'https://clearfolio.example'; + process.env.CLEARFOLIO_HMAC_SECRET = HMAC_SECRET; + delete process.env.SCOPEWEAVE_DEV; + if (artifactOrigins === undefined) delete process.env.CLEARFOLIO_ARTIFACT_ORIGINS; + else process.env.CLEARFOLIO_ARTIFACT_ORIGINS = artifactOrigins; + importSequence += 1; + return import(`../../server/clearfolio.mjs?artifact-origin-policy=${importSequence}`); +} + +async function resolveArtifact(link, artifactOrigins) { + artifactPayload = { artifactUrl: link }; + const { artifactUrl } = await loadAdapter(artifactOrigins); + return artifactUrl(4, 5, 'job-1'); +} + +test.after(() => { + globalThis.fetch = originalFetch; + delete process.env.CLEARFOLIO_URL; + delete process.env.CLEARFOLIO_HMAC_SECRET; + delete process.env.CLEARFOLIO_ARTIFACT_ORIGINS; + delete process.env.SCOPEWEAVE_DEV; +}); + +test('artifact URLs default to the configured Clearfolio origin', async () => { + await assert.rejects( + () => resolveArtifact('https://cdn.example/file.pdf', undefined), + /clearfolio artifact-link response invalid/, + ); + await assert.rejects( + () => resolveArtifact('https://evil.com/file.pdf?artifactToken=stolen', undefined), + /clearfolio artifact-link response invalid/, + 'an unallowlisted token stays rejected instead of moving into the viewer', + ); + for (const link of [ + '//evil.com/file.pdf', + '/\\evil.com/file.pdf', + 'https://clearfolio.example@evil.com/x?artifactToken=t', + ]) { + await assert.rejects( + () => resolveArtifact(link, undefined), + /clearfolio artifact-link response invalid/, + `${link} must not inherit the provider origin`, + ); + } + assert.equal( + await resolveArtifact('/signed/file.pdf', undefined), + 'https://clearfolio.example/signed/file.pdf', + ); +}); + +test('explicit HTTPS artifact origins are exact scheme-host-port allowlist entries', async () => { + assert.equal( + await resolveArtifact('https://cdn.example/file.pdf', ' https://cdn.example '), + 'https://cdn.example/file.pdf', + ); + assert.equal( + await resolveArtifact('https://cdn.example/file.pdf', 'https://cdn.example/'), + 'https://cdn.example/file.pdf', + 'a trailing slash is still an origin-only allowlist entry', + ); + assert.equal( + await resolveArtifact( + 'https://cdn.example/file.pdf?artifactToken=remote%20token', + 'https://cdn.example', + ), + 'https://cdn.example/file.pdf?artifactToken=remote%20token', + 'an allowlisted cross-origin token remains bound to the returned origin', + ); + await assert.rejects( + () => resolveArtifact('https://cdn.example/file.pdf', 'https://cdn.example:8443'), + /clearfolio artifact-link response invalid/, + 'an allowlist entry with a different port is a different origin', + ); +}); + +test('artifact links reject credentials and fragments even on trusted origins', async () => { + for (const link of [ + 'https://user:password@clearfolio.example/file.pdf', + 'https://clearfolio.example/file.pdf#secret-fragment', + 'https://user:password@cdn.example/file.pdf', + 'https://cdn.example/file.pdf#secret-fragment', + ]) { + await assert.rejects( + () => resolveArtifact(link, 'https://cdn.example'), + /clearfolio artifact-link response invalid/, + ); + } +}); + +test('artifact origin configuration fails closed before provider transport', async () => { + const invalidConfigurations = [ + 'http://cdn.example', + 'https://user:password@cdn.example', + 'https://cdn.example/path', + 'https://cdn.example?query=1', + 'https://cdn.example#fragment', + 'https://cdn.example#', + 'https://:@cdn.example', + 'https://cdn.example/foo/..', + 'https://cdn.example:443', + 'not a URL', + 'https://cdn.example,', + '', + ' ', + ]; + + for (const artifactOrigins of invalidConfigurations) { + const before = fetchCalls; + artifactPayload = { artifactUrl: 'https://cdn.example/file.pdf' }; + const { artifactUrl } = await loadAdapter(artifactOrigins); + await assert.rejects( + () => artifactUrl(4, 5, 'job-1'), + (error) => { + assert.equal(error.code, 'clearfolio_artifact_origins_invalid'); + return true; + }, + ); + assert.equal(fetchCalls, before, `invalid allowlist ${artifactOrigins} never reaches provider transport`); + } +}); diff --git a/tests/unit/clearfolio-status-signal.test.mjs b/tests/unit/clearfolio-status-signal.test.mjs index 13531d5c..9134bb13 100644 --- a/tests/unit/clearfolio-status-signal.test.mjs +++ b/tests/unit/clearfolio-status-signal.test.mjs @@ -54,6 +54,7 @@ test.after(() => { globalThis.fetch = originalFetch; delete process.env.CLEARFOLIO_URL; delete process.env.CLEARFOLIO_HMAC_SECRET; + delete process.env.CLEARFOLIO_ARTIFACT_ORIGINS; delete process.env.SCOPEWEAVE_DEV; }); @@ -257,6 +258,28 @@ test('artifactUrl validates links and never exposes transport or response text', () => artifactUrl(4, 5, 'job-1'), 'clearfolio artifact-link response invalid', ); + + process.env.CLEARFOLIO_ARTIFACT_ORIGINS = 'https://cdn.example'; + try { + setResponse({ json: async () => ({ url: 'https://cdn.example/file.pdf' }) }); + assert.equal( + await artifactUrl(4, 5, 'job-1'), + 'https://cdn.example/file.pdf', + ); + + setResponse({ + json: async () => ({ + signedUrl: 'https://cdn.example/file.pdf?artifactToken=token%20value', + }), + }); + assert.equal( + await artifactUrl(4, 5, 'job-1'), + 'https://cdn.example/file.pdf?artifactToken=token%20value', + 'an explicitly trusted cross-origin token remains bound to its artifact origin', + ); + } finally { + delete process.env.CLEARFOLIO_ARTIFACT_ORIGINS; + } }); test('artifactUrl permits HTTP only for explicit loopback development', async () => { @@ -274,6 +297,7 @@ test('artifactUrl permits HTTP only for explicit loopback development', async () ); } finally { process.env.CLEARFOLIO_URL = 'https://clearfolio.example'; + delete process.env.CLEARFOLIO_ARTIFACT_ORIGINS; delete process.env.SCOPEWEAVE_DEV; } });