Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/35172-owner-only-fallback-warn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/plugin-sharing': patch
'@objectstack/cli': patch
---

fix(plugin-sharing): a hierarchy scope that falls back to owner-only for want of a resolver now says so once per boot

Clause-②: no
Metadata-protocol: none

When a permission set grants a hierarchy scope (`own_and_reports`, `unit`, `unit_and_below`) and no `hierarchy-scope-resolver` service is registered (the `hierarchy-security` capability, provided by `@objectstack/security-enterprise`), the sharing layer fails closed to owner-only. It used to do so without a word, so a runtime booted without the CLI gave an operator nothing to explain why every user saw only their own records.

- The first time the fallback is taken, the sharing service logs one `warn` naming the capability, its provider and the owner-only consequence. It is logged once per service instance, which is once per boot, never once per request.
- Nothing is logged for an app that never asks for a hierarchy scope, or when a resolver is registered.
- The answer does not change: the scope still resolves to the caller alone.
- `os validate`, `os verify` and `os serve` no longer end the `hierarchy-security` advisory with "and no log line says so": for that token they now say the runtime logs one warning, opening `[sharing] hierarchy scope NOT widened`, the first time it falls back. Other enterprise tokens keep their wording.
4 changes: 3 additions & 1 deletion packages/cli/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5475,7 +5475,9 @@ export default class Serve extends Command {
// only from the app's own `plugins[]`, a cloud-only tier from a cloud
// runtime. The loop below stays quiet for those (they are known
// vocabulary, not typos), and the sharing layer then fails closed to
// owner-only without a word. Say it once at start-up, in the sentence
// owner-only; the runtime logs that once, at the first fallback, which
// may be long after boot. So say it here too, once at start-up and
// before any request, in the sentence
// `os validate` and `os verify` print for the same token, and only when
// nothing in `plugins[]` provides it. A warning, never a refusal: the
// boot is unchanged.
Expand Down
37 changes: 32 additions & 5 deletions packages/cli/src/utils/capability-preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,48 @@ export function renderCapabilityMessage(c: DeclaredCapabilityClassification): st
export const ENTERPRISE_ABSENCE_CONSEQUENCE: Readonly<Record<string, string>> = Object.freeze({
// The sharing layer fails CLOSED without the `hierarchy-scope-resolver`
// service (`SharingService.resolveOwnerScopeIds`, ADR-0057): a hierarchy
// scope never widens, and nothing logs it.
// scope never widens. What the runtime logs about it is
// {@link ENTERPRISE_ABSENCE_RUNTIME_NOTICE}'s row.
'hierarchy-security':
"the hierarchy scopes (`own_and_reports`, `unit`, `unit_and_below`) behave as owner-only",
});

/**
* The warning the RUNTIME itself logs when an `enterprise` token's fallback is
* taken, for the tokens whose runtime says so; the value is that warning's
* opening words, as the operator will find them in the server log. A token
* with no row here ends its sentence "and no log line says so", which is true
* only while its runtime stays silent — so a runtime that starts logging adds
* its row here in the same change, or the CLI goes on claiming a silence the
* server log contradicts.
*
* A separate table rather than a clause folded into
* {@link ENTERPRISE_ABSENCE_CONSEQUENCE}: the consequence is what the METADATA
* does, the notice is what the RUNTIME says, and a token can have either one
* without the other. Every key is pinned to an enterprise-edition registry row
* in `capability-preflight.test.ts`.
*/
export const ENTERPRISE_ABSENCE_RUNTIME_NOTICE: Readonly<Record<string, string>> = Object.freeze({
// `SharingService.resolveOwnerScopeIds` (plugin-sharing) logs this once per
// boot, at `warn`, the first time a hierarchy scope falls back to owner-only.
'hierarchy-security': '[sharing] hierarchy scope NOT widened',
});

/**
* The consequence sentence for an `enterprise` token with no provider wired in.
* It names the edition that enforces the token and what the open edition does
* instead, and nothing else: no product pitch, one fact an author can act on.
* It names the edition that enforces the token, what the open edition does
* instead, and whether the runtime says so — nothing else: no product pitch,
* one fact an author can act on.
*/
export function enterpriseAbsenceConsequence(token: string): string {
const shape = Object.prototype.hasOwnProperty.call(ENTERPRISE_ABSENCE_CONSEQUENCE, token)
const has = (table: Readonly<Record<string, string>>) => Object.prototype.hasOwnProperty.call(table, token);
const shape = has(ENTERPRISE_ABSENCE_CONSEQUENCE)
? ENTERPRISE_ABSENCE_CONSEQUENCE[token]
: `nothing provides "${token}", and the metadata that relies on it is not enforced`;
return `Only the enterprise edition enforces it: without a wired provider, as on the open edition, ${shape}, and no log line says so.`;
const said = has(ENTERPRISE_ABSENCE_RUNTIME_NOTICE)
? `and the runtime logs one warning ("${ENTERPRISE_ABSENCE_RUNTIME_NOTICE[token]} …") the first time it falls back`
: 'and no log line says so';
return `Only the enterprise edition enforces it: without a wired provider, as on the open edition, ${shape}, ${said}.`;
}

/** {@link renderCapabilityMessage} without the package prefix. */
Expand Down
22 changes: 22 additions & 0 deletions packages/cli/test/capability-preflight.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
import {
ENTERPRISE_ABSENCE_CONSEQUENCE,
ENTERPRISE_ABSENCE_RUNTIME_NOTICE,
enterpriseAbsenceConsequence,
judgeDeclaredCapabilities,
preflightDeclaredCapabilities,
preflightProviderWiring,
Expand Down Expand Up @@ -384,6 +386,26 @@ describe('the enterprise consequence sentence', () => {
}
});

it('every runtime-notice row keys an enterprise-edition registry token', () => {
for (const token of Object.keys(ENTERPRISE_ABSENCE_RUNTIME_NOTICE)) {
expect(PLATFORM_CAPABILITY_PROVIDERS[token]?.edition, token).toBe('enterprise');
}
});

it('hierarchy-security no longer claims silence: it names the warning the runtime logs', () => {
const m = enterpriseAbsenceConsequence('hierarchy-security');
expect(m).not.toContain('no log line says so');
// The prefix plugin-sharing's HIERARCHY_RESOLVER_ABSENT_NOTICE opens with.
expect(m).toContain('[sharing] hierarchy scope NOT widened');
});

it('CONTROL: a token whose runtime logs nothing still says so', () => {
const m = enterpriseAbsenceConsequence('fixture-enterprise-token');
expect(Object.prototype.hasOwnProperty.call(ENTERPRISE_ABSENCE_RUNTIME_NOTICE, 'fixture-enterprise-token')).toBe(false);
expect(m).toContain('no log line says so');
expect(m).not.toContain('[sharing]');
});

it('hierarchy-security names the owner-only fallback, absent and unwired alike', async () => {
const absent = renderCapabilityMessage(classifyRequiredCapability('hierarchy-security', () => false));
const [unwired] = await preflightProviderWiring({
Expand Down
93 changes: 92 additions & 1 deletion packages/plugins/plugin-sharing/src/sharing-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { assertEngineDeleteDispatch } from '@objectstack/objectql';
import { SharingService, type SharingServiceOptions } from './sharing-service.js';
import {
SharingService,
HIERARCHY_RESOLVER_ABSENT_NOTICE,
type SharingServiceOptions,
} from './sharing-service.js';
import { buildSharingMiddleware } from './sharing-plugin.js';
import { bootRequestContext } from './exec-context-seam.testkit.js';
import { SysRecordShare } from './objects/sys-record-share.object.js';
Expand Down Expand Up @@ -2367,3 +2371,90 @@ describe('[#14484] grant stamps organization_id on both halves of the upsert', (
expect(engine._tables.sys_record_share[0].organization_id).toBe(ORG_CALLER);
});
});

describe('[ADR-0057] a missing hierarchy-scope resolver is said once per boot', () => {
const MANAGER_PROBE = {
hasWriteBypass: async () => false,
resolveWriteScope: async () => 'unit_and_below' as const,
};
const notices = (warn: ReturnType<typeof vi.fn>) =>
warn.mock.calls.filter((c) => c[0] === HIERARCHY_RESOLVER_ABSENT_NOTICE);

let engine: ReturnType<typeof makeFakeEngine>;
beforeEach(() => {
engine = makeFakeEngine({ account: ACCOUNT_SCHEMA, sys_record_share: {} });
engine._tables.account = [{ id: 'a1', name: 'Acme', owner_id: 'alice' }];
});

it('the notice names the capability, its registry provider and the owner-only consequence', () => {
expect(HIERARCHY_RESOLVER_ABSENT_NOTICE).toContain('"hierarchy-security"');
expect(HIERARCHY_RESOLVER_ABSENT_NOTICE).toContain('@objectstack/security-enterprise');
expect(HIERARCHY_RESOLVER_ABSENT_NOTICE).toContain('owner-only');
// `os validate` / `os verify` / `os serve` quote these opening words
// (`ENTERPRISE_ABSENCE_RUNTIME_NOTICE` in the CLI's capability-preflight).
expect(HIERARCHY_RESOLVER_ABSENT_NOTICE.startsWith('[sharing] hierarchy scope NOT widened')).toBe(true);
});

it('a hierarchy scope with no resolver warns ONCE across two calls, and still answers owner-only', async () => {
const warn = vi.fn();
const svc = new SharingService({ engine, securityService: () => MANAGER_PROBE, logger: { warn } });
const bob = await bootRequestContext({ userId: 'bob', activeOrganizationId: 'org_a' });
const resolve = (s: any) => (svc as any).resolveOwnerScopeIds(bob, s);

expect(await resolve('unit_and_below')).toEqual(['bob']);
expect(await resolve('own_and_reports')).toEqual(['bob']);
// Through a public gate too: the verdict is the owner-only one.
expect(await svc.canManageShares('account', 'a1', bob)).toBe(false);

expect(notices(warn)).toHaveLength(1);
expect(notices(warn)[0][1]).toMatchObject({
capability: 'hierarchy-security',
provider: '@objectstack/security-enterprise',
scope: 'unit_and_below',
});
});

it('a fresh service instance (a new boot) says it again', async () => {
const warn = vi.fn();
const bob = await bootRequestContext({ userId: 'bob', activeOrganizationId: 'org_a' });
for (let boot = 0; boot < 2; boot++) {
const svc = new SharingService({ engine, logger: { warn } });
expect(await (svc as any).resolveOwnerScopeIds(bob, 'unit')).toEqual(['bob']);
}
expect(notices(warn)).toHaveLength(2);
});

it('CONTROL: non-hierarchy scopes take no fallback and log nothing', async () => {
const warn = vi.fn();
const svc = new SharingService({ engine, logger: { warn } });
const bob = await bootRequestContext({ userId: 'bob', activeOrganizationId: 'org_a' });
for (const scope of [undefined, 'own', 'org'] as const) {
expect(await (svc as any).resolveOwnerScopeIds(bob, scope)).toEqual(['bob']);
}
expect(await svc.canManageShares('account', 'a1', { userId: 'alice' })).toBe(true);
expect(warn).not.toHaveBeenCalled();
});

it('CONTROL: a registered resolver takes no fallback and logs nothing', async () => {
const warn = vi.fn();
const svc = new SharingService({
engine,
securityService: () => MANAGER_PROBE,
hierarchyResolver: () => ({ resolveOwnerIds: async () => ['bob', 'alice'] }),
tenancy: () => ({ posture: 'single' }),
logger: { warn },
});
const bob = await bootRequestContext({ userId: 'bob', activeOrganizationId: 'org_a' });
expect(await (svc as any).resolveOwnerScopeIds(bob, 'unit_and_below')).toEqual(['bob', 'alice']);
expect(notices(warn)).toHaveLength(0);
});

it('a throwing logger neither fails the gate nor throws again', async () => {
const warn = vi.fn(() => { throw new Error('sink down'); });
const svc = new SharingService({ engine, logger: { warn } });
const bob = await bootRequestContext({ userId: 'bob', activeOrganizationId: 'org_a' });
expect(await (svc as any).resolveOwnerScopeIds(bob, 'unit')).toEqual(['bob']);
expect(await (svc as any).resolveOwnerScopeIds(bob, 'unit')).toEqual(['bob']);
expect(warn).toHaveBeenCalledTimes(1);
});
});
58 changes: 56 additions & 2 deletions packages/plugins/plugin-sharing/src/sharing-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
// since commit aa4b90d9a (the full-envelope ruling: no per-site subset contracts). Annotating the
// implementations with a narrower shape is what forced this file to cast its
// way out of its own contract to read fields the caller had already supplied.
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { PLATFORM_CAPABILITY_PROVIDERS, type ExecutionContext } from '@objectstack/spec/kernel';
// [commit 3f64fe6c6] The engine's own answer to "which column is this object walled
// by?" — the twin of `SqlDriver.computeTenantField`, so the organization a grant
// is stamped from is read off the SAME column the wall scopes the record by.
Expand Down Expand Up @@ -443,6 +443,30 @@ export const PHANTOM_ANCHOR_WRITE_DENY_NOTICE =
'injected anchor, not a remote column, so ownership can never match; ' +
'declare the real remote owner column or change the sharing model';

/**
* [ADR-0057] The provider of the `hierarchy-security` capability, read from the
* capability registry so this line names the SAME package `os validate`,
* `os verify` and `os serve` name for the token.
*/
const HIERARCHY_SECURITY_PROVIDER =
PLATFORM_CAPABILITY_PROVIDERS['hierarchy-security'].package;

/**
* [ADR-0057] Logged ONCE per service instance (one per boot), the first time a
* hierarchy scope (`own_and_reports` / `unit` / `unit_and_below`) is asked for
* while no `hierarchy-scope-resolver` service is registered — the moment
* {@link SharingService.resolveOwnerScopeIds} falls back to owner-only. A
* functional degradation (the scope is narrower, nothing is lost), hence WARN.
* The CLI says the same at `os serve` start; this is the line a runtime booted
* without the CLI prints.
*/
export const HIERARCHY_RESOLVER_ABSENT_NOTICE =
'[sharing] hierarchy scope NOT widened: capability "hierarchy-security" has no provider — ' +
`no hierarchy-scope-resolver service is registered (${HIERARCHY_SECURITY_PROVIDER} provides it), ` +
'so the hierarchy scopes (`own_and_reports`, `unit`, `unit_and_below`) behave as owner-only. ' +
`Install ${HIERARCHY_SECURITY_PROVIDER} and add its plugin to \`plugins[]\` to widen them. ` +
'Logged once per boot.';

/**
* [#27662] The second silent cause of the same refusal: a federated object
* whose owner column is NOT the phantom anchor — the author mapped a remote
Expand Down Expand Up @@ -682,6 +706,20 @@ export class SharingService implements ISharingService {
*/
private readonly phantomAnchorNotified = new Set<string>();

/**
* [ADR-0057] Has {@link HIERARCHY_RESOLVER_ABSENT_NOTICE} been logged?
*
* One boolean per service instance. The plugin builds ONE service at
* `kernel:ready`, so this is once per boot, while the fallback it reports
* runs on every read, write and share-management gate. The condition is a
* property of the composition, not of the caller or the object, so no key
* finer than the instance adds anything but repeats. Set only when the
* fallback is TAKEN: an app that never asks for a hierarchy scope logs
* nothing. It records no verdict — the resolver is still looked up on every
* call, so the returned ids never depend on it.
*/
private hierarchyResolverAbsenceNoted = false;

constructor(options: SharingServiceOptions) {
this.engine = options.engine;
this.hierarchyResolver = options.hierarchyResolver;
Expand Down Expand Up @@ -2474,7 +2512,23 @@ export class SharingService implements ISharingService {
const me = String(context.userId);
if (!scope || scope === 'own' || scope === 'org') return [me];
const resolver = this.hierarchyResolver?.();
if (!resolver) return [me];
if (!resolver) {
if (!this.hierarchyResolverAbsenceNoted) {
// Latch BEFORE the log, so a throwing logger cannot turn one line
// into one throw per request (#6783's ordering).
this.hierarchyResolverAbsenceNoted = true;
try {
this.logger?.warn?.(HIERARCHY_RESOLVER_ABSENT_NOTICE, {
capability: 'hierarchy-security',
provider: HIERARCHY_SECURITY_PROVIDER,
scope,
});
} catch {
/* a diagnostic must never fail, or change, an access verdict */
}
}
return [me];
}

const organizationId = activeOrganizationId(context);
if (organizationId === null && this.organizationScopeRequired()) {
Expand Down
Loading