feat(admission): add scheduled group access
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
import { hashToken } from "@minecraft-account-manager/auth";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const databaseState = vi.hoisted(() => ({
|
||||
responses: [] as unknown[][],
|
||||
inserted: [] as Array<Record<string, unknown>>,
|
||||
isolationLevel: "",
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/database", () => {
|
||||
function selection(response: unknown[]) {
|
||||
const chain: Record<string, unknown> = {};
|
||||
for (const method of ["from", "where", "innerJoin", "leftJoin", "orderBy"]) {
|
||||
chain[method] = () => chain;
|
||||
}
|
||||
chain.limit = () => Promise.resolve(response);
|
||||
chain.then = (resolve: (value: unknown[]) => unknown, reject: (reason: unknown) => unknown) =>
|
||||
Promise.resolve(response).then(resolve, reject);
|
||||
return chain;
|
||||
}
|
||||
const tx = {
|
||||
select: () => selection(databaseState.responses.shift() ?? []),
|
||||
insert: () => ({
|
||||
values: (value: Record<string, unknown>) => {
|
||||
databaseState.inserted.push(value);
|
||||
return Promise.resolve();
|
||||
},
|
||||
}),
|
||||
delete: () => ({ where: () => Promise.resolve() }),
|
||||
update: () => ({ set: () => ({ where: () => Promise.resolve() }) }),
|
||||
};
|
||||
return {
|
||||
db: {
|
||||
select: () => selection(databaseState.responses.shift() ?? []),
|
||||
transaction: async (callback: (transaction: typeof tx) => Promise<unknown>, options: { isolationLevel?: string }) => {
|
||||
databaseState.isolationLevel = options?.isolationLevel ?? "";
|
||||
return callback(tx);
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/ip-intelligence", () => ({
|
||||
getIpIntelligence: async () => ({ classification: "clear" }),
|
||||
toAuditIpData: () => ({ classification: "clear" }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logger", () => ({ logger: { error: vi.fn() } }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
const messages = {
|
||||
registrationMessage: "Register {player} in {group}.",
|
||||
groupAccessDeniedMessage: "Disabled {player} in {group}.",
|
||||
vpnDeniedMessage: "Network denied for {player} in {group}.",
|
||||
scheduledAccessDeniedMessage: "Scheduled {player} in {group}: {next_start} / {next_end}.",
|
||||
};
|
||||
|
||||
function utcMinuteOfWeek(value: Date) {
|
||||
return ((value.getUTCDay() + 6) % 7) * 1440 + value.getUTCHours() * 60 + value.getUTCMinutes();
|
||||
}
|
||||
|
||||
function normalized(value: number) {
|
||||
return (value + 10080) % 10080;
|
||||
}
|
||||
|
||||
function request() {
|
||||
return new Request("http://localhost/api/velocity/access", {
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer route-secret", "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
requestId: "11111111-1111-4111-8111-111111111111",
|
||||
serverId: "velocity-main",
|
||||
minecraftUuid: "0123456789abcdef0123456789abcdef",
|
||||
username: "AlexMC",
|
||||
ipAddress: "203.0.113.10",
|
||||
occurredAt: new Date().toISOString(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function arrange(group: { accessEnabled: boolean; anonymizedNetworksAllowed: boolean }, windows: Array<{ startMinuteOfWeek: number; endMinuteOfWeek: number }>) {
|
||||
databaseState.responses = [
|
||||
[{ secretHash: hashToken("route-secret") }],
|
||||
[messages],
|
||||
[{ id: "account-id", userId: "user-id", minecraftUuid: "0123456789abcdef0123456789abcdef", username: "AlexMC" }],
|
||||
[{ id: "group-id", name: "Friday friends", ...group }],
|
||||
[{ id: "everyone-id", name: "everyone", accessEnabled: false, anonymizedNetworksAllowed: false }],
|
||||
windows,
|
||||
];
|
||||
}
|
||||
|
||||
describe("Velocity scheduled admission integration", () => {
|
||||
beforeEach(() => {
|
||||
databaseState.responses = [];
|
||||
databaseState.inserted = [];
|
||||
databaseState.isolationLevel = "";
|
||||
});
|
||||
|
||||
it("loads effective-group windows and returns a rendered schedule denial", async () => {
|
||||
const minute = utcMinuteOfWeek(new Date());
|
||||
arrange(
|
||||
{ accessEnabled: true, anonymizedNetworksAllowed: false },
|
||||
[{ startMinuteOfWeek: normalized(minute + 60), endMinuteOfWeek: normalized(minute + 120) }],
|
||||
);
|
||||
|
||||
const response = await POST(request());
|
||||
const body = await response.json();
|
||||
expect(body.allowed).toBe(false);
|
||||
expect(body.message).toMatch(/^Scheduled AlexMC in Friday friends: .* UTC \/ .* UTC\.$/);
|
||||
expect(databaseState.isolationLevel).toBe("repeatable read");
|
||||
expect(databaseState.inserted).toContainEqual(expect.objectContaining({
|
||||
type: "games.minecraft.account-manager.game.login.denied",
|
||||
data: expect.objectContaining({ reason: "schedule_disallowed", accessGroup: "Friday friends" }),
|
||||
}));
|
||||
});
|
||||
|
||||
it("fails closed for malformed persisted windows while disabled access retains precedence", async () => {
|
||||
const malformed = [
|
||||
{ startMinuteOfWeek: 100, endMinuteOfWeek: 200 },
|
||||
{ startMinuteOfWeek: 150, endMinuteOfWeek: 250 },
|
||||
];
|
||||
arrange({ accessEnabled: true, anonymizedNetworksAllowed: true }, malformed);
|
||||
expect(await (await POST(request())).json()).toMatchObject({ allowed: false, message: expect.stringContaining("unavailable") });
|
||||
expect(databaseState.inserted).toContainEqual(expect.objectContaining({
|
||||
data: expect.objectContaining({ reason: "schedule_disallowed" }),
|
||||
}));
|
||||
|
||||
databaseState.inserted = [];
|
||||
arrange({ accessEnabled: false, anonymizedNetworksAllowed: true }, malformed);
|
||||
expect(await (await POST(request())).json()).toEqual({ allowed: false, message: "Disabled AlexMC in Friday friends." });
|
||||
expect(databaseState.inserted).toContainEqual(expect.objectContaining({
|
||||
data: expect.objectContaining({ reason: "group_access_disabled" }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,10 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { gameAdmissionDenialReason, isRequestTimestampFresh, resolveEffectiveGroup, verifyHashedToken } from "@minecraft-account-manager/auth";
|
||||
import { isRequestTimestampFresh, resolveEffectiveGroup, verifyHashedToken } from "@minecraft-account-manager/auth";
|
||||
import { problemDetails, velocityAccessRequestSchema } from "@minecraft-account-manager/contracts";
|
||||
import {
|
||||
appSettings,
|
||||
events,
|
||||
groupAccessWindows,
|
||||
groups,
|
||||
ipObservations,
|
||||
minecraftAccounts,
|
||||
@@ -13,9 +14,10 @@ import {
|
||||
} from "@minecraft-account-manager/database";
|
||||
import { and, eq, isNull, lt, sql } from "drizzle-orm";
|
||||
import { NextResponse } from "next/server";
|
||||
import { admissionDenialMessage, DEFAULT_ADMISSION_MESSAGES } from "@/lib/admission-settings";
|
||||
import { admissionDenialMessage, DEFAULT_ADMISSION_MESSAGES, renderAdmissionMessage } from "@/lib/admission-settings";
|
||||
import { db } from "@/lib/database";
|
||||
import { isUniqueConstraintViolation } from "@/lib/database-errors";
|
||||
import { evaluateRegisteredPlayerAdmission } from "@/lib/game-admission-policy";
|
||||
import { getIpIntelligence, toAuditIpData } from "@/lib/ip-intelligence";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { problemInstance, problemResponse } from "@/lib/problem-response";
|
||||
@@ -115,10 +117,12 @@ async function handleVelocityAccess(request: Request) {
|
||||
registrationMessage: settings?.registrationMessage ?? DEFAULT_ADMISSION_MESSAGES.registrationMessage,
|
||||
groupAccessDeniedMessage: settings?.groupAccessDeniedMessage ?? DEFAULT_ADMISSION_MESSAGES.groupAccessDeniedMessage,
|
||||
vpnDeniedMessage: settings?.vpnDeniedMessage ?? DEFAULT_ADMISSION_MESSAGES.vpnDeniedMessage,
|
||||
scheduledAccessDeniedMessage: settings?.scheduledAccessDeniedMessage ?? DEFAULT_ADMISSION_MESSAGES.scheduledAccessDeniedMessage,
|
||||
};
|
||||
|
||||
const intelligence = await getIpIntelligence(input.ipAddress);
|
||||
const auditIpData = toAuditIpData(intelligence);
|
||||
const decisionAt = new Date();
|
||||
|
||||
const decision = await db.transaction(async (tx) => {
|
||||
await tx.delete(pluginRequests).where(lt(pluginRequests.expiresAt, new Date()));
|
||||
@@ -187,7 +191,13 @@ async function handleVelocityAccess(request: Request) {
|
||||
classification: intelligence.classification,
|
||||
observedAt: occurredAt,
|
||||
});
|
||||
return { allowed: false as const, message: admissionDenialMessage("not_registered", admissionMessages) };
|
||||
return {
|
||||
allowed: false as const,
|
||||
message: renderAdmissionMessage(admissionDenialMessage("not_registered", admissionMessages), {
|
||||
player: input.username,
|
||||
group: "everyone",
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const [explicitGroup] = await tx
|
||||
@@ -202,9 +212,22 @@ async function handleVelocityAccess(request: Request) {
|
||||
.where(eq(groups.isDefault, true))
|
||||
.limit(1);
|
||||
const effectiveGroup = resolveEffectiveGroup(explicitGroup ?? null, defaultGroup ?? null);
|
||||
|
||||
const denialReason = gameAdmissionDenialReason(effectiveGroup ?? null, intelligence.classification);
|
||||
if (denialReason) {
|
||||
const accessWindows = effectiveGroup
|
||||
? await tx.select({
|
||||
startMinuteOfWeek: groupAccessWindows.startMinuteOfWeek,
|
||||
endMinuteOfWeek: groupAccessWindows.endMinuteOfWeek,
|
||||
}).from(groupAccessWindows).where(eq(groupAccessWindows.groupId, effectiveGroup.id))
|
||||
: [];
|
||||
const policyDecision = evaluateRegisteredPlayerAdmission({
|
||||
group: effectiveGroup ?? null,
|
||||
windows: accessWindows,
|
||||
classification: intelligence.classification,
|
||||
now: decisionAt,
|
||||
player: input.username,
|
||||
messages: admissionMessages,
|
||||
});
|
||||
if (!policyDecision.allowed) {
|
||||
const denialReason = policyDecision.reason;
|
||||
await tx.insert(events).values({
|
||||
id: randomUUID(),
|
||||
source: `/velocity/${input.serverId}`,
|
||||
@@ -217,6 +240,10 @@ async function handleVelocityAccess(request: Request) {
|
||||
reason: denialReason,
|
||||
accessGroup: effectiveGroup?.name ?? null,
|
||||
accessGroupId: effectiveGroup?.id ?? null,
|
||||
nextScheduleWindow: policyDecision.nextWindow ? {
|
||||
start: policyDecision.nextWindow.start.toISOString(),
|
||||
end: policyDecision.nextWindow.end.toISOString(),
|
||||
} : null,
|
||||
ipIntelligence: auditIpData,
|
||||
},
|
||||
ipAddress: input.ipAddress,
|
||||
@@ -234,7 +261,7 @@ async function handleVelocityAccess(request: Request) {
|
||||
});
|
||||
return {
|
||||
allowed: false as const,
|
||||
message: admissionDenialMessage(denialReason, admissionMessages),
|
||||
message: policyDecision.message,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -297,7 +324,7 @@ async function handleVelocityAccess(request: Request) {
|
||||
});
|
||||
|
||||
return { allowed: true as const, message: "Account approved." };
|
||||
});
|
||||
}, { isolationLevel: "repeatable read" });
|
||||
|
||||
return NextResponse.json(decision);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user