mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
feat: list the guardians of a managed profile
- add GET /api/managed-profiles/{id}/guardians, cookie-only, refusing
anybody who is not an active guardian of that profile with the same 404
an unknown id gets
- disclose the grant id, the party block already shared between grant
parties, the derived state and the two timestamps, and nothing else
- publish the route in the OpenAPI contract
This commit is contained in:
1 parent
110511ff31
commit
365ba8c2eb
5 files changed
+635
No files matched your search
@@ -12743,6 +12743,43 @@ paths:
|
||||
$ref: "#/components/schemas/ErrorEnvelope"
|
||||
"422": *a3
|
||||
"429": *a4
|
||||
/api/managed-profiles/{id}/guardians:
|
||||
get:
|
||||
tags:
|
||||
- Account sharing
|
||||
summary: Who looks after a managed profile
|
||||
description: "The live Guardians of one managed profile — every unexpired, unrevoked MANAGE grant on it, PENDING and
|
||||
ACTIVE alike. Cookie transport only, by the same structural argument as the rest of this family: it resolves
|
||||
through the session and never falls through to the Bearer branch. A fresh second factor is NOT required, unlike
|
||||
every act on the same profile: this is a read, and it discloses nothing about a party the caller cannot already
|
||||
read on their own sharing panel. An ACTOR surface — the profile is named in the path and the caller acts as
|
||||
themselves, so it answers from the Guardian's own account rather than only while switched into the record.
|
||||
Anyone who is not an active Guardian of THIS profile gets the same 404 as an unknown id, including a READ, WRITE
|
||||
or MANAGE delegate of an ordinary record: the refusal is not an enumeration oracle. Count the ACTIVE rows to
|
||||
know whether removing a Guardian is possible — a PENDING invitation does not satisfy the last-Guardian floor."
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
schema:
|
||||
type: string
|
||||
required: true
|
||||
responses:
|
||||
"200":
|
||||
description: The profile's live Guardians, oldest invitation first.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ManagedProfileGuardianListEnvelope"
|
||||
"401": *a1
|
||||
"404":
|
||||
description: "No such managed profile, or the caller is not one of its Guardians (`meta.errorCode:
|
||||
managed_profile.not_found`). The two are byte-identical."
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorEnvelope"
|
||||
"422": *a3
|
||||
"429": *a4
|
||||
/api/account/switch:
|
||||
post:
|
||||
tags:
|
||||
@@ -37258,6 +37295,57 @@ components:
|
||||
- data
|
||||
- error
|
||||
additionalProperties: false
|
||||
ManagedProfileGuardianListEnvelope:
|
||||
type: object
|
||||
properties:
|
||||
data:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/ManagedProfileGuardian"
|
||||
error:
|
||||
type: "null"
|
||||
meta:
|
||||
type: object
|
||||
properties:
|
||||
requestId:
|
||||
type: string
|
||||
additionalProperties: false
|
||||
required:
|
||||
- data
|
||||
- error
|
||||
additionalProperties: false
|
||||
ManagedProfileGuardian:
|
||||
type: object
|
||||
properties:
|
||||
grantId:
|
||||
type: string
|
||||
description: The grant row. This is the value `DELETE /api/managed-profiles/{id}/guardians/{grantId}` takes.
|
||||
account:
|
||||
$ref: "#/components/schemas/AccountGrantParty"
|
||||
state:
|
||||
type: string
|
||||
enum:
|
||||
- PENDING
|
||||
- ACTIVE
|
||||
description: "PENDING means the invitation has been sent and not yet accepted. A PENDING Guardian does NOT count toward
|
||||
the last-Guardian floor: the server counts accepted, unexpired MANAGE grants, so inviting somebody and then
|
||||
trying to leave is still refused until they accept. Say so before the act rather than letting it arrive as a
|
||||
409."
|
||||
invitedAt:
|
||||
type: string
|
||||
acceptedAt:
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: "null"
|
||||
required:
|
||||
- grantId
|
||||
- account
|
||||
- state
|
||||
- invitedAt
|
||||
- acceptedAt
|
||||
additionalProperties: false
|
||||
description: "One person who looks after a managed profile. Ended grants — revoked or expired — are absent rather than
|
||||
listed with a state: the question is who looks after this record now."
|
||||
AccountSwitchEnvelope:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
@@ -4,6 +4,7 @@ import { z } from "zod/v4";
|
||||
import {
|
||||
apiHandler,
|
||||
MFA_STEP_UP_MAX_AGE_SECONDS,
|
||||
requireCookieAuth,
|
||||
requireFreshMfa,
|
||||
} from "@/lib/api-handler";
|
||||
import {
|
||||
@@ -14,12 +15,57 @@ import {
|
||||
} from "@/lib/api-response";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { listManagedProfileGuardians } from "@/lib/managed-profiles/guardian-list";
|
||||
import { ManagedProfileLifecycleError } from "@/lib/managed-profiles/lifecycle";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { GrantError, inviteManagedProfileGuardian } from "@/lib/sharing/grants";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* Who looks after this profile.
|
||||
*
|
||||
* The read the panel needs before it can offer to remove anybody, and the one
|
||||
* the last-Guardian floor is counted from before the click rather than
|
||||
* discovered as a 409 after it.
|
||||
*
|
||||
* Cookie-only, like every endpoint in this family, and for the same structural
|
||||
* reason: `requireCookieAuth` resolves through `getSession()` and never falls
|
||||
* through to the Bearer branch. Fresh MFA is deliberately NOT required — this
|
||||
* is a read, and it discloses nothing the caller cannot already read on their
|
||||
* own sharing panel about a party to a grant they hold. The gate belongs to the
|
||||
* acts, not to looking.
|
||||
*
|
||||
* An actor surface: the profile is named by the URL, and the caller acts as
|
||||
* themselves. `requireRecordAuth` / `requireGuardianAuth` would make the roster
|
||||
* answerable only while switched INTO the profile, which is backwards for a
|
||||
* panel whose whole purpose is to work from the Guardian's own account.
|
||||
*/
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireCookieAuth();
|
||||
const { id } = await params;
|
||||
|
||||
const guardians = await listManagedProfileGuardians({
|
||||
profileId: id,
|
||||
callerId: user.id,
|
||||
});
|
||||
// One refusal for "no such account", "not a managed profile" and "you are
|
||||
// not a Guardian of it", so the route is not an enumeration oracle.
|
||||
if (guardians === null) {
|
||||
return apiError("Managed profile not found", 404, {
|
||||
errorCode: "managed_profile.not_found",
|
||||
});
|
||||
}
|
||||
|
||||
annotate({
|
||||
action: { name: "managed_profile.guardian.list" },
|
||||
meta: { profile_id: id, guardian_count: guardians.length },
|
||||
});
|
||||
return apiSuccess(guardians);
|
||||
},
|
||||
);
|
||||
|
||||
const INVITE_LIMIT = 10;
|
||||
const INVITE_WINDOW_MS = 60 * 60 * 1000;
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { activeGuardianWhere } from "@/lib/managed-profiles/lifecycle";
|
||||
import { grantState } from "@/lib/sharing/grants";
|
||||
import { GRANT_PARTY_SELECT, type GrantParty } from "@/lib/sharing/grant-view";
|
||||
|
||||
/**
|
||||
* v1.37.0 — who looks after one managed profile.
|
||||
*
|
||||
* The read the removal route always needed. `DELETE
|
||||
* /api/managed-profiles/{id}/guardians/{grantId}` shipped with integration
|
||||
* coverage and no caller, because nothing in the product could hand a browser a
|
||||
* `grantId` for it: `GET /api/account/grants` returns the CALLER's grants, and
|
||||
* a Guardian grant has the PROFILE as grantor, so a Guardian's given-list never
|
||||
* contains one.
|
||||
*
|
||||
* ## What it discloses, and what it deliberately does not
|
||||
*
|
||||
* `GRANT_PARTY_SELECT` — `{ id, username, displayName }` — and nothing else per
|
||||
* Guardian. That is exactly what one party to a grant already sees of another
|
||||
* on the sharing panel today, so this route widens nobody's reach; it makes
|
||||
* reachable, on the record's own page, a fact the same person can already read
|
||||
* one page over. No e-mail, no channel data, no `lastUsedAt`.
|
||||
*
|
||||
* `access` and `scope` are omitted because they are constants here: a Guardian
|
||||
* grant is always `MANAGE` with `scope: null` (`inviteManagedProfileGuardian`),
|
||||
* and publishing a constant invites a client to branch on it.
|
||||
*
|
||||
* ## Why `state` is derived and not read
|
||||
*
|
||||
* Through `grantState()`, the same function the request resolver's own
|
||||
* predicate is built on. A second derivation from `acceptedAt` would drift in
|
||||
* the dangerous direction — a roster saying "accepted" about a grant the
|
||||
* resolver has stopped honouring, or the reverse — and this roster is what the
|
||||
* card counts to decide whether a remove control may exist at all.
|
||||
*
|
||||
* EXPIRED and REVOKED rows are filtered out rather than published. The question
|
||||
* this answers is "who looks after this record NOW"; an ended Guardian grant is
|
||||
* history that belongs to the grant panel, not to a floor calculation.
|
||||
*/
|
||||
export interface ManagedProfileGuardianView {
|
||||
/** The grant row's id — what `DELETE .../guardians/{grantId}` takes. */
|
||||
grantId: string;
|
||||
account: GrantParty;
|
||||
state: "PENDING" | "ACTIVE";
|
||||
invitedAt: string;
|
||||
acceptedAt: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The roster, or `null` when the caller may not have it.
|
||||
*
|
||||
* One `null` for three different situations — no such account, an account that
|
||||
* is not a managed profile, and a profile the caller is not an active Guardian
|
||||
* of — so the route answers the same 404 to all three. An adult record whose
|
||||
* owner happened to grant somebody MANAGE is not a managed profile and must be
|
||||
* indistinguishable from one that does not exist, exactly as it is in
|
||||
* `inviteManagedProfileGuardian`.
|
||||
*
|
||||
* No lock and no transaction. `withManagedProfileLock` exists to serialize
|
||||
* lifecycle TRANSITIONS so a reducer decides from a committed count rather than
|
||||
* a stale one; taking it for a panel refresh would put an advisory lock on a
|
||||
* read that guards no invariant. The roster is a snapshot and is allowed to be
|
||||
* one — which is why the last-Guardian refusal stays enforced at the route that
|
||||
* changes something, and the card's pre-emptive floor is a courtesy on top of
|
||||
* it rather than a replacement for it.
|
||||
*/
|
||||
export async function listManagedProfileGuardians(input: {
|
||||
profileId: string;
|
||||
callerId: string;
|
||||
now?: Date;
|
||||
}): Promise<ManagedProfileGuardianView[] | null> {
|
||||
const now = input.now ?? new Date();
|
||||
|
||||
const profile = await prisma.user.findUnique({
|
||||
where: { id: input.profileId },
|
||||
select: { id: true, managedProfileAt: true },
|
||||
});
|
||||
if (!profile?.managedProfileAt) return null;
|
||||
|
||||
const caller = await prisma.accountGrant.findFirst({
|
||||
where: {
|
||||
grantorId: profile.id,
|
||||
granteeId: input.callerId,
|
||||
...activeGuardianWhere(now),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!caller) return null;
|
||||
|
||||
const grants = await prisma.accountGrant.findMany({
|
||||
where: {
|
||||
grantorId: profile.id,
|
||||
access: "MANAGE",
|
||||
revokedAt: null,
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
acceptedAt: true,
|
||||
revokedAt: true,
|
||||
expiresAt: true,
|
||||
invitedAt: true,
|
||||
grantee: { select: GRANT_PARTY_SELECT },
|
||||
},
|
||||
orderBy: { invitedAt: "asc" },
|
||||
});
|
||||
|
||||
const roster: ManagedProfileGuardianView[] = [];
|
||||
for (const grant of grants) {
|
||||
const state = grantState(grant, now);
|
||||
// The `where` above already excludes both, so this is the belt on the
|
||||
// derivation rather than the filter itself: `grantState` is the authority
|
||||
// on what a row IS, and a row it calls ended must not reach a roster the
|
||||
// last-Guardian floor is counted from.
|
||||
if (state !== "PENDING" && state !== "ACTIVE") continue;
|
||||
roster.push({
|
||||
grantId: grant.id,
|
||||
account: grant.grantee,
|
||||
state,
|
||||
invitedAt: grant.invitedAt.toISOString(),
|
||||
acceptedAt: grant.acceptedAt?.toISOString() ?? null,
|
||||
});
|
||||
}
|
||||
return roster;
|
||||
}
|
||||
@@ -107,6 +107,39 @@ const endedGrantView = grantView
|
||||
"A grant that has just been ended, plus what the cleanup did. Nothing is deleted: the row survives as the consent record and DELETE names the act, not the storage.",
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.37.0 — one Guardian of a managed profile, as the roster publishes them.
|
||||
*
|
||||
* Deliberately narrower than {@link grantView}, and the narrowing is the
|
||||
* privacy decision rather than an omission. `access` and `scope` are constants
|
||||
* for a Guardian grant (MANAGE, whole record) and publishing a constant invites
|
||||
* a client to branch on it; `lastUsedAt`, `revokedAt` and `revokedBy` describe
|
||||
* a history this list is not about; and the party block is the same
|
||||
* `{ id, username, displayName }` one sharing party already sees of another,
|
||||
* with no e-mail.
|
||||
*/
|
||||
const managedProfileGuardian = z
|
||||
.object({
|
||||
grantId: z
|
||||
.string()
|
||||
.describe(
|
||||
"The grant row. This is the value `DELETE /api/managed-profiles/{id}/guardians/{grantId}` takes.",
|
||||
),
|
||||
account: grantParty,
|
||||
state: z
|
||||
.enum(["PENDING", "ACTIVE"])
|
||||
.describe(
|
||||
"PENDING means the invitation has been sent and not yet accepted. A PENDING Guardian does NOT count toward the last-Guardian floor: the server counts accepted, unexpired MANAGE grants, so inviting somebody and then trying to leave is still refused until they accept. Say so before the act rather than letting it arrive as a 409.",
|
||||
),
|
||||
invitedAt: z.string(),
|
||||
acceptedAt: z.string().nullable(),
|
||||
})
|
||||
.meta({
|
||||
id: "ManagedProfileGuardian",
|
||||
description:
|
||||
"One person who looks after a managed profile. Ended grants — revoked or expired — are absent rather than listed with a state: the question is who looks after this record now.",
|
||||
});
|
||||
|
||||
const grantListResponse = z
|
||||
.object({
|
||||
given: z.array(grantView),
|
||||
@@ -553,6 +586,36 @@ export const accountSharingPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/managed-profiles/{id}/guardians": {
|
||||
get: {
|
||||
tags: ["Account sharing"],
|
||||
summary: "Who looks after a managed profile",
|
||||
description:
|
||||
"The live Guardians of one managed profile — every unexpired, unrevoked MANAGE grant on it, PENDING and ACTIVE alike. Cookie transport only, by the same structural argument as the rest of this family: it resolves through the session and never falls through to the Bearer branch. A fresh second factor is NOT required, unlike every act on the same profile: this is a read, and it discloses nothing about a party the caller cannot already read on their own sharing panel. An ACTOR surface — the profile is named in the path and the caller acts as themselves, so it answers from the Guardian's own account rather than only while switched into the record. Anyone who is not an active Guardian of THIS profile gets the same 404 as an unknown id, including a READ, WRITE or MANAGE delegate of an ordinary record: the refusal is not an enumeration oracle. Count the ACTIVE rows to know whether removing a Guardian is possible — a PENDING invitation does not satisfy the last-Guardian floor.",
|
||||
requestParams: {
|
||||
path: z.object({ id: z.string() }),
|
||||
},
|
||||
responses: {
|
||||
...stdResponses,
|
||||
"200": {
|
||||
description: "The profile's live Guardians, oldest invitation first.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
z.array(managedProfileGuardian),
|
||||
"ManagedProfileGuardianListEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description:
|
||||
"No such managed profile, or the caller is not one of its Guardians (`meta.errorCode: managed_profile.not_found`). The two are byte-identical.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/account/switch": {
|
||||
post: {
|
||||
tags: ["Account sharing"],
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
/**
|
||||
* Every mutation and read the managed-profile surface can issue, through the
|
||||
* real routes and a real Postgres.
|
||||
*
|
||||
* The browser card is proved from a static render in
|
||||
* `src/components/settings/access/__tests__/managed-profile-affordances.test.tsx`,
|
||||
* which can say that a control exists and nothing about what happens when it is
|
||||
* pressed. This file is the other half: the same calls the card makes, against
|
||||
* the handlers themselves, including every refusal the card renders a sentence
|
||||
* for.
|
||||
*
|
||||
* The roster read is where most of the weight sits, because it is the one
|
||||
* capability this release adds to the server. Its field set is asserted with
|
||||
* `Object.keys` rather than by presence: an over-disclosing route passes every
|
||||
* "contains" assertion ever written about it, and the decision that the roster
|
||||
* publishes no e-mail address is a privacy decision rather than plumbing.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { cookieJar, headerJar, queuedSessionIds } from "./mock-next-headers";
|
||||
import { getPrismaClient, truncateAllTables } from "./setup";
|
||||
import { createManagedProfile } from "@/lib/managed-profiles/create";
|
||||
import { acceptGrant, inviteGrant } from "@/lib/sharing/grants";
|
||||
|
||||
process.env.API_TOKEN_HMAC_KEY ??=
|
||||
"test-hmac-key-managed-profile-surface-32-bytes-min-1234509876";
|
||||
|
||||
const { hashToken } = await import("@/lib/auth/hmac");
|
||||
|
||||
vi.mock("next/headers", async () => {
|
||||
const { cookieJar, headerJar, queuedSessionIds } =
|
||||
await import("./mock-next-headers");
|
||||
return {
|
||||
headers: vi.fn(async () => ({
|
||||
get: (name: string) => headerJar.get(name.toLowerCase()) ?? null,
|
||||
})),
|
||||
cookies: vi.fn(async () => {
|
||||
const snapshot = new Map(cookieJar);
|
||||
const queuedSessionId = queuedSessionIds.shift();
|
||||
if (queuedSessionId) {
|
||||
snapshot.set("healthlog_session", queuedSessionId);
|
||||
}
|
||||
return {
|
||||
get: (name: string) => {
|
||||
const value = snapshot.get(name);
|
||||
return value ? { name, value } : undefined;
|
||||
},
|
||||
set: (name: string, value: string) => {
|
||||
cookieJar.set(name, value);
|
||||
},
|
||||
delete: (name: string) => {
|
||||
cookieJar.delete(name);
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
let sequence = 0;
|
||||
|
||||
interface Person {
|
||||
id: string;
|
||||
username: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
/** An account with a second factor and a session that has just proved it. */
|
||||
async function person(label: string): Promise<Person> {
|
||||
const suffix = sequence++;
|
||||
const prisma = getPrismaClient();
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
username: `${label}-${suffix}`,
|
||||
email: `${label}-${suffix}@example.test`,
|
||||
totpConfirmedAt: new Date(),
|
||||
},
|
||||
});
|
||||
const session = await prisma.session.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
|
||||
mfaVerifiedAt: new Date(),
|
||||
},
|
||||
});
|
||||
return { id: user.id, username: user.username, sessionId: session.id };
|
||||
}
|
||||
|
||||
function signIn(who: Person): void {
|
||||
headerJar.delete("authorization");
|
||||
cookieJar.set("healthlog_session", who.sessionId);
|
||||
}
|
||||
|
||||
/** A wildcard Bearer token for `who`, with no cookie session armed. */
|
||||
async function signInWithBearer(who: Person): Promise<void> {
|
||||
const raw = `hlk_surface_${"0".repeat(48)}`;
|
||||
await getPrismaClient().apiToken.create({
|
||||
data: {
|
||||
userId: who.id,
|
||||
name: "surface",
|
||||
tokenHash: hashToken(raw),
|
||||
permissions: ["*"],
|
||||
},
|
||||
});
|
||||
cookieJar.clear();
|
||||
headerJar.set("authorization", `Bearer ${raw}`);
|
||||
}
|
||||
|
||||
async function listGuardians(profileId: string) {
|
||||
const { GET } =
|
||||
await import("@/app/api/managed-profiles/[id]/guardians/route");
|
||||
return GET(
|
||||
new NextRequest(
|
||||
`http://localhost/api/managed-profiles/${profileId}/guardians`,
|
||||
{ method: "GET" },
|
||||
),
|
||||
{ params: Promise.resolve({ id: profileId }) },
|
||||
);
|
||||
}
|
||||
|
||||
/** A profile with its creator as sole Guardian, plus a pending second one. */
|
||||
async function profileWithPendingSecondGuardian() {
|
||||
const creator = await person("creator");
|
||||
const invitee = await person("invitee");
|
||||
const { profile } = await createManagedProfile({
|
||||
creatorId: creator.id,
|
||||
displayName: "Managed record",
|
||||
dateOfBirth: null,
|
||||
locale: "en",
|
||||
timezone: "UTC",
|
||||
});
|
||||
const invitation = await inviteGrant({
|
||||
grantorId: profile.id,
|
||||
granteeId: invitee.id,
|
||||
access: "MANAGE",
|
||||
scope: null,
|
||||
});
|
||||
return { creator, invitee, profile, invitation };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await truncateAllTables(getPrismaClient());
|
||||
cookieJar.clear();
|
||||
headerJar.clear();
|
||||
queuedSessionIds.length = 0;
|
||||
});
|
||||
|
||||
describe("who looks after a managed profile (real Postgres)", () => {
|
||||
it("shows an active Guardian every live grant, pending and accepted", async () => {
|
||||
const { creator, invitee, profile } =
|
||||
await profileWithPendingSecondGuardian();
|
||||
signIn(creator);
|
||||
|
||||
const response = await listGuardians(profile.id);
|
||||
expect(response.status).toBe(200);
|
||||
const roster = (await response.json()).data as Array<
|
||||
Record<string, unknown>
|
||||
>;
|
||||
|
||||
expect(roster).toHaveLength(2);
|
||||
const byName = new Map(
|
||||
roster.map((row) => [
|
||||
(row.account as { username: string }).username,
|
||||
row,
|
||||
]),
|
||||
);
|
||||
expect(byName.get(creator.username)?.state).toBe("ACTIVE");
|
||||
expect(byName.get(creator.username)?.acceptedAt).toEqual(
|
||||
expect.any(String),
|
||||
);
|
||||
expect(byName.get(invitee.username)?.state).toBe("PENDING");
|
||||
expect(byName.get(invitee.username)?.acceptedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("discloses exactly five fields, and the party block carries no e-mail", async () => {
|
||||
// `Object.keys`, not `toContain`. A route that also published the
|
||||
// invitee's e-mail address, their notification channels or their last
|
||||
// access would satisfy every presence assertion in this file.
|
||||
const { profile, creator } = await profileWithPendingSecondGuardian();
|
||||
signIn(creator);
|
||||
|
||||
const roster = (await (await listGuardians(profile.id)).json())
|
||||
.data as Array<Record<string, unknown>>;
|
||||
expect(roster.length).toBeGreaterThan(0);
|
||||
for (const row of roster) {
|
||||
expect(Object.keys(row).sort()).toEqual([
|
||||
"acceptedAt",
|
||||
"account",
|
||||
"grantId",
|
||||
"invitedAt",
|
||||
"state",
|
||||
]);
|
||||
expect(Object.keys(row.account as object).sort()).toEqual([
|
||||
"displayName",
|
||||
"id",
|
||||
"username",
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("answers a second Guardian with the same roster", async () => {
|
||||
const { creator, invitee, profile, invitation } =
|
||||
await profileWithPendingSecondGuardian();
|
||||
await acceptGrant({ grantId: invitation.id, granteeId: invitee.id });
|
||||
|
||||
signIn(creator);
|
||||
const first = (await (await listGuardians(profile.id)).json()).data;
|
||||
signIn(invitee);
|
||||
const second = (await (await listGuardians(profile.id)).json()).data;
|
||||
|
||||
expect(second).toEqual(first);
|
||||
expect(
|
||||
(second as Array<{ state: string }>).every((r) => r.state === "ACTIVE"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses somebody who is not a Guardian of that profile", async () => {
|
||||
const { profile } = await profileWithPendingSecondGuardian();
|
||||
const stranger = await person("stranger");
|
||||
signIn(stranger);
|
||||
|
||||
const response = await listGuardians(profile.id);
|
||||
expect(response.status).toBe(404);
|
||||
expect((await response.json()).meta?.errorCode).toBe(
|
||||
"managed_profile.not_found",
|
||||
);
|
||||
});
|
||||
|
||||
it("answers an unknown id with the same bytes as a refused one", async () => {
|
||||
// The refusal must not be an enumeration oracle: "no such profile" and
|
||||
// "not yours" have to be indistinguishable from the outside.
|
||||
const { profile } = await profileWithPendingSecondGuardian();
|
||||
const stranger = await person("stranger");
|
||||
signIn(stranger);
|
||||
|
||||
const refused = await (await listGuardians(profile.id)).json();
|
||||
const unknown = await (await listGuardians("does-not-exist")).json();
|
||||
expect(unknown).toEqual(refused);
|
||||
});
|
||||
|
||||
it.each(["READ", "WRITE", "MANAGE"] as const)(
|
||||
"refuses a %s delegate of an ordinary record against that record",
|
||||
async (access) => {
|
||||
// Holding a grant is not holding this read. An adult record whose owner
|
||||
// granted MANAGE is not a managed profile, and must 404 exactly as an
|
||||
// unknown id does.
|
||||
const owner = await person("owner");
|
||||
const delegate = await person("delegate");
|
||||
const invitation = await inviteGrant({
|
||||
grantorId: owner.id,
|
||||
granteeId: delegate.id,
|
||||
access,
|
||||
scope: null,
|
||||
});
|
||||
await acceptGrant({ grantId: invitation.id, granteeId: delegate.id });
|
||||
signIn(delegate);
|
||||
|
||||
const response = await listGuardians(owner.id);
|
||||
expect(response.status).toBe(404);
|
||||
expect((await response.json()).meta?.errorCode).toBe(
|
||||
"managed_profile.not_found",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("drops a revoked Guardian from the roster and refuses them the read", async () => {
|
||||
const { creator, invitee, profile, invitation } =
|
||||
await profileWithPendingSecondGuardian();
|
||||
await acceptGrant({ grantId: invitation.id, granteeId: invitee.id });
|
||||
await getPrismaClient().accountGrant.update({
|
||||
where: { id: invitation.id },
|
||||
data: { revokedAt: new Date(), revokedBy: "GRANTOR" },
|
||||
});
|
||||
|
||||
signIn(invitee);
|
||||
expect((await listGuardians(profile.id)).status).toBe(404);
|
||||
|
||||
signIn(creator);
|
||||
const roster = (await (await listGuardians(profile.id)).json())
|
||||
.data as Array<{ account: { username: string } }>;
|
||||
expect(roster).toHaveLength(1);
|
||||
expect(roster[0].account.username).toBe(creator.username);
|
||||
});
|
||||
|
||||
it("drops an expired Guardian grant from the roster", async () => {
|
||||
const { creator, profile, invitation } =
|
||||
await profileWithPendingSecondGuardian();
|
||||
await getPrismaClient().accountGrant.update({
|
||||
where: { id: invitation.id },
|
||||
data: { expiresAt: new Date(Date.now() - 60_000) },
|
||||
});
|
||||
|
||||
signIn(creator);
|
||||
const roster = (await (await listGuardians(profile.id)).json())
|
||||
.data as Array<{ account: { username: string } }>;
|
||||
expect(roster).toHaveLength(1);
|
||||
expect(roster[0].account.username).toBe(creator.username);
|
||||
});
|
||||
|
||||
it("refuses a Bearer caller, because the family is cookie-only", async () => {
|
||||
const { creator, profile } = await profileWithPendingSecondGuardian();
|
||||
await signInWithBearer(creator);
|
||||
|
||||
// The same account, the same wildcard reach it has everywhere else, and
|
||||
// still no answer here: `requireCookieAuth` never falls through to the
|
||||
// Bearer branch.
|
||||
expect((await listGuardians(profile.id)).status).toBe(401);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user