diff --git a/.changeset/33891-cloud-managed-storage-ai-settings.md b/.changeset/33891-cloud-managed-storage-ai-settings.md new file mode 100644 index 00000000000..fd8f9a4752f --- /dev/null +++ b/.changeset/33891-cloud-managed-storage-ai-settings.md @@ -0,0 +1,16 @@ +--- +'@objectstack/service-settings': patch +'@objectstack/platform-objects': patch +--- + +fix(settings)!: a cloud-managed environment does not offer its file storage or AI provider settings + +Clause-②: no (narrowing) — narrowed, in a cloud-managed process (`OS_CLOUD_MANAGED=1`) only: `GET /api/settings` no longer lists `storage`, and serves `ai` without its provider, per-provider model and credential, generation-default (`temperature`, `max_tokens`, `request_timeout_ms`) and embedder keys; `GET` / `PUT /api/settings/storage` and `POST /api/settings/storage/:actionId` answer `409 RESOURCE_CONFLICT` with `details.managedBy: 'platform'`; `GET /api/settings/ai` serves the conversation-title and observability keys only; a `PUT /api/settings/ai` that names a hidden key answers the same 409 and writes nothing; `POST /api/settings/ai/test`, `ai/test_embedder` and `ai/reset` answer the same 409; the data API's reads of `sys_setting`, `sys_platform_setting` and their audit objects leave out every `storage` row and every row of a hidden `ai` key for a caller that is not the system; the Setup entry `nav_settings_storage` carries `visible: 'features.cloudManaged != true'`. A self-hosted deployment answers exactly as before. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the hosted settings doors or the storage / AI settings pages. + + + +**BREAKING** for a caller of a cloud-managed environment: its file storage and its AI provider are provided and configured by the hosting platform, so the settings doors no longer show or change them. The registry stays whole: the storage and AI services, which read these settings in process, keep reading every value. The refusal is `409 RESOURCE_CONFLICT`, as at every other cloud-managed door, with `details.managedBy: 'platform'` so a console can tell it apart from `404 UNKNOWN_NAMESPACE`. + +What to do: nothing on a self-hosted deployment. A client of a hosted environment that read or wrote `storage.*`, or the hidden `ai.*` keys, stops doing so: those values are the hosting platform's. diff --git a/packages/platform-objects/src/apps/setup-nav.contributions.ts b/packages/platform-objects/src/apps/setup-nav.contributions.ts index 8fe40598767..54bf41c515f 100644 --- a/packages/platform-objects/src/apps/setup-nav.contributions.ts +++ b/packages/platform-objects/src/apps/setup-nav.contributions.ts @@ -172,7 +172,11 @@ export const SETUP_NAV_CONTRIBUTIONS: NavigationContribution[] = [ // `@objectstack/service-settings` (`setup-nav-hub-parity.test.ts`). { id: 'nav_settings_mail', type: 'url', label: 'Mail Delivery', url: '/apps/setup/system/settings/mail', icon: 'mail', requiredPermissions: ['manage_platform_settings'] }, { id: 'nav_settings_sms', type: 'url', label: 'SMS Delivery', url: '/apps/setup/system/settings/sms', icon: 'message-square', requiredPermissions: ['manage_platform_settings'] }, - { id: 'nav_settings_storage', type: 'url', label: 'File Storage', url: '/apps/setup/system/settings/storage', icon: 'hard-drive', requiredPermissions: ['manage_platform_settings'] }, + // [#33891] A cloud-managed environment's file storage is the hosting + // platform's: the settings doors refuse the page there + // (`@objectstack/service-settings` `cloud-managed-settings.ts`), so the + // entry is not drawn. `features` is a root every nav entry binds. + { id: 'nav_settings_storage', type: 'url', label: 'File Storage', url: '/apps/setup/system/settings/storage', icon: 'hard-drive', requiredPermissions: ['manage_platform_settings'], visible: 'features.cloudManaged != true' }, { id: 'nav_settings_ai', type: 'url', label: 'AI & Embedder', url: '/apps/setup/system/settings/ai', icon: 'sparkles', requiredPermissions: ['manage_platform_settings'] }, { id: 'nav_settings_knowledge', type: 'url', label: 'Knowledge', url: '/apps/setup/system/settings/knowledge', icon: 'book-open', requiredPermissions: ['manage_platform_settings'] }, // `lifecycle` is `@objectstack/objectql`'s manifest (ADR-0057), offered diff --git a/packages/services/service-settings/src/cloud-managed-settings.pin.test.ts b/packages/services/service-settings/src/cloud-managed-settings.pin.test.ts new file mode 100644 index 00000000000..f32f89ee44f --- /dev/null +++ b/packages/services/service-settings/src/cloud-managed-settings.pin.test.ts @@ -0,0 +1,207 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A cloud-managed environment does not offer its file storage or its AI + * provider settings at the settings doors (#33891, `cloud-managed-settings.ts`). + * + * Every door is driven twice on the same composition: once with + * `OS_CLOUD_MANAGED=1` (hosted) and once without it (self-hosted, the control, + * which must answer exactly as before). Refusals are pinned by envelope + * (status + `error.code` + `details.managedBy`), which is what the console and + * an API caller read. + * + * The data-API read of the rows is pinned beside the read door's own suite + * (`settings-read-door.pin.test.ts`), on the real engine. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { resetCloudManagedForTesting } from '@objectstack/core'; +import { SETUP_NAV_CONTRIBUTIONS } from '@objectstack/platform-objects'; +import type { IHttpRequest, IHttpResponse } from '@objectstack/spec/contracts'; +import { SettingsService } from './settings-service.js'; +import { registerSettingsRoutes } from './settings-routes.js'; +import { MockHttp } from './__tests__/settings-door.testkit.js'; +import { aiSettingsManifest, builtinSettingsManifests } from './manifests/index.js'; +import { + CLOUD_MANAGED_HIDDEN_SETTINGS, + CLOUD_MANAGED_SERVED_AI_KEYS, +} from './cloud-managed-settings.js'; + +const HIDDEN_AI = CLOUD_MANAGED_HIDDEN_SETTINGS.ai.keys as readonly string[]; + +function hosted(on: boolean): void { + if (on) process.env.OS_CLOUD_MANAGED = '1'; + else delete process.env.OS_CLOUD_MANAGED; + resetCloudManagedForTesting(); +} + +async function boot(): Promise<{ service: SettingsService; http: MockHttp }> { + const service = new SettingsService({ env: {} }); + for (const m of builtinSettingsManifests) service.registerManifest(m as any); + const http = new MockHttp(); + registerSettingsRoutes(http, service, { + contextFromRequest: () => ({ enforced: true, permissions: ['manage_platform_settings', 'setup.access'], userId: 'usr_admin' }), + }); + return { service, http }; +} + +async function call( + http: MockHttp, + route: string, + params: Record, + body?: Record, +): Promise<{ status: number; body?: any }> { + const handler = http.routes.get(route); + if (!handler) throw new Error(`route not registered: ${route}`); + const [method] = route.split(' '); + const req = { params, query: {}, body: body ?? {}, headers: {}, method, path: '/' } as IHttpRequest; + const state: { status: number; body?: any } = { status: 200 }; + const res: IHttpResponse = { + json: vi.fn((d) => { state.body = d; }) as any, + send: vi.fn() as any, + status: vi.fn((c: number) => { state.status = c; return res; }) as any, + header: vi.fn(() => res) as any, + }; + await handler(req, res); + return state; +} + +const LIST = 'GET /api/settings'; +const READ = 'GET /api/settings/:namespace'; +const WRITE = 'PUT /api/settings/:namespace'; +const ACTION = 'POST /api/settings/:namespace/:actionId'; + +function expectManaged(answer: { status: number; body?: any }, namespace: string): void { + expect(answer.status).toBe(409); + expect(answer.body?.error?.code).toBe('RESOURCE_CONFLICT'); + expect(answer.body?.error?.details?.managedBy).toBe('platform'); + expect(answer.body?.error?.details?.namespace).toBe(namespace); +} + +const keysOf = (manifest: any): string[] => + (manifest?.specifiers ?? []).map((s: any) => s.key).filter((k: unknown): k is string => typeof k === 'string'); +const idsOf = (manifest: any, type: string): string[] => + (manifest?.specifiers ?? []).filter((s: any) => s.type === type).map((s: any) => s.id); + +describe('#33891 — the hosted projection table', () => { + it('classifies every ai key: hidden, or served — none both, none neither', () => { + const declared = keysOf(aiSettingsManifest); + const served = new Set(CLOUD_MANAGED_SERVED_AI_KEYS); + for (const key of declared) expect(HIDDEN_AI.includes(key) !== served.has(key), key).toBe(true); + for (const key of served) expect(declared, key).toContain(key); + for (const key of HIDDEN_AI) expect(served.has(key), key).toBe(false); + // The ruled split: provider, model, credentials, temperature, max output + // and timeout hidden; titles and observability served. + expect(HIDDEN_AI).toEqual(expect.arrayContaining(['provider', 'openai_model', 'openai_api_key', 'temperature', 'max_tokens', 'request_timeout_ms'])); + expect([...served].sort()).toEqual(['log_prompts', 'title_generation_enabled', 'title_max_length', 'trace_enabled']); + }); +}); + +for (const managed of [true, false]) { + describe(`#33891 — the settings doors, ${managed ? 'cloud-managed' : 'self-hosted (control)'}`, () => { + let service: SettingsService; + let http: MockHttp; + beforeEach(async () => { + hosted(managed); + ({ service, http } = await boot()); + }); + afterEach(() => hosted(false)); + + it('GET /api/settings: storage is listed only self-hosted; ai is listed either way, without its hidden keys when hosted', async () => { + const answer = await call(http, LIST, {}); + expect(answer.status).toBe(200); + const manifests = answer.body?.data?.manifests as any[]; + const namespaces = manifests.map((m) => m.namespace); + expect(namespaces).toEqual(expect.arrayContaining(['ai', 'mail'])); + const ai = manifests.find((m) => m.namespace === 'ai'); + expect(keysOf(ai)).toEqual(expect.arrayContaining([...CLOUD_MANAGED_SERVED_AI_KEYS])); + if (managed) { + expect(namespaces).not.toContain('storage'); + for (const key of HIDDEN_AI) expect(keysOf(ai), key).not.toContain(key); + } else { + expect(namespaces).toContain('storage'); + expect(keysOf(ai)).toEqual(expect.arrayContaining([...HIDDEN_AI])); + } + }); + + it('GET /api/settings/storage is refused as platform-managed when hosted, served self-hosted', async () => { + const answer = await call(http, READ, { namespace: 'storage' }); + if (managed) expectManaged(answer, 'storage'); + else expect(answer.status).toBe(200); + }); + + it('GET /api/settings/ai serves titles and observability; the hidden keys, their sections and the refused buttons only self-hosted', async () => { + const answer = await call(http, READ, { namespace: 'ai' }); + expect(answer.status).toBe(200); + const { manifest, values } = answer.body?.data ?? {}; + expect(keysOf(manifest)).toEqual(expect.arrayContaining([...CLOUD_MANAGED_SERVED_AI_KEYS])); + expect(Object.keys(values)).toEqual(expect.arrayContaining([...CLOUD_MANAGED_SERVED_AI_KEYS])); + expect(idsOf(manifest, 'group')).toEqual(expect.arrayContaining(['titles', 'observability'])); + if (managed) { + for (const key of HIDDEN_AI) { + expect(keysOf(manifest), key).not.toContain(key); + expect(Object.keys(values), key).not.toContain(key); + } + for (const group of ['provider', 'openai', 'defaults', 'embedder']) expect(idsOf(manifest, 'group'), group).not.toContain(group); + expect(idsOf(manifest, 'action_button')).toEqual([]); + } else { + expect(keysOf(manifest)).toEqual(expect.arrayContaining([...HIDDEN_AI])); + expect(idsOf(manifest, 'group')).toEqual(expect.arrayContaining(['provider', 'defaults', 'embedder'])); + expect(idsOf(manifest, 'action_button')).toEqual(expect.arrayContaining(['test', 'reset', 'test_embedder'])); + } + }); + + it('PUT /api/settings/storage is refused as platform-managed when hosted', async () => { + const answer = await call(http, WRITE, { namespace: 'storage' }, { adapter: 'local' }); + if (managed) expectManaged(answer, 'storage'); + else expect(answer.status).not.toBe(409); + }); + + it('a write naming a hidden ai key is refused WHOLE when hosted: the served key beside it is not written either', async () => { + const answer = await call(http, WRITE, { namespace: 'ai' }, { temperature: 0.2, title_max_length: 20 }); + const stored = (await service.get('ai', 'title_max_length')).value; + if (managed) { + expectManaged(answer, 'ai'); + expect(answer.body?.error?.details?.keys).toEqual(['temperature']); + expect(stored).not.toBe(20); + } else { + expect(answer.status).toBe(200); + expect(stored).toBe(20); + } + }); + + it('a write of served ai keys only is written either way', async () => { + const answer = await call(http, WRITE, { namespace: 'ai' }, { title_max_length: 24, trace_enabled: false }); + expect(answer.status).toBe(200); + expect((await service.get('ai', 'title_max_length')).value).toBe(24); + }); + + for (const [namespace, actionId] of [['storage', 'test'], ['ai', 'test'], ['ai', 'test_embedder'], ['ai', 'reset']] as const) { + it(`POST /api/settings/${namespace}/${actionId} is refused as platform-managed when hosted only`, async () => { + const answer = await call(http, ACTION, { namespace, actionId }, { values: {} }); + if (managed) expectManaged(answer, namespace); + else expect(answer.status).not.toBe(409); + }); + } + + it('the in-process reader keeps reading every value: the registry is whole', async () => { + const storage = await service.getNamespace('storage'); + expect(Object.keys(storage.values).length).toBeGreaterThan(0); + await expect(service.get('ai', 'provider')).resolves.toBeDefined(); + }); + }); +} + +describe('#33891 — the Setup entry', () => { + const items = SETUP_NAV_CONTRIBUTIONS.flatMap((c) => (c.items ?? []) as Array<{ id?: string; visible?: unknown }>); + + it('the File Storage entry is drawn only where the environment is not cloud-managed', () => { + expect(items.find((i) => i.id === 'nav_settings_storage')?.visible).toBe('features.cloudManaged != true'); + }); + + it('the AI entry stays: its titles and observability are served when hosted', () => { + const ai = items.find((i) => i.id === 'nav_settings_ai'); + expect(ai).toBeDefined(); + expect(ai?.visible).toBeUndefined(); + }); +}); diff --git a/packages/services/service-settings/src/cloud-managed-settings.ts b/packages/services/service-settings/src/cloud-managed-settings.ts new file mode 100644 index 00000000000..cb201878b18 --- /dev/null +++ b/packages/services/service-settings/src/cloud-managed-settings.ts @@ -0,0 +1,244 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The settings a cloud-managed environment does not offer at its doors (#33891). + * + * A hosted environment's file storage and its AI provider are provided and + * configured by the hosting platform, so an administrator of the environment + * neither sees nor changes them. Whether this process is hosted is + * `isCloudManaged()` from `@objectstack/core` (`OS_CLOUD_MANAGED=1`) and + * nothing else; a self-hosted deployment never sets it, and there every door + * answers exactly as before. + * + * ## A door check, not a registry withholding + * + * The registry stays whole. The storage service reads + * `settings.getNamespace('storage')` for its adapter and its limits on every + * pass, and `SettingsService.get` throws `UnknownKeyError` for an unregistered + * key, so withholding the manifest at `init()` (what the branding namespace + * does under a walled posture) would break the hosted readers this platform + * configures through. The hiding happens where a CALLER meets the settings: + * + * - `GET /api/settings`: a whole-hidden namespace is left out of the list, and + * a per-key namespace is served without its hidden keys; + * - `GET /api/settings/:namespace`: a whole-hidden namespace is refused, a + * per-key namespace is served without its hidden keys (manifest, values and + * `live`); + * - `PUT /api/settings/:namespace`: a whole-hidden namespace is refused, and a + * write that names any hidden key is refused WHOLE, nothing written, the way + * `setMany` refuses a write that names an unknown key; + * - `POST /api/settings/:namespace/:actionId`: the refused actions; + * - the data API's read of `sys_setting` / `sys_platform_setting` and their + * audit trails (`settings-read-door.ts`): the hidden rows are filtered out + * for every caller that is not the system. + * + * In-process readers (the storage service, the AI service) call the service + * directly and keep reading every value. + * + * ## The refusal + * + * `409 RESOURCE_CONFLICT`, no code minted: the house answer of every + * cloud-managed door (plugin-auth's `cloudManagedRefusal`, cloud-connection's + * platform-managed doors), on the same rule — the refusal comes from the + * runtime's state, not from the request. It is told apart from + * `404 UNKNOWN_NAMESPACE` by its code, and `details.managedBy: 'platform'` + * names the reason, so the console can draw "managed by the platform" instead + * of "no such page". + */ + +import { isCloudManaged } from '@objectstack/core'; + +/** What a cloud-managed environment hides of one namespace. */ +export interface CloudManagedNamespaceRule { + /** `'*'` hides the whole namespace; a list hides those keys only. */ + readonly keys: '*' | readonly string[]; + /** The actions refused (`'*'` = every action). */ + readonly actions: '*' | readonly string[]; + /** What the platform provides here, for the refusal's sentence. */ + readonly provides: string; +} + +/** + * The hosted projection. ONE table, read by every door. + * + * `ai` hides per key: the provider and its per-provider sections (model and + * credentials), the generation defaults (temperature, max output, timeout) and + * the embedder (its provider, model and credentials). The conversation-title + * and observability keys stay served. Its `test` / `test_embedder` buttons + * exercise the hidden credentials, and `reset` clears every stored `ai` row, + * hidden ones included, so all three are refused. + */ +export const CLOUD_MANAGED_HIDDEN_SETTINGS: Readonly> = Object.freeze({ + storage: { + keys: '*', + actions: '*', + provides: 'file storage', + }, + ai: { + keys: Object.freeze([ + 'provider', + 'gateway_model', 'gateway_api_key', + 'openai_api_key', 'openai_model', 'openai_base_url', + 'anthropic_api_key', 'anthropic_model', + 'google_api_key', 'google_model', + 'deepseek_api_key', 'deepseek_model', + 'dashscope_api_key', 'dashscope_model', + 'cloudflare_account_id', 'cloudflare_gateway_id', 'cloudflare_api_key', 'cloudflare_model', + 'siliconflow_api_key', 'siliconflow_model', + 'openrouter_api_key', 'openrouter_model', + 'temperature', 'max_tokens', 'request_timeout_ms', + 'embedder_provider', 'embedder_api_key', 'embedder_model', 'embedder_base_url', + 'embedder_dimensions', 'embedder_batch_size', + ]), + actions: Object.freeze(['test', 'test_embedder', 'reset']), + provides: 'the AI provider, its model and credentials', + }, +}); + +/** The keys of `ai` a hosted environment still serves — the complement, pinned. */ +export const CLOUD_MANAGED_SERVED_AI_KEYS: readonly string[] = Object.freeze([ + 'title_generation_enabled', 'title_max_length', 'trace_enabled', 'log_prompts', +]); + +/** The `details` a cloud-managed refusal carries. */ +export interface SettingsCloudManagedDetails { + namespace: string; + managedBy: 'platform'; + keys?: string[]; + actionId?: string; +} + +/** A settings door refused because the hosting platform manages what was asked for. */ +export class SettingsCloudManagedError extends Error { + readonly details: SettingsCloudManagedDetails; + constructor(message: string, details: SettingsCloudManagedDetails) { + super(message); + this.name = 'SettingsCloudManagedError'; + this.details = details; + } +} + +/** The status and code every cloud-managed settings refusal answers. */ +export const SETTINGS_CLOUD_MANAGED_STATUS = 409; +export const SETTINGS_CLOUD_MANAGED_CODE = 'RESOURCE_CONFLICT' as const; + +/** The rule for a namespace in THIS process: none when it is not cloud-managed. */ +export function cloudManagedRule(namespace: string): CloudManagedNamespaceRule | undefined { + if (!isCloudManaged()) return undefined; + return Object.prototype.hasOwnProperty.call(CLOUD_MANAGED_HIDDEN_SETTINGS, namespace) + ? CLOUD_MANAGED_HIDDEN_SETTINGS[namespace] + : undefined; +} + +function prefix(rule: CloudManagedNamespaceRule): string { + return `This environment is cloud-managed: ${rule.provides} is provided and configured by the hosting platform`; +} + +/** Refuse a read or write of a namespace hidden whole. */ +export function assertNamespaceServed(namespace: string, verb: 'read' | 'write'): void { + const rule = cloudManagedRule(namespace); + if (rule?.keys !== '*') return; + throw new SettingsCloudManagedError( + `${prefix(rule)}, so its settings are not ${verb === 'read' ? 'shown' : 'changed'} here.` + + (verb === 'write' ? ' Nothing was written.' : ''), + { namespace, managedBy: 'platform' }, + ); +} + +/** Refuse a write that names any hidden key — the whole write, nothing applied. */ +export function assertWriteServed(namespace: string, keys: Iterable): void { + assertNamespaceServed(namespace, 'write'); + const rule = cloudManagedRule(namespace); + if (!rule || rule.keys === '*') return; + const hidden = new Set(rule.keys); + const named = [...keys].filter((k) => hidden.has(k)); + if (named.length === 0) return; + throw new SettingsCloudManagedError( + `${prefix(rule)}, so ${named.map((k) => `'${k}'`).join(', ')} cannot be changed here. Nothing was written.`, + { namespace, managedBy: 'platform', keys: named }, + ); +} + +/** Refuse an action the hosted projection refuses. */ +export function assertActionServed(namespace: string, actionId: string): void { + const rule = cloudManagedRule(namespace); + if (!rule) return; + if (rule.actions !== '*' && !rule.actions.includes(actionId)) return; + throw new SettingsCloudManagedError( + `${prefix(rule)}, so '${actionId}' is not run here.`, + { namespace, managedBy: 'platform', actionId }, + ); +} + +interface SpecifierLike { type?: string; key?: string; id?: string; handler?: unknown } + +/** + * The manifest a hosted caller is served: hidden keys removed, refused action + * buttons removed, and every group (with the layout items under it) whose + * section is left with no served key removed. A section runs from a `group` + * to the next one; items before the first group form their own section. + */ +export function projectManifest(manifest: M): M { + const rule = cloudManagedRule(manifest.namespace); + if (!rule || rule.keys === '*') return manifest; + const hidden = new Set(rule.keys); + const refusedAction = (id: string | undefined) => + id !== undefined && (rule.actions === '*' || rule.actions.includes(id)); + const sections: SpecifierLike[][] = []; + for (const s of manifest.specifiers as SpecifierLike[]) { + if (s.type === 'group' || sections.length === 0) sections.push([]); + sections[sections.length - 1].push(s); + } + const served: SpecifierLike[] = []; + for (const section of sections) { + const kept = section.filter((s) => { + if (s.key !== undefined) return !hidden.has(s.key); + if (s.type === 'action_button') return !refusedAction(s.id); + return true; + }); + const keyed = section.some((s) => s.key !== undefined); + const servesAKey = kept.some((s) => s.key !== undefined); + // A section that held keys and kept none goes whole: its heading and its + // banners describe settings this environment does not offer. A keyless + // section (action buttons only) keeps what survived. + if (keyed && !servesAKey) continue; + served.push(...kept); + } + return { ...manifest, specifiers: served }; +} + +/** The list a hosted caller is served: whole-hidden namespaces left out, the rest projected. */ +export function projectManifestList(manifests: M[]): M[] { + return manifests + .filter((m) => cloudManagedRule(m.namespace)?.keys !== '*') + .map((m) => projectManifest(m)); +} + +/** A key-indexed map with a namespace's hidden keys removed. */ +export function projectKeyed(namespace: string, values: Record): Record { + const rule = cloudManagedRule(namespace); + if (!rule || rule.keys === '*') return values; + const hidden = new Set(rule.keys); + return Object.fromEntries(Object.entries(values).filter(([k]) => !hidden.has(k))); +} + +/** + * The row predicate the data-API read door ANDs in for a non-system caller in + * a hosted process: no row of a whole-hidden namespace, and no row of a hidden + * key. `null` when nothing is hidden (self-hosted). Built only from the shapes + * the read door already composes (`$and`, `$or`, `$nin`). + */ +export function cloudManagedRowScope(): Record | null { + if (!isCloudManaged()) return null; + const whole: string[] = []; + const perKey: Record[] = []; + for (const [namespace, rule] of Object.entries(CLOUD_MANAGED_HIDDEN_SETTINGS)) { + if (rule.keys === '*') whole.push(namespace); + else perKey.push({ $or: [{ namespace: { $nin: [namespace] } }, { key: { $nin: [...rule.keys] } }] }); + } + const terms: Record[] = []; + if (whole.length > 0) terms.push({ namespace: { $nin: whole } }); + terms.push(...perKey); + if (terms.length === 0) return null; + return terms.length === 1 ? terms[0] : { $and: terms }; +} diff --git a/packages/services/service-settings/src/settings-read-door.pin.test.ts b/packages/services/service-settings/src/settings-read-door.pin.test.ts index a0648d69505..e1e721a39d7 100644 --- a/packages/services/service-settings/src/settings-read-door.pin.test.ts +++ b/packages/services/service-settings/src/settings-read-door.pin.test.ts @@ -15,7 +15,8 @@ * principal holding the namespace's capability, returns the row. */ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { resetCloudManagedForTesting } from '@objectstack/core'; import { ObjectQL } from '@objectstack/objectql'; import { SysPlatformSetting, SysPlatformSettingAudit, SysSetting, SysSettingAudit } from '@objectstack/platform-objects/system'; import { SettingsService } from './settings-service.js'; @@ -222,3 +223,52 @@ describe('settingsReadDoorMiddleware — the operations it scopes', () => { expect(ran).toBe(false); }); }); + +/** + * #33891 — in a cloud-managed process the door also leaves out the rows the + * settings routes hide (`cloud-managed-settings.ts`): every `storage` row and + * every row of a hidden `ai` key. Driven hosted and self-hosted (the control) + * on the same rows; a system context reads them all either way. + */ +for (const managed of [true, false]) { + describe(`the read door, ${managed ? 'cloud-managed' : 'self-hosted (control)'}`, () => { + beforeEach(async () => { + if (managed) process.env.OS_CLOUD_MANAGED = '1'; + else delete process.env.OS_CLOUD_MANAGED; + resetCloudManagedForTesting(); + for (const [namespace, key] of [['storage', 'adapter'], ['ai', 'provider'], ['ai', 'openai_api_key'], ['ai', 'trace_enabled']]) { + await engine.insert('sys_setting', { + namespace, key, scope: 'tenant', user_id: null, value: 'v', value_enc: null, + encrypted: false, locked: false, locked_reason: null, + }, SYS); + await engine.insert('sys_platform_setting', { + namespace, key, value: 'v', value_enc: null, encrypted: false, locked: false, locked_reason: null, + }, SYS); + } + }); + afterEach(() => { + delete process.env.OS_CLOUD_MANAGED; + resetCloudManagedForTesting(); + }); + + const hostedRows = async (object: string, as: any): Promise => + ((await engine.find(object, { where: { namespace: { $in: ['storage', 'ai'] } } }, as)) as any[]) + .map((r) => `${r.namespace}.${r.key}`).sort(); + + for (const object of ['sys_setting', 'sys_platform_setting']) { + it(`${object}: a reader holding every capability ${managed ? 'reads no storage row and no hidden ai key' : 'reads every row'}`, async () => { + const rows = await hostedRows(object, BOTH); + if (managed) expect(rows).toEqual(['ai.trace_enabled']); + else expect(rows).toEqual(['ai.openai_api_key', 'ai.provider', 'ai.trace_enabled', 'storage.adapter']); + }); + + it(`${object}: a count agrees with the list`, async () => { + expect(await engine.count(object, { where: { namespace: { $in: ['storage', 'ai'] } } }, BOTH)).toBe(managed ? 1 : 4); + }); + + it(`${object}: a system context reads every row`, async () => { + expect(await hostedRows(object, SYS)).toEqual(['ai.openai_api_key', 'ai.provider', 'ai.trace_enabled', 'storage.adapter']); + }); + } + }); +} diff --git a/packages/services/service-settings/src/settings-read-door.ts b/packages/services/service-settings/src/settings-read-door.ts index 70ecaba7cfe..7a938df9616 100644 --- a/packages/services/service-settings/src/settings-read-door.ts +++ b/packages/services/service-settings/src/settings-read-door.ts @@ -35,10 +35,22 @@ * * A context that is not system and carries no capability holds none, so it * reads no namespace at all: the deny baseline, not a hand-through. + * + * ## Cloud-managed (#33891) + * + * In a cloud-managed process the door also ANDs in + * {@link cloudManagedRowScope}: no row of a namespace the platform manages + * whole (`storage`), and no row of a key it manages (`ai`'s provider, model, + * credentials and generation defaults). The settings routes hide the same + * table (`cloud-managed-settings.ts`), so a caller reading the rows here + * learns nothing the settings door would not show. A system context still + * reads every row, which is how the storage and AI services keep reading + * the values the platform configured. */ import type { IObjectQLEngine } from '@objectstack/spec/contracts'; import type { SettingsService } from './settings-service.js'; +import { cloudManagedRowScope } from './cloud-managed-settings.js'; /** The objects whose rows carry a settings `namespace`. */ export const SETTINGS_READ_DOOR_OBJECTS: readonly string[] = Object.freeze([ @@ -87,6 +99,10 @@ export function settingsReadDoorMiddleware(service: SettingsService): EngineMidd if (scope) { ast.where = ast.where ? { $and: [ast.where, scope] } : scope; } + const hosted = cloudManagedRowScope(); + if (hosted) { + ast.where = ast.where ? { $and: [ast.where, hosted] } : hosted; + } return next(); }; } diff --git a/packages/services/service-settings/src/settings-routes.ts b/packages/services/service-settings/src/settings-routes.ts index 26d9e6f8826..5bbbce6db9e 100644 --- a/packages/services/service-settings/src/settings-routes.ts +++ b/packages/services/service-settings/src/settings-routes.ts @@ -59,6 +59,19 @@ import { SettingsService } from './settings-service.js'; // nothing that leaves over HTTP may carry it. See the module header for the // mask shape and why it mirrors ADR-0100's encrypted-field convention. import { dropEchoedSecretMasks, redactSecretValues } from './settings-secret-redaction.js'; +// [#33891] What a cloud-managed environment does not offer at these doors: one +// table, asked by every route below and by the data-API read door. +import { + SETTINGS_CLOUD_MANAGED_CODE, + SETTINGS_CLOUD_MANAGED_STATUS, + SettingsCloudManagedError, + assertActionServed, + assertNamespaceServed, + assertWriteServed, + projectKeyed, + projectManifest, + projectManifestList, +} from './cloud-managed-settings.js'; import { DEPLOYMENT_NOTICE_CAPABILITY, type DeploymentNoticeDoor } from './deployment-notice.js'; import { SettingsCryptoUnavailableError, @@ -277,6 +290,12 @@ export function registerSettingsRoutes( } catch (err: any) { if (relayAuthzStoreOutage(res, err)) return; if (relayApiKeyLifecycleRefusal(res, err)) return; + // [#33891] One spelling for every route: the hosted refusal is the + // runtime's state, answered alike wherever it is met. + if (err instanceof SettingsCloudManagedError) { + sendError(res, SETTINGS_CLOUD_MANAGED_STATUS, SETTINGS_CLOUD_MANAGED_CODE, err.message, { details: err.details }); + return; + } route.refuse(res, err); } }) satisfies RouteHandler); @@ -286,7 +305,8 @@ export function registerSettingsRoutes( async serve(req, res, ctx) { // Served as the namespace read serves them: a sourced key's options. const manifests = service.listManifests(ctx, { locale: requestLocaleOf(req) }); - sendOk(res, { manifests }); + // [#33891] A hosted caller is not offered what the platform manages. + sendOk(res, { manifests: projectManifestList(manifests) }); }, refuse(res, err) { if (err instanceof SettingsForbiddenError) { @@ -300,6 +320,9 @@ export function registerSettingsRoutes( mountFamilyRoute('get', `${base}/:namespace`, { async serve(req, res, ctx) { const ns = req.params.namespace; + // [#33891] Asked first: a namespace the platform manages whole is not a + // page here, whoever asks. + assertNamespaceServed(ns, 'read'); // The request's language names a served option no longer offered. const payload = await service.getNamespace(ns, ctx, { locale: requestLocaleOf(req) }); // The page states what is LIVE, not only what is stored: the owning @@ -321,11 +344,12 @@ export function registerSettingsRoutes( // and every `cascadeChain` entry of a secret-backed key are masked; // `source`, `locked` and `lockedReason` are untouched, so the console's // "configured" state and the env-lock affordances read the same as before. + // [#33891] A per-key projection leaves the hidden keys out of all three. sendOk(res, { ...payload, - manifest, - values: redactSecretValues(payload.values, service.secretKeysOf(ns)), - ...(live ? { live } : {}), + manifest: projectManifest(manifest), + values: projectKeyed(ns, redactSecretValues(payload.values, service.secretKeysOf(ns))), + ...(live ? { live: projectKeyed(ns, live) } : {}), }); }, refuse(res, err) { @@ -363,6 +387,10 @@ export function registerSettingsRoutes( ), ); } + // [#33891] A write that names a key the platform manages is refused + // whole, before anything is applied: the same all-or-nothing answer + // `setMany` gives a write that names an unknown key. + assertWriteServed(ns, Object.keys(body)); // #7522 — the echoed-mask no-op. GET now answers a secret with the mask; // a form that submits back what it read means "unchanged", so the key is // dropped rather than persisted as the mask's literal text. Resolved here @@ -439,6 +467,8 @@ export function registerSettingsRoutes( mountFamilyRoute('post', `${base}/:namespace/:actionId`, { async serve(req, res, ctx) { const { namespace, actionId } = req.params; + // [#33891] The actions that exercise or clear what the platform manages. + assertActionServed(namespace, actionId); const result = await service.runAction(namespace, actionId, req.body, ctx, { locale: requestLocaleOf(req) }); // The 200/400 split is PRE-EXISTING and preserved verbatim: an action // that ran and reported `ok: false` is still answered 400. Whether a