Profile pictures from Gravatar or the identity provider, fetched and kept by the server

Both sources are off until switched on under Settings, Sign-in. The server asks only
gravatar.com (by a hash of the email) and the identity provider's own host, accepts only
small PNG/JPEG/WebP/GIF, keeps each picture for a day and serves it from /api/avatars/<id>,
so browsers never contact either. Shown in the user menu and on the Users page, with initials
as the fallback; the Privacy page says when it is on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-18 23:47:50 +02:00
1 parent 9782bd3252
commit c05c847d17
26 files changed
+4361 -21

No files matched your search

+252
View File
@@ -0,0 +1,252 @@
/**
* Profile pictures: where they may come from, what is accepted, that nothing is asked of anyone while the settings are off, and that the
* browser only ever talks to this app.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after, beforeEach } from "node:test";
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-avatars-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
process.env.AUTHENTIK_ISSUER_URL = "https://auth.example.lan/application/o/homelab/";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { avatarsRouter } = await import("../src/routes/avatars.js");
const { meRouter } = await import("../src/routes/me.js");
const { usersRouter } = await import("../src/routes/users.js");
const { upsertUserFromLogin } = await import("../src/auth/users.js");
const { updateSettings } = await import("../src/services/settingsStore.js");
const { gravatarHash, gravatarUrl, isAllowedPictureUrl, pictureFromClaims, avatarSources, avatarUrlFor, getAvatar, setAvatarFetcherForTests } = await import("../src/services/avatars.js");
await runMigrations();
const IDP = "auth.example.lan";
const PNG = Buffer.from("89504e470d0a1a0a0000000d49484452", "hex");
const none = { gravatar: false, identityProvider: false };
const both = { gravatar: true, identityProvider: true };
describe("where a picture may come from", () => {
test("Gravatar gets a hash of the address — trimmed, lower case, SHA-256 — never the address itself", () => {
const hash = createHash("sha256").update("olga@example.com").digest("hex");
assert.equal(gravatarHash(" Olga@Example.COM "), hash);
assert.equal(gravatarUrl("Olga@example.com"), `https://gravatar.com/avatar/${hash}?s=128&d=404`);
assert.equal(gravatarUrl("Olga@example.com").includes("olga"), false);
});
test("only Gravatar over HTTPS and the identity provider's own host are allowed", () => {
assert.equal(isAllowedPictureUrl("https://gravatar.com/avatar/abc", IDP), true);
assert.equal(isAllowedPictureUrl("https://secure.gravatar.com/avatar/abc", IDP), true);
assert.equal(isAllowedPictureUrl("http://gravatar.com/avatar/abc", IDP), false, "Gravatar only over HTTPS");
assert.equal(isAllowedPictureUrl("https://auth.example.lan/media/me.png", IDP), true);
assert.equal(isAllowedPictureUrl("http://auth.example.lan/media/me.png", IDP), true, "the provider's own host may be plain HTTP on a LAN");
for (const bad of ["https://evil.example/me.png", "https://gravatar.com.evil.example/a", "https://evilgravatar.com/a", "http://169.254.169.254/latest", "https://user:pw@auth.example.lan/x", "file:///etc/passwd", "not a url"]) {
assert.equal(isAllowedPictureUrl(bad, IDP), false, bad);
}
assert.equal(isAllowedPictureUrl("https://auth.example.lan/x", null), false, "with no provider known, only Gravatar");
});
test("the picture claim is read from the ID token or userinfo, and only if it is an address", () => {
assert.equal(pictureFromClaims([{ sub: "a" }, { picture: "https://auth.example.lan/media/me.png" }]), "https://auth.example.lan/media/me.png");
assert.equal(pictureFromClaims([{ picture: "not an address" }, { picture: "https://x.example/p.png" }]), "https://x.example/p.png", "an unusable claim is skipped for a usable one");
assert.equal(pictureFromClaims([{ picture: "javascript:alert(1)" }, { picture: 5 }, { picture: "" }, { picture: "https://x/" + "a".repeat(600) }]), undefined);
});
test("the provider's picture is tried before Gravatar; each needs its own setting; a claim naming Gravatar needs Gravatar on", () => {
const user = { email: "olga@example.com", pictureUrl: "https://auth.example.lan/media/olga.png" };
assert.deepEqual(avatarSources(user, none, IDP), []);
assert.deepEqual(avatarSources(user, { gravatar: false, identityProvider: true }, IDP), ["https://auth.example.lan/media/olga.png"]);
assert.deepEqual(avatarSources(user, { gravatar: true, identityProvider: false }, IDP), [gravatarUrl("olga@example.com")]);
assert.deepEqual(avatarSources(user, both, IDP), ["https://auth.example.lan/media/olga.png", gravatarUrl("olga@example.com")]);
const viaGravatar = { email: null, pictureUrl: gravatarUrl("olga@example.com") };
assert.deepEqual(avatarSources(viaGravatar, { gravatar: false, identityProvider: true }, IDP), [], "that would tell Gravatar all the same");
assert.deepEqual(avatarSources(viaGravatar, both, IDP), [gravatarUrl("olga@example.com")], "and one address is not asked twice");
assert.deepEqual(avatarSources({ email: "no-at-sign", pictureUrl: "https://evil.example/x.png" }, both, IDP), [], "a claim naming anywhere else, and no address, is no source");
});
test("the address the page uses changes when the source does, and is null with nothing to look for", () => {
const a = avatarUrlFor({ id: 7, email: "a@example.com", pictureUrl: null }, { gravatar: true, identityProvider: false })!;
const b = avatarUrlFor({ id: 7, email: "b@example.com", pictureUrl: null }, { gravatar: true, identityProvider: false })!;
assert.match(a, /^\/api\/avatars\/7\?v=[0-9a-f]{8}$/);
assert.notEqual(a, b);
assert.equal(avatarUrlFor({ id: 7, email: "a@example.com", pictureUrl: null }, none), null);
});
});
describe("fetching and keeping", () => {
let calls: string[] = [];
const image = (type = "image/png", body: Buffer = PNG) => new Response(body, { status: 200, headers: { "content-type": type } });
const answer = (fn: (url: string) => Response) => setAvatarFetcherForTests(async (url) => (calls.push(url), fn(url)));
const user = { email: "olga@example.com", pictureUrl: null };
const on = { gravatar: true, identityProvider: false };
beforeEach(() => {
calls = [];
});
after(() => setAvatarFetcherForTests(null));
test("nothing is asked of anyone while both settings are off", async () => {
answer(() => image());
assert.equal(await getAvatar(user, none), null);
assert.deepEqual(calls, []);
});
test("a picture comes back with its type, and is kept so the next ask does not go out again", async () => {
answer(() => image());
const first = await getAvatar(user, on);
assert.equal(first?.contentType, "image/png");
assert.deepEqual(first?.body, PNG);
await getAvatar(user, on);
assert.equal(calls.length, 1);
assert.equal(calls[0], gravatarUrl("olga@example.com"));
});
test("no picture (404) is kept for a while too, and falls through to the next source", async () => {
answer((url) => (url.includes("auth.example.lan") ? new Response("", { status: 404 }) : image("image/jpeg")));
const both_ = { user: { email: "olga@example.com", pictureUrl: "https://auth.example.lan/media/olga.png" }, settings: both };
assert.equal((await getAvatar(both_.user, both_.settings))?.contentType, "image/jpeg", "the provider had none, so Gravatar's");
await getAvatar(both_.user, both_.settings);
assert.equal(calls.filter((c) => c.includes("auth.example.lan")).length, 1, "the provider is not asked again straight away");
});
test("only small PNG, JPEG, WebP and GIF are accepted — not SVG, not HTML, not something huge", async () => {
answer(() => image("image/svg+xml", Buffer.from("<svg onload=alert(1)/>")));
assert.equal(await getAvatar({ email: "svg@example.com", pictureUrl: null }, on), null);
answer(() => image("text/html", Buffer.from("<script>")));
assert.equal(await getAvatar({ email: "html@example.com", pictureUrl: null }, on), null);
answer(() => image("image/png", Buffer.alloc(300 * 1024)));
assert.equal(await getAvatar({ email: "big@example.com", pictureUrl: null }, on), null);
answer(() => new Response(PNG, { status: 200, headers: { "content-type": "image/png", "content-length": "9999999" } }));
assert.equal(await getAvatar({ email: "declared@example.com", pictureUrl: null }, on), null);
});
test("a redirect is followed only to an address that is allowed, and not for ever", async () => {
answer((url) => (url.startsWith("https://gravatar.com/") ? new Response("", { status: 302, headers: { location: "https://secure.gravatar.com/avatar/x" } }) : image()));
assert.ok(await getAvatar({ email: "r1@example.com", pictureUrl: null }, on));
assert.equal(calls.length, 2);
calls = [];
answer(() => new Response("", { status: 302, headers: { location: "http://169.254.169.254/latest/meta-data" } }));
assert.equal(await getAvatar({ email: "r2@example.com", pictureUrl: null }, on), null);
assert.equal(calls.length, 1, "the metadata address was never asked");
calls = [];
answer((url) => new Response("", { status: 302, headers: { location: url + "x" } }));
assert.equal(await getAvatar({ email: "r3@example.com", pictureUrl: null }, on), null);
assert.ok(calls.length <= 3, "a redirect loop ends");
});
test("an unreachable host gives no picture and does not throw; it is tried again soon, not every page view", async () => {
setAvatarFetcherForTests(async (url) => {
calls.push(url);
throw new Error("connection refused");
});
assert.equal(await getAvatar({ email: "down@example.com", pictureUrl: null }, on), null);
await getAvatar({ email: "down@example.com", pictureUrl: null }, on);
assert.equal(calls.length, 1);
});
});
describe("through the routes", () => {
let app: Server;
let base = "";
let who = "olga";
let olgaId = 0;
let fetched: string[] = [];
before(async () => {
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
a.use("/api/me", meRouter);
a.use("/api/avatars", avatarsRouter);
a.use("/api/users", usersRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
// Through the sign-in code, as a login would: the first person is the administrator, and the picture claim is kept.
const olga = await upsertUserFromLogin({ sub: "olga", email: "Olga@example.com", name: "Olga", pictureUrl: "https://auth.example.lan/media/olga.png" });
olgaId = olga.user.id;
await upsertUserFromLogin({ sub: "vic", email: "vic@example.com", name: "Vic" });
setAvatarFetcherForTests(async (url) => {
fetched.push(url);
return url.includes("auth.example.lan") ? new Response("", { status: 404 }) : new Response(PNG, { status: 200, headers: { "content-type": "image/png" } });
});
});
after(() => {
app.close();
setAvatarFetcherForTests(null);
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const get = (path: string) => fetch(`${base}${path}`);
test("the picture claim from the sign-in is kept, and is still there when a later sign-in carries none", async () => {
const [row] = await db.select().from(users);
assert.equal(row.pictureUrl, "https://auth.example.lan/media/olga.png");
await upsertUserFromLogin({ sub: "olga", email: "Olga@example.com", name: "Olga" });
assert.equal((await db.select().from(users)).find((u) => u.oidcSub === "olga")!.pictureUrl, "https://auth.example.lan/media/olga.png");
});
test("with the settings off there is no picture address for anyone and nothing is fetched", async () => {
assert.equal((await (await get("/me")).json()).user.avatarUrl, null);
assert.equal((await get(`/avatars/${olgaId}`)).status, 404);
const list = (await (await get("/users")).json()).users as { avatarUrl: string | null }[];
assert.deepEqual(list.map((u) => u.avatarUrl), [null, null]);
assert.deepEqual(fetched, []);
});
test("turned on, the browser is given an address on this app, and the picture is served from here with safe headers", async () => {
await updateSettings({ profilePictures: { gravatar: true, identityProvider: true } });
const me = (await (await get("/me")).json()).user;
assert.match(me.avatarUrl, new RegExp(`^/api/avatars/${olgaId}\\?v=`));
who = "vic"; // anyone signed in may see anyone's picture
const res = await fetch(`${base.slice(0, -"/api".length)}${me.avatarUrl}`);
assert.equal(res.status, 200);
assert.equal(res.headers.get("content-type"), "image/png");
assert.match(res.headers.get("cache-control") ?? "", /private, max-age=\d+/);
assert.match(res.headers.get("content-security-policy") ?? "", /sandbox/);
assert.deepEqual(Buffer.from(await res.arrayBuffer()), PNG);
assert.deepEqual(fetched[0], "https://auth.example.lan/media/olga.png", "the provider is tried first");
assert.equal(fetched[1], gravatarUrl("olga@example.com"), "then Gravatar, with the address lower-cased and hashed");
who = "olga";
});
test("the Users page is told who has a picture to look for; someone unknown or a bad id is simply not found", async () => {
const list = (await (await get("/users")).json()).users as { name: string; avatarUrl: string | null }[];
assert.match(list.find((u) => u.name === "Olga")!.avatarUrl!, /^\/api\/avatars\//);
assert.equal((await get("/avatars/99999")).status, 404);
assert.equal((await get("/avatars/abc")).status, 404);
assert.equal((await get("/avatars/1e3")).status, 404);
});
test("a person with no email and no usable claim has no picture to look for", async () => {
await upsertUserFromLogin({ sub: "nomail", name: "No Mail" });
who = "nomail";
assert.equal((await (await get("/me")).json()).user.avatarUrl, null);
who = "olga";
});
});
+2 -1
View File
@@ -158,7 +158,8 @@ describe("the Users routes", () => {
assert.equal(body.rolesFollowGroups, true);
const olga = body.users.find((u: { name: string }) => u.name === "olga");
assert.deepEqual(olga.groups, ["cooks"]);
assert.deepEqual(Object.keys(olga).sort(), ["createdAt", "email", "groups", "id", "lastLoginAt", "name", "oidcSub", "role"]);
assert.deepEqual(Object.keys(olga).sort(), ["avatarUrl", "createdAt", "email", "groups", "id", "lastLoginAt", "name", "oidcSub", "role"]);
assert.equal(olga.avatarUrl, null, "no picture source is on, so none to look for");
});
test("a role can't be set by hand while groups decide it", async () => {