mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
Merge branch 'fix/v1437-data' into release/v1.43.7
This commit is contained in:
commit
dee6a27ae4
100 files changed
+2314
-506
No files matched your search
@@ -320,3 +320,51 @@ describe("auditLog", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("auditLog — refused attempts", () => {
|
||||
it("keeps a refusal on the caller's own record out of audit_logs and on the wide event", async () => {
|
||||
const { WideEventBuilder } = await import("@/lib/logging/event-builder");
|
||||
const { eventStorage } = await import("@/lib/logging/context");
|
||||
const evt = new WideEventBuilder("http");
|
||||
evt.setAuth({ user_id: "owner-1", auth_method: "session" });
|
||||
|
||||
await eventStorage.run(evt, () =>
|
||||
auditLog("measurements.list.validation-failed", {
|
||||
userId: "owner-1",
|
||||
details: { issues: [] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(prisma.auditLog.create).not.toHaveBeenCalled();
|
||||
expect(
|
||||
(evt.toJSON() as { meta?: Record<string, unknown> }).meta
|
||||
?.rejected_attempt,
|
||||
).toBe("measurements.list.validation-failed");
|
||||
});
|
||||
|
||||
it("writes a delegate's refusal under the record it targeted, for the owner's feed", async () => {
|
||||
const { WideEventBuilder } = await import("@/lib/logging/event-builder");
|
||||
const { eventStorage } = await import("@/lib/logging/context");
|
||||
const evt = new WideEventBuilder("http");
|
||||
evt.setAuth({ user_id: "delegate-1", auth_method: "session" });
|
||||
evt.setActingAs("owner-1");
|
||||
|
||||
await eventStorage.run(evt, () =>
|
||||
auditLog("measurements.create.validation-failed", { userId: "owner-1" }),
|
||||
);
|
||||
|
||||
expect(prisma.auditLog.create).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
vi.mocked(prisma.auditLog.create).mock.calls[0][0].data,
|
||||
).toMatchObject({
|
||||
action: "measurements.create.validation-failed",
|
||||
userId: "owner-1",
|
||||
actorUserId: "delegate-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("still writes every other action on the caller's own record", async () => {
|
||||
await auditLog("measurement.create", { userId: "owner-1" });
|
||||
expect(prisma.auditLog.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -86,7 +86,10 @@ import {
|
||||
createSession,
|
||||
destroyAllSessions,
|
||||
destroySession,
|
||||
validateSessionFromCookieValue,
|
||||
validateSessionWithCreatedAt,
|
||||
} from "../session";
|
||||
import { SessionStoreUnavailableError } from "@/lib/api-errors";
|
||||
|
||||
const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
@@ -254,6 +257,59 @@ describe("getSession", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a session lookup that fails is not a missing session", () => {
|
||||
// A dropped connection used to fold into `null`, which every caller reads
|
||||
// as "signed out": the route answered 401 and the client discarded a good
|
||||
// credential because the database blinked.
|
||||
function failLookup() {
|
||||
vi.mocked(prisma.session.findUnique).mockRejectedValueOnce(
|
||||
Object.assign(new Error("Can't reach database server"), {
|
||||
code: "P1001",
|
||||
}) as never,
|
||||
);
|
||||
}
|
||||
|
||||
it("getSession raises a 503 with a retryable code", async () => {
|
||||
cookieState.sessionId = "hls_abc";
|
||||
failLookup();
|
||||
const err = await getSession().catch((e: unknown) => e);
|
||||
expect(err).toBeInstanceOf(SessionStoreUnavailableError);
|
||||
expect(err).toMatchObject({
|
||||
statusCode: 503,
|
||||
errorCode: "auth.session.unavailable",
|
||||
});
|
||||
// Nothing about the browser's credential changes on a fault.
|
||||
expect(cookieState.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("validateSessionFromCookieValue raises instead of answering null", async () => {
|
||||
failLookup();
|
||||
await expect(
|
||||
validateSessionFromCookieValue("hls_abc"),
|
||||
).rejects.toBeInstanceOf(SessionStoreUnavailableError);
|
||||
});
|
||||
|
||||
it("validateSessionWithCreatedAt raises instead of answering null", async () => {
|
||||
failLookup();
|
||||
await expect(
|
||||
validateSessionWithCreatedAt("hls_abc"),
|
||||
).rejects.toBeInstanceOf(SessionStoreUnavailableError);
|
||||
});
|
||||
|
||||
it("still answers null for a cookie that matches nothing", async () => {
|
||||
await expect(validateSessionFromCookieValue("hls_nope")).resolves.toBe(
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
it("logout still clears the cookie when the lookup fails", async () => {
|
||||
cookieState.sessionId = "hls_abc";
|
||||
failLookup();
|
||||
await expect(destroySession()).resolves.toBeUndefined();
|
||||
expect(cookieState.delete).toHaveBeenCalledWith("healthlog_session");
|
||||
});
|
||||
});
|
||||
|
||||
describe("destroySession", () => {
|
||||
it("deletes the row the secret resolves to, not the cookie value", async () => {
|
||||
// The cookie is no longer the primary key, so a logout that deletes by
|
||||
|
||||
+28
-5
@@ -1,7 +1,7 @@
|
||||
import { settleWithin } from "@/lib/async/settle-within";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { lookupIpGeo } from "@/lib/geo";
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
|
||||
/**
|
||||
* v1.36.0 — the action a delegated request records against the record it read.
|
||||
@@ -46,6 +46,26 @@ function actingActorFor(filedUnder: string | null): string | null {
|
||||
return filedUnder === owner ? actor : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A request that was refused before it did anything: `<surface>.validation-failed`.
|
||||
*
|
||||
* Every route that parses a body or a query files one of these when the parse
|
||||
* fails, through `auditLog`, and until v1.43.7 every one of them became an
|
||||
* `audit_logs` row, on the owner's own requests too. A person's app sending a
|
||||
* malformed query is not a security event, and nothing reads those rows: the
|
||||
* activity feed shows refusals only where somebody else acted, and the wide
|
||||
* event already carries the refusal. They were telemetry in the audit table,
|
||||
* a few per sync on a busy client, growing the one table a self-hoster keeps.
|
||||
*
|
||||
* So a refused attempt is written only where it means something to someone
|
||||
* other than the caller: a delegated request, filed under the record it
|
||||
* targeted, which is what the owner's activity feed reads. Everywhere else it
|
||||
* stays on the wide event (`meta.rejected_attempt`).
|
||||
*/
|
||||
export function isRejectedAttemptAction(action: string): boolean {
|
||||
return action.endsWith(".validation-failed");
|
||||
}
|
||||
|
||||
export async function auditLog(
|
||||
action: string,
|
||||
opts: {
|
||||
@@ -60,14 +80,17 @@ export async function auditLog(
|
||||
) {
|
||||
const userId = opts.userId ?? null;
|
||||
const client = opts.client ?? prisma;
|
||||
const actorUserId =
|
||||
opts.actorUserId === undefined ? actingActorFor(userId) : opts.actorUserId;
|
||||
if (isRejectedAttemptAction(action) && actorUserId === null) {
|
||||
annotate({ meta: { rejected_attempt: action } });
|
||||
return;
|
||||
}
|
||||
const entry = await client.auditLog.create({
|
||||
data: {
|
||||
action,
|
||||
userId,
|
||||
actorUserId:
|
||||
opts.actorUserId === undefined
|
||||
? actingActorFor(userId)
|
||||
: opts.actorUserId,
|
||||
actorUserId,
|
||||
details: opts.details ? JSON.stringify(opts.details) : null,
|
||||
ipAddress: opts.ipAddress ?? null,
|
||||
},
|
||||
|
||||
+31
-13
@@ -7,6 +7,7 @@ import { ensureDbCompatibility } from "@/lib/db-compat";
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie";
|
||||
import { isP2025 } from "@/lib/prisma-errors";
|
||||
import { SessionStoreUnavailableError } from "@/lib/api-errors";
|
||||
import { locales, type Locale } from "@/lib/i18n/config";
|
||||
import { LOCALE_COOKIE, setLocaleCookie } from "@/lib/i18n/locale-cookie";
|
||||
|
||||
@@ -73,19 +74,28 @@ function mintSessionSecret(): string {
|
||||
* login from the deploy onward is on a secret immediately.
|
||||
*/
|
||||
async function findSessionByCookie(cookieValue: string) {
|
||||
if (cookieValue.startsWith(SESSION_TOKEN_PREFIX)) {
|
||||
return prisma.session.findUnique({
|
||||
where: { tokenHash: hashToken(cookieValue) },
|
||||
try {
|
||||
if (cookieValue.startsWith(SESSION_TOKEN_PREFIX)) {
|
||||
return await prisma.session.findUnique({
|
||||
where: { tokenHash: hashToken(cookieValue) },
|
||||
include: { user: true },
|
||||
});
|
||||
}
|
||||
|
||||
const legacy = await prisma.session.findUnique({
|
||||
where: { id: cookieValue },
|
||||
include: { user: true },
|
||||
});
|
||||
// A row that already holds a secret has retired its id as a credential.
|
||||
return legacy && legacy.tokenHash === null ? legacy : null;
|
||||
} catch (error) {
|
||||
// "No such session" and "could not look" are different answers and only
|
||||
// the first one is null. A failed query used to be folded into null by
|
||||
// the callers, so a database restart answered 401 and every client
|
||||
// signed its person out. It is a 503 now, with a code a client can retry
|
||||
// on (`auth.session.unavailable`).
|
||||
throw new SessionStoreUnavailableError(error);
|
||||
}
|
||||
|
||||
const legacy = await prisma.session.findUnique({
|
||||
where: { id: cookieValue },
|
||||
include: { user: true },
|
||||
});
|
||||
// A row that already holds a secret has retired its id as a credential.
|
||||
return legacy && legacy.tokenHash === null ? legacy : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,7 +116,7 @@ export async function validateSessionFromCookieValue(
|
||||
cookieValue: string | undefined | null,
|
||||
): Promise<{ session: { id: string; expiresAt: Date }; user: User } | null> {
|
||||
if (!cookieValue) return null;
|
||||
const session = await findSessionByCookie(cookieValue).catch(() => null);
|
||||
const session = await findSessionByCookie(cookieValue);
|
||||
if (!session || session.expiresAt < new Date()) return null;
|
||||
return {
|
||||
session: { id: session.id, expiresAt: session.expiresAt },
|
||||
@@ -138,7 +148,7 @@ export async function validateSessionWithCreatedAt(
|
||||
user: User;
|
||||
} | null> {
|
||||
if (!cookieValue) return null;
|
||||
const session = await findSessionByCookie(cookieValue).catch(() => null);
|
||||
const session = await findSessionByCookie(cookieValue);
|
||||
if (!session || session.expiresAt < new Date()) return null;
|
||||
return {
|
||||
session: {
|
||||
@@ -462,7 +472,15 @@ export async function destroySession(): Promise<void> {
|
||||
// event rather than swallowing it silently, but never block the cookie
|
||||
// clear below: a transient DB fault must not leave the client logged in
|
||||
// with the cookie intact.
|
||||
const session = await findSessionByCookie(cookieValue).catch(() => null);
|
||||
// A lookup that fails cannot find the row to delete, but must not keep
|
||||
// the cookie in the browser either; the warning is what tells the
|
||||
// operator a server-side session outlived its logout.
|
||||
const session = await findSessionByCookie(cookieValue).catch((err) => {
|
||||
getEvent()?.addWarning(
|
||||
`destroySession lookup failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return null;
|
||||
});
|
||||
if (session) {
|
||||
await prisma.session
|
||||
.delete({ where: { id: session.id } })
|
||||
|
||||
Reference in new issue
Block a user