fix(medications): let a manager end a course and serve End only to who may press it

POST /api/medications/{id}/courses/end resolved the caller with
requireAuth(), so a delegate managing the record got 403 while the
medication PUT that used to carry the end date admits MANAGE, and the
reads still served canEndCourse true. The action now resolves the record
at MANAGE over medications and files the previous end (C4) with the
count of tombstoned placeholders.

The medication reads narrow canEndCourse and canStartCourse to the
caller: End needs MANAGE, starting a course stays owner-only. The list
cell stays per record and the narrowing runs after it. Create and edit
answers pass the grant they were resolved under instead of null.

Registered in the sharing surface guard, the MANAGE handler matrix and
the activity feed's verb lines.

Refs #1280
This commit is contained in:
Marc-André Bombeck committed 2026-10-25 00:26:55 +02:00
1 parent 3984ceb01c
commit 8fd1d543a6
28 files changed
+421 -102

No files matched your search

@@ -12,12 +12,17 @@
* `medications.course.notRunning` while no course is running, the same rule
* the reads publish as `canEndCourse`.
*
* Owner-only, like the other course routes.
* MANAGE over the record's medications, the level the medication's own PUT
* (which used to carry the end date) is written at: a manager running
* somebody's regimen may end a course they could already end through the
* edit. Starting, editing and removing courses stay owner-only. The reads
* publish `canEndCourse` false to a caller below that level
* (`course-authority.ts`), so no client offers the button this refuses.
*/
import { NextRequest } from "next/server";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { auditLog } from "@/lib/auth/audit";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { withIdempotency } from "@/lib/idempotency";
@@ -28,6 +33,7 @@ import {
endCurrentCourse,
} from "@/lib/medications/courses";
import { dayKeyOfDate } from "@/lib/medications/course-window";
import { overwriteDetails } from "@/lib/sharing/audit-details";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
export const dynamic = "force-dynamic";
@@ -42,11 +48,11 @@ async function postEndCourse(
request: NextRequest,
{ params }: RouteParams,
): Promise<Response> {
const { user } = await requireAuth();
const { user } = await requireRecordAuth("manage", "medications");
const { id } = await params;
try {
const window = await endCurrentCourse({
const { window, previous, droppedPlaceholders } = await endCurrentCourse({
userId: user.id,
medicationId: id,
timeZone: user.timezone || DEFAULT_TIMEZONE,
@@ -60,7 +66,16 @@ async function postEndCourse(
await auditLog("medication.course.end", {
userId: user.id,
ipAddress: getClientIp(request),
details: { medicationId: id, ...body },
// C4: the end the course had before, so a manager's End reads back
// out of the trail; and how many pending slots it took with it.
details: {
medicationId: id,
...overwriteDetails({
before: { endsOn: previous.endsOn, endedAt: previous.endedAt },
after: { endsOn: window.endsOn, endedAt: window.endedAt },
}),
droppedPlaceholders,
},
});
annotate({
action: { name: "medication.course.end" },
+2 -1
View File
@@ -36,7 +36,7 @@ export const PUT = apiHandler(
// excludes every actioned row — and the previous cadence is the one
// genuinely unrecoverable part, which is what C7 puts in the audit row.
// The DELETE beside it stays refused.
const { user, authMethod } = await requireRecordAuth(
const { user, authMethod, grantId } = await requireRecordAuth(
"manage",
"medications",
);
@@ -60,6 +60,7 @@ export const PUT = apiHandler(
const outcome = await updateMedication({
user,
grantId,
authMethod,
id,
existing,
+12 -3
View File
@@ -13,12 +13,16 @@ import {
unstableExternalIdShape,
} from "@/lib/validations/external-id";
import { readMedicationsListCached } from "@/lib/medications/list-read";
import {
courseActionAuthority,
withCourseActionAuthority,
} from "@/lib/medications/course-authority";
import { createMedication } from "@/lib/medications/create-medication";
import { withIdempotency } from "@/lib/idempotency";
import { NextRequest } from "next/server";
export const GET = apiHandler(async () => {
const { user } = await requireRecordAuth("read", "medications");
const { user, grantId } = await requireRecordAuth("read", "medications");
// Cache the list shape on userId. The 60 s fresh TTL bounds the
// cross-midnight staleness window for `todayEventCount` and the
@@ -30,7 +34,11 @@ export const GET = apiHandler(async () => {
// `invalidateUserMedications({ evict: true })` before the next read
// lands; background sync paths mark the bucket stale instead. The RSC
// wrapper (`src/app/medications/page.tsx`) shares this exact cell.
const result = await readMedicationsListCached(user);
const cached = await readMedicationsListCached(user);
// The cell is the record's; End and Start are narrowed to the caller after
// it, so one caller's authority never lands in another's answer (#1280).
const authority = await courseActionAuthority(grantId);
const result = cached.map((row) => withCourseActionAuthority(row, authority));
annotate({
action: { name: "medication.list" },
@@ -55,7 +63,7 @@ async function postMedication(request: NextRequest): Promise<Response> {
// it afterwards — `PUT /api/medications/[id]` and the DELETE beside it stay
// on `requireAuth()` and refuse under a switch. Adding is help; rewriting
// the owner's cabinet is not.
const { user } = await requireRecordAuth("write", "medications");
const { user, grantId } = await requireRecordAuth("write", "medications");
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 64 * 1024,
@@ -80,6 +88,7 @@ async function postMedication(request: NextRequest): Promise<Response> {
const outcome = await createMedication({
user,
grantId,
data: parsed.data,
ipAddress: getClientIp(request),
});