Add Settings -> Database viewer (Adminer) for local devs and any admin
Local dev gets an unauthenticated Adminer instance bound to loopback only. In production, any account with is_admin=true can open it - the app mints a short-lived token from a live admin session, which Nginx's new db.ciagent.org block exchanges for a session cookie that re-checks admin status on every request, instead of a shared static password that wouldn't scale to multiple admins or revoke live. Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
@@ -5,6 +5,7 @@ import { useState } from "react";
|
||||
import {
|
||||
Bell,
|
||||
CheckCircle2,
|
||||
Database,
|
||||
KeyRound,
|
||||
Loader2,
|
||||
Mail,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
import { authErrorMessage } from "@/hooks/use-auth";
|
||||
import {
|
||||
useAcceptUnbanRequest,
|
||||
useCreateDbViewerSession,
|
||||
useCreateIpBan,
|
||||
useCurrentUser,
|
||||
useDeleteIpBan,
|
||||
@@ -48,6 +50,7 @@ import { FormField } from "@/components/ui/form-field";
|
||||
import { Select } from "@/components/ui/select";
|
||||
import { SystemSecretRow } from "@/components/ui/system-secret-row";
|
||||
import { UserApiKeyRow } from "@/components/ui/user-api-key-row";
|
||||
import { isLocalConvenience } from "@/lib/auth";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import {
|
||||
SEVERITY_LABELS,
|
||||
@@ -663,6 +666,60 @@ function IpBansBox() {
|
||||
);
|
||||
}
|
||||
|
||||
function DatabaseViewerBox() {
|
||||
const { data: systemStatus } = useSystemStatus();
|
||||
const createSession = useCreateDbViewerSession();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const isLocal = systemStatus ? isLocalConvenience(systemStatus) : false;
|
||||
const dbViewerUrl = process.env.NEXT_PUBLIC_DB_VIEWER_URL;
|
||||
|
||||
const handleOpen = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const { token } = await createSession.mutateAsync();
|
||||
window.open(`${dbViewerUrl}/_auth?token=${encodeURIComponent(token)}`, "_blank", "noopener,noreferrer");
|
||||
} catch {
|
||||
setError("Couldn't open the database viewer. Try again.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-slate-200 bg-white p-6">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
|
||||
<Database className="h-4 w-4" aria-hidden /> Database
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-slate-500">
|
||||
Open a web-based Postgres client (Adminer) in a new tab to view and edit rows directly.
|
||||
Local developers and server admins only.
|
||||
</p>
|
||||
|
||||
<div className="mt-4">
|
||||
{isLocal ? (
|
||||
<a
|
||||
href="http://localhost:8081"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="focus-ring inline-flex items-center gap-1.5 rounded-md bg-slate-800 px-3 py-1.5 text-xs font-semibold text-white transition-colors duration-200 hover:bg-slate-900"
|
||||
>
|
||||
<Database className="h-3.5 w-3.5" aria-hidden /> Open database viewer
|
||||
</a>
|
||||
) : dbViewerUrl ? (
|
||||
<ActionButton
|
||||
onClick={handleOpen}
|
||||
pending={createSession.isPending}
|
||||
colorClass="bg-slate-800 hover:bg-slate-900"
|
||||
icon={Database}
|
||||
label="Open database viewer"
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-slate-500">Not configured for this deployment.</p>
|
||||
)}
|
||||
{error && <p className="mt-2 text-xs text-red-600">{error}</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { data: user } = useCurrentUser();
|
||||
const { data: systemStatus } = useSystemStatus();
|
||||
@@ -759,6 +816,7 @@ export default function SettingsPage() {
|
||||
<>
|
||||
<ServerSecretsBox />
|
||||
<IpBansBox />
|
||||
<DatabaseViewerBox />
|
||||
<LoggingBox />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -47,6 +47,12 @@ export function useSetSystemSecret() {
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateDbViewerSession() {
|
||||
return useMutation({
|
||||
mutationFn: () => api.createDbViewerSession(),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSystemLogs() {
|
||||
return useQuery({
|
||||
queryKey: ["system-logs"],
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
CompanyUpdatePayload,
|
||||
ConfirmPasswordResetPayload,
|
||||
DashboardAnalytics,
|
||||
DbViewerSessionResponse,
|
||||
DiscoverCompanyRequest,
|
||||
DiscoveredCompanyProfile,
|
||||
IpBan,
|
||||
@@ -166,6 +167,9 @@ export const api = {
|
||||
|
||||
listSystemSecrets: () => request<SystemSecretStatus[]>("/api/v1/system/secrets"),
|
||||
|
||||
createDbViewerSession: () =>
|
||||
request<DbViewerSessionResponse>("/api/v1/db-viewer/session", { method: "POST" }),
|
||||
|
||||
setSystemSecret: (key: string, payload: SetSystemSecretPayload) =>
|
||||
request<SystemSecretStatus>(`/api/v1/system/secrets/${key}`, {
|
||||
method: "PUT",
|
||||
|
||||
@@ -29,6 +29,10 @@ export interface SystemSecretStatus {
|
||||
value: string | null;
|
||||
}
|
||||
|
||||
export interface DbViewerSessionResponse {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface SetSystemSecretPayload {
|
||||
value: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import SettingsPage from "@/app/(app)/settings/page";
|
||||
import { renderWithQueryClient } from "./test-utils";
|
||||
|
||||
const ADMIN_USER = {
|
||||
id: "user-1",
|
||||
email: "[email protected]",
|
||||
display_name: "Admin",
|
||||
timezone: "America/New_York",
|
||||
is_active: true,
|
||||
is_admin: true,
|
||||
auth_mode: "jwt",
|
||||
};
|
||||
|
||||
function systemStatusBody(isLocalhost: boolean, authMode: "local" | "jwt") {
|
||||
return {
|
||||
app_env: "development",
|
||||
auth_mode: authMode,
|
||||
llm_provider: "mock",
|
||||
search_provider: "mock",
|
||||
sms_enabled: false,
|
||||
sms_provider: "twilio",
|
||||
ninjapear_configured: false,
|
||||
ninjapear_credit_balance: null,
|
||||
ninjapear_estimated_credits_per_company: null,
|
||||
is_localhost: isLocalhost,
|
||||
turnstile_site_key: null,
|
||||
components: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Covers every endpoint SettingsPage's admin-gated boxes touch on mount -
|
||||
* empty-list/no-op responses for everything except /system/status, which
|
||||
* each test configures to drive the local-vs-remote branch under test. */
|
||||
function mockFetchImplementation(isLocalhost: boolean, authMode: "local" | "jwt" = "jwt") {
|
||||
return vi.fn().mockImplementation((url: string, init?: RequestInit) => {
|
||||
const path = url.replace("http://localhost:8000", "");
|
||||
const ok = (json: unknown, status = 200) =>
|
||||
Promise.resolve({ ok: true, status, json: async () => json });
|
||||
|
||||
if (path === "/api/v1/auth/me") return ok(ADMIN_USER);
|
||||
if (path === "/api/v1/system/status") return ok(systemStatusBody(isLocalhost, authMode));
|
||||
if (path === "/api/v1/notification-destinations") return ok([]);
|
||||
if (path === "/api/v1/companies") return ok([]);
|
||||
if (path === "/api/v1/system/logs") return ok([]);
|
||||
if (path === "/api/v1/user-api-keys") return ok([]);
|
||||
if (path === "/api/v1/system/secrets") return ok([]);
|
||||
if (path === "/api/v1/auth/security-events") return ok([]);
|
||||
if (path === "/api/v1/admin/ip-bans") return ok([]);
|
||||
if (path === "/api/v1/admin/unban-requests") return ok([]);
|
||||
if (path === "/api/v1/db-viewer/session" && init?.method === "POST") {
|
||||
return ok({ token: "mock-bootstrap-token" });
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({ detail: "not found" }) });
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("NEXT_PUBLIC_DB_VIEWER_URL", "https://db.ciagent.org");
|
||||
});
|
||||
|
||||
describe("Settings - Database viewer box", () => {
|
||||
it("links straight to the local Adminer instance for the local-dev bypass account", async () => {
|
||||
vi.stubGlobal("fetch", mockFetchImplementation(true, "local"));
|
||||
renderWithQueryClient(<SettingsPage />);
|
||||
|
||||
const link = await screen.findByRole("link", { name: /open database viewer/i });
|
||||
expect(link).toHaveAttribute("href", "http://localhost:8081");
|
||||
expect(link).toHaveAttribute("target", "_blank");
|
||||
});
|
||||
|
||||
it("mints a session token and opens the configured remote viewer URL for a real admin", async () => {
|
||||
vi.stubGlobal("fetch", mockFetchImplementation(false, "jwt"));
|
||||
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
||||
const user = userEvent.setup();
|
||||
renderWithQueryClient(<SettingsPage />);
|
||||
|
||||
const button = await screen.findByRole("button", { name: /open database viewer/i });
|
||||
await user.click(button);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openSpy).toHaveBeenCalledWith(
|
||||
"https://db.ciagent.org/_auth?token=mock-bootstrap-token",
|
||||
"_blank",
|
||||
"noopener,noreferrer",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a not-configured message when NEXT_PUBLIC_DB_VIEWER_URL is unset for a remote admin", async () => {
|
||||
vi.stubEnv("NEXT_PUBLIC_DB_VIEWER_URL", "");
|
||||
vi.stubGlobal("fetch", mockFetchImplementation(false, "jwt"));
|
||||
renderWithQueryClient(<SettingsPage />);
|
||||
|
||||
expect(await screen.findByText(/not configured for this deployment/i)).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /open database viewer/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user