mirror of
https://github.com/traberph/short.git
synced 2026-11-22 22:55:12 +00:00
Review fixes: forwarded IP, sign-in errors, revoking access
- take the visitor IP from the last X-Forwarded-For entry (the one the proxy adds); the first can be set by the client to fake unique visitors - show "Sign-in failed" with a retry link when the identity provider rejects the callback instead of a generic 500 page - report concurrent unique-constraint conflicts (e.g. two requests claiming the same shortcode) as 409 instead of 500 - admins can revoke a user's access (end sessions, delete API tokens) from Administration; previously a removed user kept working tokens - README: security notes on the proxy header, offboarding and rate limiting Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -67,6 +67,12 @@ docker compose up -d
|
|||||||
|
|
||||||
Put it behind a reverse proxy with TLS. Back up `data/`: it holds the SQLite database (`short.db`) and the uploaded avatars. Database migrations run automatically on startup.
|
Put it behind a reverse proxy with TLS. Back up `data/`: it holds the SQLite database (`short.db`) and the uploaded avatars. Database migrations run automatically on startup.
|
||||||
|
|
||||||
|
## Security notes
|
||||||
|
|
||||||
|
- **Reverse proxy:** with `TRUST_PROXY=true` the visitor IP is taken from the last `X-Forwarded-For` entry, so the proxy in front of short must append to that header (Traefik, Caddy and nginx' `$proxy_add_x_forwarded_for` do).
|
||||||
|
- **Removing someone:** admin rights and access follow Authentik at each sign-in, but existing sessions (up to 30 days) and API tokens keep working. When someone leaves or loses admin rights, use **Administration → user → Revoke access** to end their sessions and delete their tokens, and remove their access in Authentik.
|
||||||
|
- **Rate limiting** isn't built in. Every visit is recorded, so very public links can be flooded to inflate stats; rate-limit at the reverse proxy if needed. Individual clicks are deleted after 90 days.
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
The admin UI uses the same JSON API. Create a token under **API tokens**; it has the same permissions as your account.
|
The admin UI uses the same JSON API. Create a token under **API tokens**; it has the same permissions as your account.
|
||||||
|
|||||||
+7
-1
@@ -16,7 +16,7 @@ import {
|
|||||||
} from "../shared/validation.js";
|
} from "../shared/validation.js";
|
||||||
import type { AppEnv, Deps } from "./app.js";
|
import type { AppEnv, Deps } from "./app.js";
|
||||||
import { requireActor } from "./auth/middleware.js";
|
import { requireActor } from "./auth/middleware.js";
|
||||||
import { createApiToken } from "./auth/sessions.js";
|
import { createApiToken, revokeAccess } from "./auth/sessions.js";
|
||||||
import { apiTokens } from "./db/schema.js";
|
import { apiTokens } from "./db/schema.js";
|
||||||
import { forbidden, HttpError, notFound } from "./lib/errors.js";
|
import { forbidden, HttpError, notFound } from "./lib/errors.js";
|
||||||
import { removeMedia, saveAvatar } from "./lib/media.js";
|
import { removeMedia, saveAvatar } from "./lib/media.js";
|
||||||
@@ -186,6 +186,12 @@ export function apiRoutes(deps: Deps) {
|
|||||||
if (!c.var.actor.isAdmin) throw forbidden();
|
if (!c.var.actor.isAdmin) throw forbidden();
|
||||||
return c.json(pages.listUsernames(db));
|
return c.json(pages.listUsernames(db));
|
||||||
})
|
})
|
||||||
|
.delete("/users/:username/access", (c) => {
|
||||||
|
if (!c.var.actor.isAdmin) throw forbidden();
|
||||||
|
const revoked = revokeAccess(db, c.req.param("username"));
|
||||||
|
if (!revoked) throw notFound();
|
||||||
|
return c.json(revoked);
|
||||||
|
})
|
||||||
.get("/conflicts", (c) => {
|
.get("/conflicts", (c) => {
|
||||||
if (!c.var.actor.isAdmin) throw forbidden();
|
if (!c.var.actor.isAdmin) throw forbidden();
|
||||||
return c.json(pages.listConflicts(db));
|
return c.json(pages.listConflicts(db));
|
||||||
|
|||||||
@@ -48,6 +48,10 @@ export function createApp(deps: Deps) {
|
|||||||
|
|
||||||
app.onError((err, c) => {
|
app.onError((err, c) => {
|
||||||
const isApi = c.req.path.startsWith("/~/api/");
|
const isApi = c.req.path.startsWith("/~/api/");
|
||||||
|
// Two requests claiming the same unique value at once (e.g. a shortcode): the database rejects the second.
|
||||||
|
if ((err as { code?: string }).code === "SQLITE_CONSTRAINT_UNIQUE") {
|
||||||
|
err = new HttpError(409, "This already exists. Please try again with a different value.");
|
||||||
|
}
|
||||||
if (err instanceof HttpError) {
|
if (err instanceof HttpError) {
|
||||||
if (isApi) return c.json({ error: err.message, issues: err.issues }, err.status);
|
if (isApi) return c.json({ error: err.message, issues: err.issues }, err.status);
|
||||||
return c.html(<MessagePage title="Something went wrong" message={err.message} link={{ href: "/~/", label: "Back" }} />, err.status);
|
return c.html(<MessagePage title="Something went wrong" message={err.message} link={{ href: "/~/", label: "Back" }} />, err.status);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Hono } from "hono";
|
|||||||
import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
|
import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
|
||||||
import type { AppEnv, Deps } from "../app.js";
|
import type { AppEnv, Deps } from "../app.js";
|
||||||
import { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "./oidc.js";
|
import { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "./oidc.js";
|
||||||
|
import { HttpError } from "../lib/errors.js";
|
||||||
import { createSession, deleteSession, SESSION_TTL_MS, upsertUser } from "./sessions.js";
|
import { createSession, deleteSession, SESSION_TTL_MS, upsertUser } from "./sessions.js";
|
||||||
|
|
||||||
export const SESSION_COOKIE = "short_session";
|
export const SESSION_COOKIE = "short_session";
|
||||||
@@ -38,7 +39,14 @@ export function authRoutes({ db, config, oidc }: Deps) {
|
|||||||
// Behind a reverse proxy the request URL may be internal, so rebuild it from BASE_URL.
|
// Behind a reverse proxy the request URL may be internal, so rebuild it from BASE_URL.
|
||||||
const requestUrl = new URL(c.req.url);
|
const requestUrl = new URL(c.req.url);
|
||||||
const currentUrl = new URL(`${redirectUri}${requestUrl.search}`);
|
const currentUrl = new URL(`${redirectUri}${requestUrl.search}`);
|
||||||
const claims = await oidc.exchange({ currentUrl, state, codeVerifier });
|
let claims;
|
||||||
|
try {
|
||||||
|
claims = await oidc.exchange({ currentUrl, state, codeVerifier });
|
||||||
|
} catch (err) {
|
||||||
|
// E.g. the login was cancelled at the identity provider or took too long.
|
||||||
|
console.warn("OIDC callback failed:", err instanceof Error ? err.message : err);
|
||||||
|
throw new HttpError(400, "Sign-in failed. Please try again.");
|
||||||
|
}
|
||||||
const actor = upsertUser(db, claims, config.adminGroup);
|
const actor = upsertUser(db, claims, config.adminGroup);
|
||||||
|
|
||||||
setCookie(c, SESSION_COOKIE, createSession(db, actor.id), {
|
setCookie(c, SESSION_COOKIE, createSession(db, actor.id), {
|
||||||
|
|||||||
@@ -75,3 +75,14 @@ export function createApiToken(db: Db, userId: number, name: string) {
|
|||||||
export function pruneSessions(db: Db, now = new Date()): number {
|
export function pruneSessions(db: Db, now = new Date()): number {
|
||||||
return db.delete(sessions).where(lt(sessions.expiresAt, now)).run().changes;
|
return db.delete(sessions).where(lt(sessions.expiresAt, now)).run().changes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ends all sessions and deletes all API tokens of a user, e.g. when they leave.
|
||||||
|
// They can sign in again only if Authentik still lets them.
|
||||||
|
export function revokeAccess(db: Db, username: string): { sessions: number; tokens: number } | null {
|
||||||
|
const user = db.select().from(users).where(eq(users.username, username)).get();
|
||||||
|
if (!user) return null;
|
||||||
|
return db.transaction((tx) => ({
|
||||||
|
sessions: tx.delete(sessions).where(eq(sessions.userId, user.id)).run().changes,
|
||||||
|
tokens: tx.delete(apiTokens).where(eq(apiTokens.userId, user.id)).run().changes,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ import { LinkPage, MessagePage } from "./views.js";
|
|||||||
export function publicRoutes({ db, config }: Deps) {
|
export function publicRoutes({ db, config }: Deps) {
|
||||||
const clientIp = (c: Context<AppEnv>): string => {
|
const clientIp = (c: Context<AppEnv>): string => {
|
||||||
if (config.trustProxy) {
|
if (config.trustProxy) {
|
||||||
const forwarded = c.req.header("x-forwarded-for")?.split(",")[0]?.trim();
|
// The last entry is the one added by our proxy; earlier ones can be set by the client.
|
||||||
|
const forwarded = c.req.header("x-forwarded-for")?.split(",").at(-1)?.trim();
|
||||||
if (forwarded) return forwarded;
|
if (forwarded) return forwarded;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,15 +1,51 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { ChevronRight, Link2, MousePointerClick, PanelsTopLeft, Plus, UserX } from "lucide-react";
|
import { ChevronRight, Link2, MousePointerClick, PanelsTopLeft, Plus, ShieldOff, UserX } from "lucide-react";
|
||||||
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
|
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
|
||||||
import { useApi } from "../api.js";
|
import { api, useApi } from "../api.js";
|
||||||
import { CreatePageDialog } from "../components/CreatePageDialog.js";
|
import { CreatePageDialog } from "../components/CreatePageDialog.js";
|
||||||
import { PageTable } from "../components/PageTable.js";
|
import { PageTable } from "../components/PageTable.js";
|
||||||
import { Button, buttonClass } from "../components/ui/button.js";
|
import { Button, buttonClass } from "../components/ui/button.js";
|
||||||
import { Link, Stat } from "../components/ui/misc.js";
|
import { Link, Stat } from "../components/ui/misc.js";
|
||||||
import { EmptyState, Skeleton } from "../components/ui/surface.js";
|
import { useConfirm } from "../components/ui/dialog.js";
|
||||||
import { useToast } from "../components/ui/toast.js";
|
import { Card, CardHeader, EmptyState, Skeleton } from "../components/ui/surface.js";
|
||||||
|
import { useAction, useToast } from "../components/ui/toast.js";
|
||||||
import { detailPath, navigate } from "../router.js";
|
import { detailPath, navigate } from "../router.js";
|
||||||
|
|
||||||
|
// Offboarding: ends the user's sessions and deletes their API tokens. Their content stays online.
|
||||||
|
function RevokeAccessCard({ username }: { username: string }) {
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const { busy, run } = useAction();
|
||||||
|
const toast = useToast();
|
||||||
|
|
||||||
|
const revoke = async () => {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: `Revoke ${username}'s access?`,
|
||||||
|
description: `${username} is signed out everywhere and their API tokens are deleted. Their links and pages stay online. To stop them from signing in again, remove their access in Authentik.`,
|
||||||
|
confirmLabel: "Revoke access",
|
||||||
|
danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
void run(async () => {
|
||||||
|
const { sessions, tokens } = await api<{ sessions: number; tokens: number }>("DELETE", `/users/${encodeURIComponent(username)}/access`);
|
||||||
|
toast(`Ended ${sessions} ${sessions === 1 ? "session" : "sessions"}, deleted ${tokens} API ${tokens === 1 ? "token" : "tokens"}`);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="border-danger/30">
|
||||||
|
<CardHeader
|
||||||
|
title={<span className="text-danger">Revoke access</span>}
|
||||||
|
description="Sign this user out everywhere and delete their API tokens, e.g. when they leave. Their links and pages stay online."
|
||||||
|
actions={
|
||||||
|
<Button variant="danger" size="sm" icon={<ShieldOff />} loading={busy} onClick={() => void revoke()}>
|
||||||
|
Revoke access
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Everything one user owns, for admins. Kept apart from the admin's own and root content.
|
// Everything one user owns, for admins. Kept apart from the admin's own and root content.
|
||||||
export function AdminUserScreen({ username, me }: { username: string; me: Me }) {
|
export function AdminUserScreen({ username, me }: { username: string; me: Me }) {
|
||||||
const users = useApi<string[]>("/users");
|
const users = useApi<string[]>("/users");
|
||||||
@@ -88,6 +124,8 @@ export function AdminUserScreen({ username, me }: { username: string; me: Me })
|
|||||||
<h2 className="mb-3 text-base font-semibold">Link pages</h2>
|
<h2 className="mb-3 text-base font-semibold">Link pages</h2>
|
||||||
<PageTable kind="linkpage" pages={theirs} empty={{ title: "No link pages", description: `${username} hasn't created any link pages.` }} />
|
<PageTable kind="linkpage" pages={theirs} empty={{ title: "No link pages", description: `${username} hasn't created any link pages.` }} />
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<RevokeAccessCard username={username} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{creating && (
|
{creating && (
|
||||||
|
|||||||
@@ -63,6 +63,17 @@ describe("authentication", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("shows a friendly page when the identity provider rejects the login", async () => {
|
||||||
|
const { app, setNextLogin } = setup();
|
||||||
|
const login = await app.request("/~/auth/login");
|
||||||
|
setNextLogin(new Error("state mismatch"));
|
||||||
|
const res = await app.request("/~/auth/callback?code=c&state=s", {
|
||||||
|
headers: { cookie: login.headers.get("set-cookie")!.split(";")[0]! },
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(await res.text()).toContain("Sign-in failed");
|
||||||
|
});
|
||||||
|
|
||||||
it("rejects usernames that aren't URL-safe", async () => {
|
it("rejects usernames that aren't URL-safe", async () => {
|
||||||
const { app, setNextLogin } = setup();
|
const { app, setNextLogin } = setup();
|
||||||
const login = await app.request("/~/auth/login");
|
const login = await app.request("/~/auth/login");
|
||||||
@@ -167,6 +178,24 @@ describe("namespaces and permissions", () => {
|
|||||||
expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "r" })).status).toBe(200);
|
expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "r" })).status).toBe(200);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("lets admins revoke a user's sessions and API tokens", async () => {
|
||||||
|
const { app, user } = setup();
|
||||||
|
const alice = user("alice");
|
||||||
|
const bob = user("bob");
|
||||||
|
const admin = user("root", true);
|
||||||
|
const cookie = `short_session=${alice.session}`;
|
||||||
|
|
||||||
|
expect((await bob.api("DELETE", "/users/alice/access")).status).toBe(403);
|
||||||
|
expect((await admin.api("DELETE", "/users/nobody/access")).status).toBe(404);
|
||||||
|
|
||||||
|
const res = await admin.api("DELETE", "/users/alice/access");
|
||||||
|
expect(await res.json()).toEqual({ sessions: 1, tokens: 1 });
|
||||||
|
expect((await alice.api("GET", "/me")).status).toBe(401);
|
||||||
|
expect((await app.request("/~/api/me", { headers: { cookie } })).status).toBe(401);
|
||||||
|
// Other users are unaffected.
|
||||||
|
expect((await bob.api("GET", "/me")).status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
it("restricts admin-only endpoints", async () => {
|
it("restricts admin-only endpoints", async () => {
|
||||||
const { user } = setup();
|
const { user } = setup();
|
||||||
const alice = user("alice");
|
const alice = user("alice");
|
||||||
@@ -323,6 +352,21 @@ describe("redirects and stats", () => {
|
|||||||
expect((await (await alice.api("GET", `/pages/${page.id}/stats`)).json()).total).toBe(0);
|
expect((await (await alice.api("GET", `/pages/${page.id}/stats`)).json()).total).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("uses the proxy-added X-Forwarded-For entry, not the client-supplied ones", async () => {
|
||||||
|
const { app, user } = setup();
|
||||||
|
const alice = user("alice");
|
||||||
|
const page = await (await alice.api("POST", "/pages", { kind: "redirect", code: "cv", dest: "https://example.com/cv" })).json();
|
||||||
|
|
||||||
|
// Same real client (last entry) faking different addresses in front: still one visitor.
|
||||||
|
for (const fake of ["10.0.0.1", "10.9.9.9", "172.16.0.1"]) {
|
||||||
|
await app.request("/alice/cv", { headers: { "x-forwarded-for": `${fake}, 5.6.7.8`, "user-agent": "test" } });
|
||||||
|
}
|
||||||
|
await flush();
|
||||||
|
const stats = await (await alice.api("GET", `/pages/${page.id}/stats`)).json();
|
||||||
|
expect(stats.today).toBe(3);
|
||||||
|
expect(stats.uniquesToday).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
it("returns 404 for unknown links and the pinned page at the root", async () => {
|
it("returns 404 for unknown links and the pinned page at the root", async () => {
|
||||||
const { app, user } = setup();
|
const { app, user } = setup();
|
||||||
expect((await app.request("/nope")).status).toBe(404);
|
expect((await app.request("/nope")).status).toBe(404);
|
||||||
|
|||||||
+6
-3
@@ -27,10 +27,13 @@ export function setup(overrides: Partial<Config> = {}) {
|
|||||||
const db = openDb(":memory:");
|
const db = openDb(":memory:");
|
||||||
|
|
||||||
// The fake provider returns whatever claims the test queued for the next login.
|
// The fake provider returns whatever claims the test queued for the next login.
|
||||||
let nextClaims: OidcClaims = { sub: "sub-x", username: "x", groups: [] };
|
let nextClaims: OidcClaims | Error = { sub: "sub-x", username: "x", groups: [] };
|
||||||
const oidc: OidcProvider = {
|
const oidc: OidcProvider = {
|
||||||
authorizationUrl: async ({ state }) => new URL(`https://auth.test/authorize?state=${state}`),
|
authorizationUrl: async ({ state }) => new URL(`https://auth.test/authorize?state=${state}`),
|
||||||
exchange: async () => nextClaims,
|
exchange: async () => {
|
||||||
|
if (nextClaims instanceof Error) throw nextClaims;
|
||||||
|
return nextClaims;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const app = createApp({ db, config, oidc });
|
const app = createApp({ db, config, oidc });
|
||||||
@@ -53,7 +56,7 @@ export function setup(overrides: Partial<Config> = {}) {
|
|||||||
db,
|
db,
|
||||||
config,
|
config,
|
||||||
user,
|
user,
|
||||||
setNextLogin: (claims: OidcClaims) => {
|
setNextLogin: (claims: OidcClaims | Error) => {
|
||||||
nextClaims = claims;
|
nextClaims = claims;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user