Skip to content

Commit 18752aa

Browse files
committed
Merge remote-tracking branch 'origin/main' into claude/project-thread-gg1w7r
2 parents cf0c0fe + 6f9f008 commit 18752aa

12 files changed

Lines changed: 704 additions & 85 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-messaging': patch
3+
---
4+
5+
feat(service-messaging): the notification preference's `quiet_hours` declares the `quiet-hours` widget
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`sys_notification_preference.quiet_hours` now carries `widget: 'quiet-hours'`, so the console draws its quiet-hours control (a time-zone picker and two times) instead of the JSON editor, as `topic` and `channel` already name their pick-or-type inputs. The field stays `json` with the same stored shape, `{ tz?, start: 'HH:MM', end: 'HH:MM' }`, and nothing new is refused. `field-types.mdx` documents the three notification preference widgets.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/cloud-connection': patch
3+
---
4+
5+
fix(cloud-connection): an unmanaged grant refused after the control plane granted it writes the environment's `package_unmanaged_import` failure row
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
cloud#3624 ruling A has both sides audit an unmanaged install. Before this, the environment wrote its `package_unmanaged_import` row only when the copy's import ran. A grant refused before the import left the control plane's grant row with no environment outcome. That covers the install-local door's install capability (403), the manifest fetch, the walled catalog and the protocol handshake, and the cloud-connection door's own two refusals.
11+
12+
- **The install-local door's refusals of a grant.** The cloud-connection door now hands the in-process door the grant beside the request: `install(request, { grant })`, with the package, version, environment and installer. When the door answers a grant with a refusal that its unmanaged copy did not already audit, it hands the `audit` slot one `package_unmanaged_import` event. The event has `outcome: 'failure'` and the answer's code and HTTP status. A throw is audited with the status it resolves to, then rethrown. The import's own success and failure events are unchanged and are never written twice.
13+
- **The cloud-connection door's own refusals.** A grant it cannot read (502) and an environment without the install-local door (503) each hand the environment's `audit` slot the same failure event. The multi-tenant slot is the environment kernel's; the single-environment slot is the host's.
14+
- **What is not audited.** A plain `POST /api/v1/marketplace/install-local` call, which no grant started, writes no row for a refusal. Nor do a control-plane refusal, a managed install, and the cloud-connection door's checks before the control plane is called. No grant exists for any of them.
15+
- The events go through the `audit` slot, never as a hand-built row. An audit slot that throws changes no answer, and the failure is logged at `error`. The row's metadata keys are the ones #30964 shipped. The refusal row names the granted marketplace package id, and carries `environment_id`, because the grant names its environment.

‎content/docs/data-modeling/field-types.mdx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,6 +1139,20 @@ has none, the list is empty, or the load fails, the field is a text box that
11391139
takes the typed name; a failure is shown with its cause, and the box stays
11401140
editable.
11411141

1142+
### Notification preference inputs (`notification-topic`, `notification-channel`, `quiet-hours`)
1143+
1144+
The platform's notification preference (`sys_notification_preference`) declares three
1145+
widgets, so the record form offers choices instead of a bare box:
1146+
1147+
| Widget | Field | Draws | Stores |
1148+
|---|---|---|---|
1149+
| `notification-topic` | `topic` (`text`; also on `sys_notification_template`) | a pick-or-type list from `GET /api/v1/messaging/preference-options` | the topic as written, `*` for all |
1150+
| `notification-channel` | `channel` (`text`) | the same list, marking a known channel whose service is not configured | the channel id as written, `*` for all |
1151+
| `quiet-hours` | `quiet_hours` (`json`) | a time-zone picker and two times | `{ tz?, start: 'HH:MM', end: 'HH:MM' }` |
1152+
1153+
A typed topic or channel the list does not hold is still stored. Like every `widget` value,
1154+
a name no host registers falls back to the type's default input.
1155+
11421156
### A widget's face on the record heading
11431157

11441158
A `text` field that declares `widget: 'recipient-picker'` or `widget: 'object-ref'` is drawn

‎packages/cloud-connection/src/cloud-connection-plugin.test.ts‎

Lines changed: 79 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -403,14 +403,25 @@ describe('[#30964] an unmanaged grant hands the copy to the environment\'s insta
403403
async function grant(opts: {
404404
body?: Record<string, unknown>;
405405
answer?: { status?: number; json: unknown };
406-
door?: { install: (r: Request) => Promise<Response> } | null;
406+
door?: { install: (r: Request, options?: { grant?: unknown }) => Promise<Response> } | null;
407407
singleEnvironment?: boolean;
408+
/** [#31481] The audit slot throws. */
409+
auditThrows?: boolean;
408410
} = {}) {
409411
const rawApp = makeRawApp();
410-
const seen: { request?: Request; body?: any } = {};
412+
const seen: { request?: Request; body?: any; options?: any } = {};
413+
// [#31481] The environment's `audit` slot, recording what it is handed.
414+
const auditEvents: any[] = [];
415+
const audit = {
416+
recordPackageLifecycleEvent: async (event: unknown) => {
417+
if (opts.auditThrows) throw new Error('ledger offline');
418+
auditEvents.push(event);
419+
},
420+
};
411421
const door = opts.door === null ? undefined : opts.door ?? {
412-
install: vi.fn(async (request: Request) => {
422+
install: vi.fn(async (request: Request, options?: { grant?: unknown }) => {
413423
seen.request = request;
424+
seen.options = options;
414425
seen.body = await request.json();
415426
return new Response(JSON.stringify({ success: true, data: { installMode: 'unmanaged', targetPackageId: 'com.acme.crm-copy' } }), { status: 200 });
416427
}),
@@ -419,11 +430,12 @@ describe('[#30964] an unmanaged grant hands the copy to the environment\'s insta
419430
getServiceAsync: async (name: string) => {
420431
if (name === 'auth') return sessionAuth('user-1');
421432
if (name === 'marketplace-install-local' && door) return door;
433+
if (name === 'audit') return audit;
422434
throw new Error(`no ${name}`);
423435
},
424436
};
425437
const services: Record<string, any> = opts.singleEnvironment
426-
? { auth: sessionAuth('user-1'), ...(door ? { 'marketplace-install-local': door } : {}) }
438+
? { auth: sessionAuth('user-1'), audit, ...(door ? { 'marketplace-install-local': door } : {}) }
427439
: { 'env-registry': { resolveByHostname: async () => ({ environmentId: ENV }) }, 'kernel-manager': { getOrCreate: async () => envKernel } };
428440
const { ctx, fireKernelReady } = makeCtx({ rawApp, services });
429441
const answer = opts.answer ?? { json: { success: true, data: { install_mode: 'unmanaged', version_id: 'ver_9', version: '2.0.0' } } };
@@ -437,7 +449,7 @@ describe('[#30964] an unmanaged grant hands the copy to the environment\'s insta
437449
const res = await rawApp.routes.get('POST /api/v1/cloud-connection/install')!(
438450
cWithCookie(opts.body ?? { package_id: 'pkg_1', install_mode: 'unmanaged' }),
439451
);
440-
return { res, door, seen, fetchSpy, logger: ctx.logger };
452+
return { res, door, seen, fetchSpy, auditEvents, logger: ctx.logger };
441453
}
442454

443455
it('copies the granted version through the door, as the caller (their own headers), and answers the door\'s answer', async () => {
@@ -532,4 +544,66 @@ describe('[#30964] an unmanaged grant hands the copy to the environment\'s insta
532544
expect(res.payload.error.code).toBe('SERVICE_UNAVAILABLE');
533545
expect(res.payload.error.message).toContain('Nothing was copied');
534546
});
547+
548+
// ── [#31481, ruling A「两边审计」] a refusal after the grant leaves the environment's audit row ──
549+
550+
/** The failure event this door hands for a grant it refuses itself. */
551+
const refusedGrant = (errorCode: string, status: number) => ({
552+
action: 'package_unmanaged_import',
553+
packageId: 'pkg_1',
554+
version: '2.0.0',
555+
environmentId: ENV,
556+
actor: 'user-1',
557+
outcome: 'failure',
558+
errorCode,
559+
status,
560+
});
561+
562+
it('[#31481] the door is handed the grant beside the request: package, version, environment and installer', async () => {
563+
const { res, seen, auditEvents } = await grant();
564+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
565+
expect(seen.options).toEqual({ grant: { packageId: 'pkg_1', version: '2.0.0', environmentId: ENV, actor: 'user-1' } });
566+
// The copy's own events are the door's; this door writes none for a copy it handed over.
567+
expect(auditEvents).toEqual([]);
568+
});
569+
570+
it('[#31481] a grant it cannot read hands the environment\'s audit slot one failure event (502), in either deployment', async () => {
571+
for (const singleEnvironment of [false, true]) {
572+
const { res, auditEvents } = await grant({
573+
singleEnvironment,
574+
answer: { json: { success: true, data: { install_mode: 'unmanaged', version: '2.0.0' } } },
575+
});
576+
expect(res.status).toBe(502);
577+
expect(auditEvents).toEqual([refusedGrant('PLUGIN_INSTALL_FAILED', 502)]);
578+
}
579+
});
580+
581+
it('[#31481] no install-local door hands the environment\'s audit slot one failure event (503)', async () => {
582+
const { res, auditEvents } = await grant({ door: null });
583+
expect(res.status).toBe(503);
584+
expect(auditEvents).toEqual([refusedGrant('SERVICE_UNAVAILABLE', 503)]);
585+
});
586+
587+
it('[#31481] a door refusal is the door\'s to audit: this door hands no second event', async () => {
588+
const door = { install: vi.fn(async () => new Response(JSON.stringify({ success: false, error: { code: 'FORBIDDEN', message: 'nope' } }), { status: 403 })) };
589+
const { res, auditEvents } = await grant({ door });
590+
expect(res.status).toBe(403);
591+
expect(auditEvents).toEqual([]);
592+
});
593+
594+
it('[#31481] no grant, no event: a control-plane refusal and a managed install hand none', async () => {
595+
const refused = await grant({ answer: { status: 403, json: { success: false, error: { code: 'FORBIDDEN', message: 'not entitled' } } } });
596+
expect(refused.auditEvents).toEqual([]);
597+
const managed = await grant({ body: { package_id: 'pkg_1' }, answer: { json: { success: true, data: { installed: true } } } });
598+
expect(managed.auditEvents).toEqual([]);
599+
});
600+
601+
it('[#31481] an audit slot that throws changes no answer, and is logged at error', async () => {
602+
const { res, logger } = await grant({ door: null, auditThrows: true });
603+
expect(res.status).toBe(503);
604+
expect(res.payload.error.code).toBe('SERVICE_UNAVAILABLE');
605+
const errors = (logger.error as any).mock.calls.map((call: unknown[]) => String(call[0])).join('\n');
606+
expect(errors).toContain('package_unmanaged_import');
607+
expect(errors).toContain('ledger offline');
608+
});
535609
});

‎packages/cloud-connection/src/cloud-connection-plugin.ts‎

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,10 @@ import { CLOUD_CONNECTION_CAPABILITY, CLOUD_CONNECTION_UI_BUNDLE } from './cloud
155155
import { readJsonRequestBody } from './request-json-body.js';
156156
// [#30964] The install mode's one declaration, read by reference: never a copy of its two spellings.
157157
import { InstallModeSchema, type InstallMode } from '@objectstack/spec/kernel';
158-
import { INSTALL_LOCAL_DOOR_SERVICE, type InstallLocalDoor } from './install-local-door-service.js';
158+
import {
159+
INSTALL_LOCAL_DOOR_SERVICE, grantRefusalEvent, recordUnmanagedImportEvent,
160+
type InstallLocalDoor, type InstallLocalDoorGrant, type UnmanagedImportAuditSurface,
161+
} from './install-local-door-service.js';
159162

160163
const CLOUD_CONNECTION_PREFIX = '/api/v1/cloud-connection';
161164

@@ -1046,7 +1049,7 @@ export class CloudConnectionPlugin implements Plugin {
10461049
const json: any = await resp.json().catch(() => ({ success: false, error: 'install failed (no body)' }));
10471050
// [#30964] A control-plane refusal, and every managed answer, is relayed as it was.
10481051
if (installMode !== 'unmanaged' || !resp.ok || json?.success === false) return c.json(json, resp.status as any);
1049-
return await copyOnUnmanagedGrant(c, { environmentId, packageId, seedSampleData, grant: json });
1052+
return await copyOnUnmanagedGrant(c, { environmentId, packageId, seedSampleData, installerUserId: session.userId, grant: json });
10501053
} catch (err: any) {
10511054
ctx.logger?.error?.('[CloudConnectionPlugin] install failed', err instanceof Error ? err : new Error(String(err)));
10521055
return c.json({ success: false, error: { code: 'PLUGIN_INSTALL_FAILED', message: String(err?.message ?? err) } }, 502);
@@ -1069,14 +1072,47 @@ export class CloudConnectionPlugin implements Plugin {
10691072
* cloud branch always has. Fail closed: an answer that does not echo
10701073
* the mode, or names no version, copies nothing (502). A
10711074
* `data.manifest` in the answer is never read.
1075+
*
1076+
* [#31481, ruling A「两边审计」] Every refusal after the grant leaves
1077+
* the environment's `package_unmanaged_import` failure row beside
1078+
* the control plane's grant row, through the environment's `audit`
1079+
* slot: this door's own two (the grant it cannot read, 502; no
1080+
* install-local door, 503) here, and the door's, which it audits
1081+
* itself when handed the grant ({@link InstallLocalDoor.install}).
10721082
*/
10731083
const copyOnUnmanagedGrant = async (
10741084
c: any,
1075-
args: { environmentId: string; packageId: string; seedSampleData: boolean; grant: any },
1085+
args: { environmentId: string; packageId: string; seedSampleData: boolean; installerUserId: string; grant: any },
10761086
): Promise<Response> => {
1077-
const { environmentId, packageId, seedSampleData, grant } = args;
1087+
const { environmentId, packageId, seedSampleData, installerUserId, grant } = args;
10781088
const data = grant?.data;
10791089
const versionId = typeof data?.version_id === 'string' ? data.version_id.trim() : '';
1090+
const granted: InstallLocalDoorGrant = {
1091+
packageId,
1092+
...(typeof data?.version === 'string' && data.version.trim() !== '' ? { version: data.version.trim() } : {}),
1093+
environmentId,
1094+
actor: installerUserId,
1095+
};
1096+
// The environment's own services: its kernel's, multi-tenant; the host's, single-environment.
1097+
let kernel: EnvironmentKernel | undefined;
1098+
if (!this.cfg.singleEnvironment) {
1099+
try {
1100+
kernel = await ctx.getService<EnvironmentKernelManager>('kernel-manager')?.getOrCreate?.(environmentId);
1101+
} catch { /* no environment kernel */ }
1102+
}
1103+
const environmentService = async <T>(name: string): Promise<T | undefined> => {
1104+
if (this.cfg.singleEnvironment) {
1105+
try { return ctx.getService<T>(name); } catch { return undefined; }
1106+
}
1107+
let found: T | undefined;
1108+
try { found = await kernel?.getServiceAsync?.<T>(name); } catch { /* not registered */ }
1109+
if (!found) { try { found = kernel?.getService?.<T>(name); } catch { /* not registered */ } }
1110+
return found;
1111+
};
1112+
const auditRefusal = async (errorCode: string, status: number): Promise<void> => {
1113+
const audit = await environmentService<UnmanagedImportAuditSurface>('audit');
1114+
await recordUnmanagedImportEvent(audit, ctx.logger, 'CloudConnectionPlugin', grantRefusalEvent(granted, errorCode, status));
1115+
};
10801116
// An answer with no `install_mode` at all may come from a control
10811117
// plane that does not read the param, and so may already have
10821118
// installed the package MANAGED; the refusal says so, so the
@@ -1094,6 +1130,7 @@ export class CloudConnectionPlugin implements Plugin {
10941130
`[CloudConnectionPlugin] the unmanaged install of ${packageId} in ${environmentId} was not copied: `
10951131
+ `the control plane's grant could not be read (${unread}).${managedNote}`,
10961132
);
1133+
await auditRefusal('PLUGIN_INSTALL_FAILED', 502);
10971134
return c.json({
10981135
success: false,
10991136
error: {
@@ -1103,18 +1140,9 @@ export class CloudConnectionPlugin implements Plugin {
11031140
},
11041141
}, 502);
11051142
}
1106-
let door: InstallLocalDoor | undefined;
1107-
try {
1108-
if (this.cfg.singleEnvironment) {
1109-
door = ctx.getService<InstallLocalDoor>(INSTALL_LOCAL_DOOR_SERVICE);
1110-
} else {
1111-
const kernels = ctx.getService<EnvironmentKernelManager>('kernel-manager');
1112-
const kernel = await kernels?.getOrCreate?.(environmentId);
1113-
try { door = await kernel?.getServiceAsync?.<InstallLocalDoor>(INSTALL_LOCAL_DOOR_SERVICE); } catch { /* not registered */ }
1114-
if (!door) { try { door = kernel?.getService?.<InstallLocalDoor>(INSTALL_LOCAL_DOOR_SERVICE); } catch { /* not registered */ } }
1115-
}
1116-
} catch { /* no door */ }
1143+
const door = await environmentService<InstallLocalDoor>(INSTALL_LOCAL_DOOR_SERVICE);
11171144
if (!door || typeof door.install !== 'function') {
1145+
await auditRefusal('SERVICE_UNAVAILABLE', 503);
11181146
return c.json({
11191147
success: false,
11201148
error: {
@@ -1137,7 +1165,8 @@ export class CloudConnectionPlugin implements Plugin {
11371165
...(seedSampleData ? { seedSampleData: true } : {}),
11381166
}),
11391167
});
1140-
const answer = await door.install(request);
1168+
// The grant rides beside the request, so the door audits its own refusals of it.
1169+
const answer = await door.install(request, { grant: granted });
11411170
const body = await answer.json().catch(() => ({
11421171
success: false,
11431172
error: { code: 'PLUGIN_INSTALL_FAILED', message: `The unmanaged copy of '${packageId}' answered no body.` },

0 commit comments

Comments
 (0)