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:
parent
d7835dd5d4
commit
80877a4659
13 changed files with 563 additions and 36 deletions
|
|
@ -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");
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue