mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
fix: recover managed sharing boundaries
This commit is contained in:
1 parent
01562b4aef
commit
d86358f3e4
96 files changed
+3578
-397
No files matched your search
+11
-1
@@ -780,7 +780,7 @@ export interface RecordAuthContext extends AuthContext {
|
||||
* the fail-closed lever: a delegable route without a classification does not
|
||||
* typecheck, so the set of routes carrying one cannot fall behind the set of
|
||||
* routes that are delegable. The value is frozen per module by
|
||||
* `src/__tests__/delegable-surface-guard.test.ts` and reviewed against the
|
||||
* `src/__tests__/sharing-surface-guard.test.ts` and reviewed against the
|
||||
* design's clustering table; this function only enforces what was declared.
|
||||
*/
|
||||
export async function requireRecordAuth(
|
||||
@@ -934,6 +934,16 @@ async function resolveSwitchedRecord(
|
||||
if (refusal !== null) throw denied(refusal);
|
||||
|
||||
getEvent()?.setActingAs(owner.id);
|
||||
// v1.37.0 — and whether this request may spend the owner's provider budget.
|
||||
// MANAGE opens the generated reads; it does not open the generation behind
|
||||
// them, because the owner would pay for and consent to an egress they did
|
||||
// not cause. A managed profile is the exception and the reason the marker is
|
||||
// read here rather than the grant: it has no self to protect from its own
|
||||
// guardian. Stamped where the owner row is already loaded, so no generator
|
||||
// has to be told; see `src/lib/sharing/delegated-generation.ts`.
|
||||
if (owner.id !== auth.user.id && owner.managedProfileAt === null) {
|
||||
getEvent()?.setDelegatedGenerationSuppressed();
|
||||
}
|
||||
// Fire-and-forget, the `ApiToken.lastUsedAt` posture: the read must not wait
|
||||
// on the bookkeeping, and the bookkeeping failing must not fail the read.
|
||||
void touchGrantUsage(grant.id);
|
||||
|
||||
@@ -26,6 +26,21 @@ export interface IllnessDayLogWriteResult {
|
||||
existed: boolean;
|
||||
/** The full DTO of the written row — no second round-trip needed. */
|
||||
dto: IllnessDayLogDTO;
|
||||
/**
|
||||
* v1.37.0 — what this write destroyed, for the caller's audit row.
|
||||
*
|
||||
* The upsert is a rewrite wearing a create's verb: its UPDATE branch forces
|
||||
* `deletedAt: null`, so it revives a day the owner deliberately deleted, and
|
||||
* the symptom write is a full replacement of that day's links. Under MANAGE
|
||||
* somebody other than the owner can do both, so the two facts that would
|
||||
* otherwise vanish silently travel back with the result.
|
||||
*/
|
||||
replaced: {
|
||||
/** Symptom keys the day carried before this write, sorted. */
|
||||
previousSymptomKeys: string[];
|
||||
/** True when the write brought a tombstoned day back. */
|
||||
revived: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
/** A symptom selection carrying its catalog key + optional 0–3 severity. */
|
||||
@@ -105,7 +120,7 @@ export async function upsertIllnessDayLog(
|
||||
// run in ONE interactive transaction: no torn state between the link delete
|
||||
// + create halves, and no second round-trip — the written row (with its
|
||||
// flattened symptom links) comes straight back as the DTO.
|
||||
const { row, existed } = await prisma.$transaction(async (tx) => {
|
||||
const { row, existed, replaced } = await prisma.$transaction(async (tx) => {
|
||||
const existing = await tx.illnessDayLog.findUnique({
|
||||
where,
|
||||
select: {
|
||||
@@ -113,6 +128,11 @@ export async function upsertIllnessDayLog(
|
||||
functionalImpact: true,
|
||||
feverC: true,
|
||||
noteEncrypted: true,
|
||||
// v1.37.0 — the two facts the caller's audit row needs. Read inside
|
||||
// the same transaction as the write, so what is reported is what was
|
||||
// actually replaced rather than what a second read happened to see.
|
||||
deletedAt: true,
|
||||
symptomLinks: { select: { symptom: { select: { key: true } } } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -171,8 +191,17 @@ export async function upsertIllnessDayLog(
|
||||
include: dayLogSymptomInclude,
|
||||
});
|
||||
|
||||
return { row: full, existed: existing !== null };
|
||||
return {
|
||||
row: full,
|
||||
existed: existing !== null,
|
||||
replaced: {
|
||||
previousSymptomKeys: (existing?.symptomLinks ?? [])
|
||||
.map((link) => link.symptom.key)
|
||||
.sort(),
|
||||
revived: existing?.deletedAt != null,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
return { id: row.id, existed, dto: toIllnessDayLogDTO(row) };
|
||||
return { id: row.id, existed, dto: toIllnessDayLogDTO(row), replaced };
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* v1.37.0 — C5 at the choke point: a delegated read enqueues no generation.
|
||||
*
|
||||
* The MANAGE level opens the ten generated reads. Nine of them reach the
|
||||
* provider through `resolveReadOnlyStatusMiss`, one hop behind a GET that
|
||||
* looks like a cache read, so a manager's first visit to a metric page used to
|
||||
* ship the owner's health data to the owner's provider on the owner's budget
|
||||
* under the owner's consent receipt — with nothing in the response saying so.
|
||||
*
|
||||
* The suppression is implemented once, here, rather than in the ten generators
|
||||
* that call this function, so this file is where it has to be pinned. Both
|
||||
* directions, because either one alone is worthless: without the positive
|
||||
* control a broken function that never enqueues anything passes, and without
|
||||
* the negative one the condition is not tested at all.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const enqueueStatusGeneration = vi.fn(async () => {});
|
||||
const hasUsableStatusProvider = vi.fn(async () => true);
|
||||
const statusConsentBlocksGeneration = vi.fn(async () => false);
|
||||
const suppressed = vi.fn(() => false);
|
||||
|
||||
vi.mock("@/lib/jobs/insight-status-generate-shared", () => ({
|
||||
enqueueStatusGeneration: (...args: unknown[]) =>
|
||||
enqueueStatusGeneration(...(args as [])),
|
||||
STATUS_GENERATE_QUEUE: "insight-status-generate",
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/insights/status-provider", () => ({
|
||||
hasUsableStatusProvider: (...args: unknown[]) =>
|
||||
hasUsableStatusProvider(...(args as [])),
|
||||
statusConsentBlocksGeneration: (...args: unknown[]) =>
|
||||
statusConsentBlocksGeneration(...(args as [])),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/sharing/delegated-generation", () => ({
|
||||
delegatedGenerationSuppressed: () => suppressed(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
// The last-good text and the negative-cache probe both read the audit
|
||||
// ledger; an empty ledger is the cold-cache case this function is for.
|
||||
auditLog: {
|
||||
findMany: vi.fn(async () => []),
|
||||
findFirst: vi.fn(async () => null),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { resolveReadOnlyStatusMiss } from "@/lib/insights/status-cache";
|
||||
|
||||
beforeEach(() => {
|
||||
// Every counter, not only the enqueue: the ordering assertion below reads
|
||||
// the provider probe's call count, and a counter carried over from the
|
||||
// previous test would make it fail for the wrong reason (or pass for one).
|
||||
enqueueStatusGeneration.mockClear();
|
||||
hasUsableStatusProvider.mockClear();
|
||||
statusConsentBlocksGeneration.mockClear();
|
||||
suppressed.mockReturnValue(false);
|
||||
hasUsableStatusProvider.mockResolvedValue(true);
|
||||
statusConsentBlocksGeneration.mockResolvedValue(false);
|
||||
});
|
||||
|
||||
const ARGS = {
|
||||
userId: "owner-1",
|
||||
metric: "WEIGHT" as never,
|
||||
locale: "en" as never,
|
||||
};
|
||||
|
||||
describe("resolveReadOnlyStatusMiss — the delegated path", () => {
|
||||
it("enqueues a generation for the person whose record it is", async () => {
|
||||
// The positive control. If this stops holding, the assertion below stops
|
||||
// meaning anything: "nothing was enqueued" would be true of a function
|
||||
// that never enqueues.
|
||||
const outcome = await resolveReadOnlyStatusMiss(ARGS);
|
||||
|
||||
expect(enqueueStatusGeneration).toHaveBeenCalledTimes(1);
|
||||
expect(outcome.kind).toBe("preparing");
|
||||
});
|
||||
|
||||
it("enqueues nothing while somebody else is holding the request", async () => {
|
||||
suppressed.mockReturnValue(true);
|
||||
|
||||
const outcome = await resolveReadOnlyStatusMiss(ARGS);
|
||||
|
||||
expect(enqueueStatusGeneration).not.toHaveBeenCalled();
|
||||
// Still served, not refused: the read is admitted at MANAGE and only the
|
||||
// generation behind it is withheld.
|
||||
expect(outcome.kind).toBe("preparing");
|
||||
if (outcome.kind === "preparing") {
|
||||
expect(outcome.revalidating).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("decides before it asks whether a provider exists", async () => {
|
||||
// Ordering matters for the money question, not only for the enqueue: the
|
||||
// provider probe reads the owner's configuration, and a suppressed
|
||||
// request has no business touching it.
|
||||
suppressed.mockReturnValue(true);
|
||||
|
||||
await resolveReadOnlyStatusMiss(ARGS);
|
||||
|
||||
expect(hasUsableStatusProvider).not.toHaveBeenCalled();
|
||||
expect(statusConsentBlocksGeneration).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "@/lib/insights/correlation-discovery";
|
||||
import { MAX_CUSTOM_CORRELATION_CHANNELS } from "@/lib/insights/correlation-channel-series";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { delegatedGenerationSuppressed } from "@/lib/sharing/delegated-generation";
|
||||
import type { SupportedLocale } from "@/lib/insights/status-shared";
|
||||
|
||||
/**
|
||||
@@ -559,6 +560,30 @@ export async function resolveReadOnlyStatusMiss(args: {
|
||||
metric: InsightStatusScope;
|
||||
locale: SupportedLocale;
|
||||
}): Promise<ReadOnlyMissOutcome> {
|
||||
// v1.37.0 — the one gate on the delegated path, and it sits here rather
|
||||
// than in the ten generators that reach this function precisely because it
|
||||
// is one gate: a generator added next year inherits it without knowing it
|
||||
// exists. A manager holding a MANAGE grant may READ the record's generated
|
||||
// assessments; the miss behind that read must not ship the owner's data to
|
||||
// the owner's provider on the owner's budget. Served the same way the
|
||||
// negative-cache branch below serves it: last-good text if there is any,
|
||||
// `preparing` if there is not, and nothing enqueued either way.
|
||||
if (delegatedGenerationSuppressed()) {
|
||||
const lastGood = await readLastGoodStatusText({
|
||||
userId: args.userId,
|
||||
cacheAction: statusCacheAction(args.metric, args.locale),
|
||||
});
|
||||
annotate({
|
||||
action: { name: "insights.status.preparing" },
|
||||
meta: {
|
||||
metric: args.metric,
|
||||
suppressed_enqueue: true,
|
||||
delegated: true,
|
||||
},
|
||||
});
|
||||
return { kind: "preparing", lastGood, revalidating: false };
|
||||
}
|
||||
|
||||
const hasProvider = await hasUsableStatusProvider(args.userId);
|
||||
if (!hasProvider) return { kind: "no-provider" };
|
||||
|
||||
|
||||
@@ -102,6 +102,21 @@ export class WideEventBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.37.0 — record that provider generation is closed on this request.
|
||||
*
|
||||
* Merges for the same reason `setActingAs` does, and is stamped in the same
|
||||
* place: the record resolver, which is where the owner row is in hand. It is
|
||||
* read back through `delegatedGenerationSuppressed()`.
|
||||
*/
|
||||
setDelegatedGenerationSuppressed(): this {
|
||||
this.event.auth = {
|
||||
...(this.event.auth ?? {}),
|
||||
delegated_generation: "suppressed",
|
||||
};
|
||||
return this;
|
||||
}
|
||||
|
||||
setAction(action: WideEvent["action"]): this {
|
||||
this.event.action = action;
|
||||
return this;
|
||||
|
||||
@@ -66,6 +66,16 @@ export interface WideEvent {
|
||||
* dashboard that conflates them cannot answer either.
|
||||
*/
|
||||
acting_as?: string;
|
||||
/**
|
||||
* v1.37.0 — set when this request is acting on somebody else's record and
|
||||
* that somebody could have asked for the generation themselves. It is the
|
||||
* one fact the generated reads consult before enqueuing a provider job:
|
||||
* a manager's navigation must not spend the owner's budget or ship the
|
||||
* owner's record to the owner's provider. Absent means "generate as
|
||||
* usual", which is what every self-request, every guardian request on a
|
||||
* managed profile and every background job is.
|
||||
*/
|
||||
delegated_generation?: "suppressed";
|
||||
};
|
||||
|
||||
// Business-Daten (was wurde getan)
|
||||
|
||||
@@ -59,8 +59,15 @@ export interface ApplyCanonicalSlotWriteInput {
|
||||
* the worker-minted pending row like every other write, and a fresh
|
||||
* create keeps the historical reminder provenance. `APPLE_HEALTH`
|
||||
* (v1.28) is the bulk route's HealthKit dose-event import.
|
||||
*
|
||||
* v1.37.0 — `IMPORT` joined the union because the per-event edit route
|
||||
* re-creates a moved dose and must carry the ORIGINAL row's provenance onto
|
||||
* the converged row (C8). A dose that came in through a history import and
|
||||
* had its time corrected is still an imported dose; stamping it `WEB`
|
||||
* because a human moved it is a small lie the compliance history then
|
||||
* repeats forever.
|
||||
*/
|
||||
createSource: "WEB" | "API" | "REMINDER" | "APPLE_HEALTH";
|
||||
createSource: "WEB" | "API" | "REMINDER" | "APPLE_HEALTH" | "IMPORT";
|
||||
/**
|
||||
* v1.36.x — refuse a write that would change an outcome the owner has
|
||||
* already recorded, instead of applying it last-write-wins.
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* v1.37.0 — the two audit-detail shapes MANAGE is admitted on.
|
||||
*
|
||||
* The rule the level ships under is "reconstructable or refused": a manager
|
||||
* may change and remove things in somebody else's record, and the owner must
|
||||
* be able to read out of their own activity feed what went missing. The tree
|
||||
* did not carry that. Every edit filed an id and nothing else — `measurement.
|
||||
* update` said `{ measurementId }`, `medication.update` said `{ medicationId }`
|
||||
* — so the feed could say a reading changed and could not say from what, and
|
||||
* the hard deletes filed the id of a row that no longer exists.
|
||||
*
|
||||
* These two helpers are what the admitted verbs use instead. They are small on
|
||||
* purpose: the audit table is not a second copy of the record and must not
|
||||
* become one. Three columns, not thirty, and never a decrypted note.
|
||||
*
|
||||
* Both return a plain object meant to be SPREAD into a `details` literal at
|
||||
* the call site rather than to replace it. The literal keeps naming the row's
|
||||
* own id in the reviewer's line of sight, which is what the structural guard
|
||||
* reads, and the spread carries the part that is tedious to write by hand and
|
||||
* easy to get wrong.
|
||||
*/
|
||||
|
||||
/**
|
||||
* What may enter an audit row.
|
||||
*
|
||||
* A closed union rather than `unknown`, because the failure it prevents is the
|
||||
* one that costs the most: `details: { previous: existing }` is one keystroke
|
||||
* from `details: { previous: { …, notesEncrypted } }`, and an encrypted note
|
||||
* copied into the audit table is PHI with a second retention policy and no
|
||||
* rotation story. A caller with a value outside this union has to decide what
|
||||
* the feed should say about it, which is the decision this type exists to
|
||||
* force.
|
||||
*/
|
||||
export type AuditScalar = string | number | boolean | Date | null | undefined;
|
||||
|
||||
/** The longest string that lands verbatim; anything longer is trimmed. */
|
||||
const MAX_VALUE_LENGTH = 120;
|
||||
|
||||
function coerce(value: AuditScalar): string | number | boolean | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
if (typeof value === "string") {
|
||||
return value.length > MAX_VALUE_LENGTH
|
||||
? `${value.slice(0, MAX_VALUE_LENGTH)}…`
|
||||
: value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function same(a: AuditScalar, b: AuditScalar): boolean {
|
||||
const left = a instanceof Date ? a.getTime() : (a ?? null);
|
||||
const right = b instanceof Date ? b.getTime() : (b ?? null);
|
||||
return left === right;
|
||||
}
|
||||
|
||||
/**
|
||||
* **C4** — what an overwrite replaced.
|
||||
*
|
||||
* `fields` names the family the write touched, so the owner's feed can say
|
||||
* "changed the value and the time" rather than "changed a reading".
|
||||
* `previous` carries the values that are gone, for the fields where a handful
|
||||
* of scalars is the whole fact.
|
||||
*
|
||||
* @param before the pre-image, caller-picked field by field. Never the row
|
||||
* object: picking is the review step, and a spread of the row is how an
|
||||
* encrypted column gets into an audit table.
|
||||
* @param after the post-image over the same keys. Fields whose value did not
|
||||
* move are left out of both halves — an edit that renamed nothing should not
|
||||
* file a line saying it did.
|
||||
* @param redacted fields that changed and whose values must never be written:
|
||||
* free text, anything encrypted at rest. They appear in `fields` and never
|
||||
* in `previous`, which is the honest answer — the feed says the note was
|
||||
* rewritten and does not say what it said.
|
||||
*/
|
||||
export function overwriteDetails(args: {
|
||||
before: Record<string, AuditScalar>;
|
||||
after: Record<string, AuditScalar>;
|
||||
redacted?: readonly string[];
|
||||
}): {
|
||||
fields: string[];
|
||||
previous: Record<string, string | number | boolean | null>;
|
||||
} {
|
||||
const previous: Record<string, string | number | boolean | null> = {};
|
||||
const fields: string[] = [];
|
||||
|
||||
for (const key of Object.keys(args.before)) {
|
||||
if (same(args.before[key], args.after[key])) continue;
|
||||
fields.push(key);
|
||||
previous[key] = coerce(args.before[key]);
|
||||
}
|
||||
for (const key of args.redacted ?? []) {
|
||||
if (!fields.includes(key)) fields.push(key);
|
||||
}
|
||||
|
||||
return { fields: fields.sort(), previous };
|
||||
}
|
||||
|
||||
/**
|
||||
* **C3** — what a hard delete destroyed.
|
||||
*
|
||||
* For the verbs whose domain does not tombstone, where the row is gone the
|
||||
* moment the transaction commits and the audit row is the only thing left. It
|
||||
* names the model, the id, a human label and the date the thing was about,
|
||||
* which is the difference between "a preventive-care reminder was deleted" and
|
||||
* "the colonoscopy recall for next March was deleted".
|
||||
*
|
||||
* `extra` is for the one or two domain facts a label cannot carry — a
|
||||
* severity, a dose, a count. Scalars only, same reasoning as above.
|
||||
*/
|
||||
export function destroyedDetails(args: {
|
||||
model: string;
|
||||
id: string;
|
||||
label: AuditScalar;
|
||||
effectiveAt: AuditScalar;
|
||||
extra?: Record<string, AuditScalar>;
|
||||
}): Record<string, string | number | boolean | null> {
|
||||
const details: Record<string, string | number | boolean | null> = {
|
||||
destroyedModel: args.model,
|
||||
destroyedId: args.id,
|
||||
destroyedLabel: coerce(args.label),
|
||||
destroyedAt: coerce(args.effectiveAt),
|
||||
};
|
||||
for (const [key, value] of Object.entries(args.extra ?? {})) {
|
||||
details[key] = coerce(value);
|
||||
}
|
||||
return details;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* v1.37.0 — whether this request may spend the record owner's provider budget.
|
||||
*
|
||||
* MANAGE opens the generated surfaces: a manager opens a metric page and reads
|
||||
* the assessment that is already there. What it must not open is the hop
|
||||
* behind that read. Nine of the ten generated reads enqueue a generation job
|
||||
* on a cache miss (`resolveReadOnlyStatusMiss`) and the narrative enqueues one
|
||||
* whenever the row is stale, so on a delegated request the sequence is: the
|
||||
* manager navigates, the owner's health data leaves the box under the owner's
|
||||
* consent receipt, against the owner's provider, on the owner's budget, and
|
||||
* the owner sees a bill line for something they did not do. The manager sees a
|
||||
* card. Nothing on the wire says the two are the same event.
|
||||
*
|
||||
* So the read stays and the enqueue goes, on exactly one condition: somebody
|
||||
* else is holding the request and the record has an owner who could have
|
||||
* pressed the button themselves. A managed profile has nobody in that
|
||||
* position — its guardian IS the person who decides what it generates — so the
|
||||
* suppression does not apply there, and the guardian surfaces that trigger
|
||||
* generation deliberately are its own list.
|
||||
*
|
||||
* Read from the request context rather than from an argument, the same
|
||||
* reasoning `actingActorFor` states in `src/lib/auth/audit.ts`: the fact is
|
||||
* settled once, in the resolver, where the owner row is in hand — and threading
|
||||
* it through ten generator modules would be a second answer to "who is asking",
|
||||
* with the routes that forgot to pass it being the ones nobody reviewed. A
|
||||
* caller with no request context (every worker, every cron pass) reads false
|
||||
* and generates as it always did, which is the correct answer for work nobody
|
||||
* navigated into.
|
||||
*/
|
||||
export function delegatedGenerationSuppressed(): boolean {
|
||||
return getEvent()?.getAuth()?.delegated_generation === "suppressed";
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
* holds nothing else: no predicate, no storage, no route knowledge. The
|
||||
* predicates live in `grants.ts` beside the rest of what a grant means, and
|
||||
* the per-route classification lives on the call sites, frozen by
|
||||
* `src/__tests__/delegable-surface-guard.test.ts`.
|
||||
* `src/__tests__/sharing-surface-guard.test.ts`.
|
||||
*
|
||||
* Two properties are the whole reason the file exists separately.
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user