Let Google Workspace groups grant admin access

Site settings → Access names a group for each of admin, editor and
viewer (migration 047). Someone in one who signs in with Google gets a
Google-only account with their highest group's role, and the role
follows the groups: at every sign-in, hourly while signed in, and on
Panel → Google groups → Re-sync now. Out of every group, the account
is disabled and signed out until they're back in one.

Group accounts' roles are locked in the Panel; a superadmin's Disable
sticks. Superadmins and admin-cli accounts are never changed. If
Google can't be asked, sign-ins are refused but the hourly check
leaves accounts alone. Panel → Check their groups tests an email.

Lookups use the service account through the Directory API as
GOOGLE_DIRECTORY_AS. Setup: docs/google-sign-in.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 17:44:04 -05:00
parent d7835dd5d4
commit 80877a4659
13 changed files with 563 additions and 36 deletions

132
server/src/accessGroups.js Normal file
View file

@ -0,0 +1,132 @@
/* ═══════════════════════════════════════════════════════════════
ADMIN ACCESS BY GOOGLE GROUP
Panel → Site settings → Access names a Workspace group for each of
viewer, editor and admin. Someone in one of them who signs in with
Google gets an account (access_source 'group', no password) with
the highest of those roles; routes/auth.js calls groupRole() and
applyGroupRole() at every Google sign-in.
The role then follows the group:
at sign-in always checked
while signed in startGroupSync() rechecks accounts with a
live session every SYNC_EVERY_MS, once
their last check is STALE_AFTER_MS old
Panel → Re-sync now every group account, straight away
Out of every group: the account is disabled (group_disabled = 1)
and signed out; back in one, the next sign-in or sync turns it on
again. A superadmin's Disable in the Panel sets group_disabled = 0,
which no group check undoes.
Never touched: superadmins and 'manual' accounts (admin-cli, which
may also sign in with Google as before).
If Google can't be asked, a sign-in is refused (it can't be shown
to be allowed), but a background recheck leaves the account as it
is and tries again next time: an outage shouldn't sign everyone out.
Needs GOOGLE_DIRECTORY_AS (googleService.js) and at least one group.
Setup: docs/google-sign-in.md.
═══════════════════════════════════════════════════════════════ */
import { directoryReady, isGroupMember } from "./googleService.js";
const SYNC_EVERY_MS = 10 * 60 * 1000;
const STALE_AFTER_MS = 30 * 60 * 1000;
// Highest first: the first group someone is in gives their role.
const GROUP_ROLES = ["admin", "editor", "viewer"];
/* [[role, group address], ...], highest role first, set ones only. */
export function accessGroups(db) {
const row =
db
.prepare(
`SELECT access_group_viewer, access_group_editor, access_group_admin
FROM site_settings WHERE id = 'site'`,
)
.get() ?? {};
return GROUP_ROLES.map((role) => [role, String(row[`access_group_${role}`] ?? "").trim().toLowerCase()]).filter(
([, group]) => group,
);
}
export const accessEnabled = (db) => directoryReady() && accessGroups(db).length > 0;
/* The role someone's groups give them, or null for none. Throws a
GoogleError when Google can't say. */
export async function groupRole(db, email) {
for (const [role, group] of accessGroups(db)) {
if (await isGroupMember(group, email)) return role;
}
return null;
}
/* Brings a group account in line with `role` (null: in no group).
Returns what changed, as text for the log and the Panel, or null. */
export function applyGroupRole(db, user, role) {
let change = null;
if (!role) {
if (user.is_active === 1) {
db.prepare(`UPDATE admin_users SET is_active = 0, group_disabled = 1 WHERE id = ?`).run(user.id);
db.prepare(`DELETE FROM sessions WHERE user_id = ?`).run(user.id);
change = "disabled: in no access group";
}
} else if (user.is_active !== 1 || user.role !== role) {
db.prepare(`UPDATE admin_users SET role = ?, is_active = 1, group_disabled = 0 WHERE id = ?`).run(role, user.id);
change = user.is_active !== 1 ? `enabled as ${role}` : `${user.role} → ${role}`;
}
db.prepare(`UPDATE admin_users SET groups_checked_at = datetime('now') WHERE id = ?`).run(user.id);
if (change) console.log(`access: ${user.email} ${change}`);
return change;
}
/* Rechecks group accounts: all of them (Panel → Re-sync now), or only
those signed in whose last check is stale (the timer). Accounts a
superadmin disabled are left alone. */
export async function syncGroupAccounts(db, { all = false } = {}) {
const users = db
.prepare(
`SELECT u.id, u.email, u.role, u.is_active FROM admin_users u
WHERE u.access_source = 'group' AND u.role <> 'superadmin'
AND (u.is_active = 1 OR u.group_disabled = 1)
${
all
? ""
: `AND u.is_active = 1
AND EXISTS (SELECT 1 FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now'))
AND (u.groups_checked_at IS NULL OR u.groups_checked_at <= datetime('now', ?))`
}`,
)
.all(...(all ? [] : [`-${STALE_AFTER_MS / 1000} seconds`]));
const result = { checked: 0, changes: [], failed: [] };
for (const user of users) {
try {
const change = applyGroupRole(db, user, await groupRole(db, user.email));
result.checked++;
if (change) result.changes.push(`${user.email}: ${change}`);
} catch (err) {
console.warn(`access: couldn't check ${user.email}: ${err.message}`);
result.failed.push(`${user.email}: ${err.message}`);
}
}
return result;
}
export function startGroupSync(db) {
let running = false;
const tick = async () => {
if (running || !accessEnabled(db)) return;
running = true;
try {
await syncGroupAccounts(db);
} catch (err) {
console.error("access sync failed", err);
} finally {
running = false;
}
};
setInterval(tick, SYNC_EVERY_MS).unref();
}

View file

@ -31,6 +31,9 @@ export const siteSettings = {
enumeration("indexing", ["on", "off"]),
text("privacy_email"),
text("notify_emails"),
text("access_group_viewer"),
text("access_group_editor"),
text("access_group_admin"),
],
children: [

View file

@ -4,7 +4,7 @@
The server acting as itself (not a person signing in, that's
googleAuth.js). A service account's key signs a short JWT, which
Google swaps for an access token (RS256 with node:crypto, no
library). Two uses:
library). Three uses:
Drive one shared drive (a service account has no storage of
its own), with a folder per use: "Requests" for files sent
@ -13,6 +13,9 @@
"Blog/2026" makes each level.
Gmail new-request notices, sent as a Workspace user through
domain-wide delegation.
Groups who is in the admin access groups (accessGroups.js), read
through the Directory API as a Workspace admin, the same
delegation.
Configured by the service environment:
@ -21,6 +24,8 @@
GOOGLE_SHARED_DRIVE the shared drive's id: only the last part
of its address, not the whole URL
GOOGLE_MAIL_FROM the Workspace address notices come from
GOOGLE_DIRECTORY_AS a Workspace admin (a user) whose view of
groups is read
Each part is off until its settings are there: without a shared drive
the form offers no uploads, and without a sender no mail goes out.
@ -32,6 +37,7 @@ import { createSign } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
const GROUPS_SCOPE = "https://www.googleapis.com/auth/admin.directory.group.member.readonly";
const DRIVE = "https://www.googleapis.com/drive/v3/files";
const DRIVE_UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
@ -51,6 +57,7 @@ function serviceKey() {
export const driveReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_SHARED_DRIVE);
export const mailReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_MAIL_FROM);
export const directoryReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_DIRECTORY_AS);
/* ── Access tokens, kept until a minute before they run out ──── */
@ -220,3 +227,23 @@ export async function sendMail({ to, subject, text, replyTo }) {
from,
);
}
/* ── Groups ──────────────────────────────────────────────────── */
/* Whether someone is in a group, directly or through a group inside
it (the Directory API's hasMember follows nesting in the domain). */
export async function isGroupMember(group, email) {
const url =
"https://admin.googleapis.com/admin/directory/v1/groups/" +
`${encodeURIComponent(group)}/hasMember/${encodeURIComponent(email)}`;
try {
const res = await call(url, {}, GROUPS_SCOPE, process.env.GOOGLE_DIRECTORY_AS);
return (await res.json()).isMember === true;
} catch (err) {
// An address Google doesn't know ("Invalid Input: memberKey",
// "Resource Not Found: memberKey") is in no group of ours. A group
// it doesn't know (groupKey) is a setup mistake, and throws.
if (/^40[04] .*memberKey/i.test(err.message)) return false;
throw new GoogleError(`${group}: ${err.message}`);
}
}

View file

@ -40,6 +40,7 @@ import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { ENTITIES } from "./admin-schema.js";
const HOST = process.env.HOST ?? "127.0.0.1";
@ -213,6 +214,7 @@ app.use(
app.route("/", pages);
startSessionSweeper(db);
startGroupSync(db);
startClipWorker(db);
console.log(`clips ${CLIPS_DIR}`);

View file

@ -0,0 +1,29 @@
-- ═══════════════════════════════════════════════════════════════
-- 047 ACCESS BY GOOGLE GROUP
--
-- Admin access from Google Workspace groups (accessGroups.js).
-- Panel → Site settings → Access names a group for each of viewer,
-- editor and admin. Someone in one of them who signs in with Google
-- gets an account with the highest of those roles, and keeps it only
-- while they're in the group. Superadmins and admin-cli accounts are
-- never touched.
--
-- admin_users.access_source 'manual' (admin-cli, the Panel) or
-- 'group' (made by a group sign-in;
-- Google only, role follows the group)
-- admin_users.group_disabled 1 when a group check turned it off
-- (back in a group turns it on again);
-- a superadmin's Disable sets 0, and
-- that one sticks
-- admin_users.groups_checked_at the last group check, UTC
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE admin_users ADD COLUMN access_source TEXT NOT NULL DEFAULT 'manual'
CHECK (access_source IN ('manual', 'group'));
ALTER TABLE admin_users ADD COLUMN group_disabled INTEGER NOT NULL DEFAULT 0
CHECK (group_disabled IN (0, 1));
ALTER TABLE admin_users ADD COLUMN groups_checked_at TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_viewer TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_editor TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_admin TEXT;

View file

@ -19,12 +19,14 @@
A failed login still runs a hash. Otherwise the response time
itself says whether the account exists.
Nothing here creates accounts. See admin-cli.js. Google sign-in
only lets in an account that already exists: matched by its
linked Google id, or on first use by its email, which then links
it. A matching email already linked to a different Google
account is refused rather than relinked. googleAuth.js checks
the identity itself.
Accounts come from admin-cli.js, with one exception: with access
groups set up (accessGroups.js), a Google sign-in by someone in
one makes a group account, whose role then follows the group.
Otherwise Google sign-in only lets in an account that already
exists: matched by its linked Google id, or on first use by its
email, which then links it. A matching email already linked to a
different Google account is refused rather than relinked.
googleAuth.js checks the identity itself.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
@ -41,6 +43,7 @@ import {
verifyPassword,
} from "../auth.js";
import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js";
import { accessEnabled, applyGroupRole, groupRole } from "../accessGroups.js";
import { failureLimit } from "../rateLimit.js";
import { NO_STORE } from "../shape.js";
@ -208,24 +211,65 @@ auth.get("/google/callback", async (c) => {
}
const db = c.get("db");
const columns = `id, email, name, role, is_active, google_sub`;
const columns = `id, email, name, role, is_active, google_sub, access_source, group_disabled`;
const byId = (id) => db.prepare(`SELECT ${columns} FROM admin_users WHERE id = ?`).get(id);
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
// What the access groups give this person (accessGroups.js), asked
// only when it matters. Unanswerable is a refusal: a sign-in has to
// be shown to be allowed.
const roleFromGroups = async () => {
try {
return { role: await groupRole(db, identity.email) };
} catch (err) {
console.warn(`google login: groups unreadable for ${identity.email}: ${err.message}`);
return { failed: true };
}
};
if (!user) {
const byEmail = db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
if (!byEmail) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
}
if (byEmail.google_sub) {
if (!accessEnabled(db)) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
}
// In an access group: the account is made now, Google only.
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
if (!found.role) {
console.warn(`google login: ${identity.email} is in no access group`);
return backToLogin(c, "not_in_group");
}
const id = db
.prepare(
`INSERT INTO admin_users (email, name, role, google_sub, access_source, groups_checked_at)
VALUES (?, ?, ?, ?, 'group', datetime('now'))`,
)
.run(identity.email, identity.name, found.role, identity.sub).lastInsertRowid;
console.log(`account ${identity.email} made from access group (${found.role})`);
user = byId(id);
} else if (byEmail.google_sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
return backToLogin(c, "linked_elsewhere");
} else {
// Before linking: a refused sign-in mustn't change the account.
if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
console.log(`google account linked to ${byEmail.email}`);
user = byEmail;
}
// Before linking: a refused sign-in mustn't change the account.
if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
console.log(`google account linked to ${byEmail.email}`);
user = byEmail;
}
// A group account's role follows its groups, checked every time.
// One a superadmin disabled stays disabled whatever its groups say.
if (user.access_source === "group" && user.role !== "superadmin" && accessEnabled(db)) {
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
applyGroupRole(db, user, found.role);
if (!found.role) return backToLogin(c, "not_in_group");
user = byId(user.id);
}
if (user.is_active !== 1) return backToLogin(c, "disabled");

View file

@ -5,6 +5,8 @@
PATCH /api/admin/panel/users/:id role, is_active
DELETE /api/admin/panel/users/:id/sessions sign out everywhere
POST /api/admin/panel/test-notice { to }: a test email
POST /api/admin/panel/access-sync recheck every group account
POST /api/admin/panel/access-check { email }: what their groups give
Everything here is superadmin-only, enforced once at the top
rather than per route; there's no read here that an ordinary
@ -28,8 +30,9 @@ import { Hono } from "hono";
import { requireAuth, requireRole, ROLES } from "../auth.js";
import { tx } from "../db.js";
import { NO_STORE } from "../shape.js";
import { mailReady, sendMail } from "../googleService.js";
import { directoryReady, mailReady, sendMail } from "../googleService.js";
import { addresses } from "../notify.js";
import { accessEnabled, accessGroups, groupRole, syncGroupAccounts } from "../accessGroups.js";
const panel = new Hono();
@ -57,7 +60,8 @@ panel.get("/overview", (c) => {
const users = db
.prepare(
`SELECT u.id, u.email, u.name, u.role, u.is_active,
u.created_at, u.last_login_at,
u.created_at, u.last_login_at, u.access_source, u.group_disabled,
u.groups_checked_at,
(SELECT COUNT(*) FROM sessions s
WHERE s.user_id = u.id
AND s.expires_at > datetime('now')) AS sessions
@ -85,6 +89,12 @@ panel.get("/overview", (c) => {
},
content,
users,
// Google groups (accessGroups.js): which are set, and whether the
// server can read them.
access: {
directory: directoryReady(),
groups: Object.fromEntries(accessGroups(db)),
},
},
200,
NO_STORE,
@ -127,10 +137,17 @@ panel.patch("/users/:id", async (c) => {
}
const target = db
.prepare("SELECT id, email, role, is_active FROM admin_users WHERE id = ?")
.prepare("SELECT id, email, role, is_active, access_source FROM admin_users WHERE id = ?")
.get(id);
if (!target) return c.json({ error: "No such account." }, 404);
if (target.access_source === "group" && body.role !== undefined && body.role !== target.role) {
return c.json(
{ error: "This account's role comes from its Google group. Change the group membership instead." },
409,
);
}
const sets = [];
const params = [];
@ -155,6 +172,8 @@ panel.patch("/users/:id", async (c) => {
if (body.is_active !== undefined) {
sets.push("is_active = ?");
params.push(Number(body.is_active) ? 1 : 0);
// A superadmin's choice: no group check undoes it (accessGroups.js).
sets.push("group_disabled = 0");
}
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
@ -208,7 +227,8 @@ function userRow(db, id) {
return db
.prepare(
`SELECT u.id, u.email, u.name, u.role, u.is_active,
u.created_at, u.last_login_at,
u.created_at, u.last_login_at, u.access_source, u.group_disabled,
u.groups_checked_at,
(SELECT COUNT(*) FROM sessions s
WHERE s.user_id = u.id
AND s.expires_at > datetime('now')) AS sessions
@ -255,4 +275,46 @@ panel.post("/test-notice", async (c) => {
return c.json({ sent: to, from }, 200, NO_STORE);
});
/* ── Access by Google group ──────────────────────────────────────
access-sync every group account against its groups now (the
timer only rechecks signed-in ones, hourly)
access-check what someone's groups would give them, changing
nothing: for checking the setup
───────────────────────────────────────────────────────────── */
const accessOff = (c, db) =>
accessEnabled(db)
? null
: c.json(
{
error: directoryReady()
? "No access groups set: Panel → Site settings → Access."
: "Group lookups aren't set up on the server: GOOGLE_SERVICE_ACCOUNT and GOOGLE_DIRECTORY_AS (docs/google-sign-in.md).",
},
400,
);
panel.post("/access-sync", async (c) => {
const db = c.get("db");
const off = accessOff(c, db);
if (off) return off;
const result = await syncGroupAccounts(db, { all: true });
console.log(`access re-sync by ${c.get("user").email}: ${result.checked} checked, ${result.changes.length} changed, ${result.failed.length} failed`);
return c.json(result, 200, NO_STORE);
});
panel.post("/access-check", async (c) => {
const db = c.get("db");
const off = accessOff(c, db);
if (off) return off;
const body = (await c.req.json().catch(() => null)) ?? {};
const email = String(body.email ?? "").trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return c.json({ error: "Enter an email address." }, 422);
try {
return c.json({ email, role: await groupRole(db, email) }, 200, NO_STORE);
} catch (err) {
return c.json({ error: `Google couldn't say: ${err.message}` }, 502);
}
});
export default panel;