-
Notifications
You must be signed in to change notification settings - Fork 0
Admin: Create admin table #101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
RandyJDean
wants to merge
1
commit into
main
Choose a base branch
from
08-31-admin_create_admin_table
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| -- Admin allowlist. Rows are inserted by hand (psql against the target database) -- | ||
| -- there is deliberately no API or UI for managing them, so the application has no | ||
| -- write path to its own permission table. Consulted once per sign-in, so grants and | ||
| -- revocations take effect at the member's next magic-link login. | ||
| -- | ||
| -- Keyed by email rather than member id, matching magic_link_tokens: an address can be | ||
| -- allowlisted before the person signs up, and the grant survives a member row being | ||
| -- rewritten. No FK to members -- the grant only has an effect at login, where the | ||
| -- member row must exist anyway, so a dangling row is inert rather than dangerous. | ||
|
|
||
| -- The single definition of a canonical address, shared by the write path (the trigger | ||
| -- below) and the read path (AdminRepo). Having exactly one definition is the point: | ||
| -- if writes normalised one way and lookups another, a correctly-listed admin would | ||
| -- silently be granted nothing. Deliberately not scoped to admins -- the member domain | ||
| -- stores raw addresses today and should adopt this. | ||
| -- | ||
| -- BTRIM is given an explicit character set because the bare one-argument form strips | ||
| -- spaces only, letting a tab- or newline-prefixed address through. | ||
| -- | ||
| -- CAUTION: existing rows are normalised under whatever rules were in force when they | ||
| -- were written. Changing this function requires re-normalising admins in the same | ||
| -- migration, or previously-stored rows stop matching. | ||
| CREATE OR REPLACE FUNCTION normalize_email(addr TEXT) RETURNS TEXT | ||
| LANGUAGE sql IMMUTABLE STRICT AS | ||
| $$ SELECT LOWER(BTRIM(addr, E' \t\n\r\f\v')) $$; | ||
|
|
||
| CREATE TABLE IF NOT EXISTS "admins" ( | ||
| email TEXT PRIMARY KEY, | ||
| note TEXT, | ||
| created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), | ||
| -- Belt and braces. The trigger fires first and always satisfies this, so it never | ||
| -- rejects a human's insert; it is an assertion that normalisation actually ran | ||
| -- (it would catch, say, a session with triggers disabled) and documents the invariant. | ||
| CONSTRAINT admins_email_normalized CHECK (email = normalize_email(email)) | ||
| ); | ||
|
|
||
| -- Normalise on write rather than rejecting un-normalised input. Pasting | ||
| -- ' Ann@Example.COM ' stores 'ann@example.com' instead of erroring, while the primary | ||
| -- key still guarantees one row per address -- which is what makes revocation safe. Were | ||
| -- casing variants allowed to coexist as separate rows, DELETE of one would report | ||
| -- success and silently leave the other still granting admin. | ||
| CREATE OR REPLACE FUNCTION admins_normalize_email() RETURNS TRIGGER | ||
| LANGUAGE plpgsql AS | ||
| $$ | ||
| BEGIN | ||
| NEW.email := normalize_email(NEW.email); | ||
| RETURN NEW; | ||
| END; | ||
| $$; | ||
|
|
||
| CREATE TRIGGER admins_normalize_email_before_write | ||
| BEFORE INSERT OR UPDATE ON admins | ||
| FOR EACH ROW EXECUTE FUNCTION admins_normalize_email(); | ||
|
|
||
| -- Stored addresses are always canonical, so revocation must normalise its predicate too: | ||
| -- DELETE FROM admins WHERE email = normalize_email('Dana@Example.com'); | ||
| -- A bare `WHERE email = 'Dana@Example.com'` matches nothing and reports success. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| -- Local-only: makes one of the mock members from R__Mock_V0001 an admin so the | ||
| -- admin-gated routes can be exercised end to end without hand-inserting a row. | ||
| -- Never reaches staging or prod -- pom.xml pins Flyway to db/migration only. | ||
| INSERT INTO admins (email, note) | ||
| VALUES ('avery.chen@example.com', 'Local dev admin (mock member)') | ||
| ON CONFLICT (email) DO NOTHING; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import { RequireAdmin } from "@/app/router/guards/RequireAdmin"; | ||
| import { RequireAuth } from "@/app/router/guards/RequireAuth"; | ||
| import { | ||
| adminSession, | ||
| memberSession, | ||
| sessionResponse, | ||
| } from "@/features/auth/api/auth.mock"; | ||
| import { renderWithProviders, screen } from "@/lib/test/render"; | ||
| import { server } from "@/lib/test/server"; | ||
| import { http } from "msw"; | ||
| import { Route, Routes } from "react-router-dom"; | ||
| import { expect, test } from "vitest"; | ||
|
|
||
| /** | ||
| * Nested under RequireAuth exactly as the real route tree mounts it: RequireAdmin | ||
| * has no pending state of its own, relying on RequireAuth to hold rendering until | ||
| * the session query resolves. | ||
| */ | ||
| function renderGuarded() { | ||
| return renderWithProviders( | ||
| <Routes> | ||
| <Route element={<RequireAuth />}> | ||
| <Route element={<RequireAdmin />}> | ||
| <Route path="/admin" element={<div>admin page</div>} /> | ||
| </Route> | ||
| </Route> | ||
| <Route path="/" element={<div>home page</div>} /> | ||
| </Routes>, | ||
| { route: "/admin" }, | ||
| ); | ||
| } | ||
|
|
||
| test("a member who is not on the admin allowlist is sent home", async () => { | ||
| server.use(http.get("/api/session", () => sessionResponse(memberSession))); | ||
|
|
||
| renderGuarded(); | ||
|
|
||
| expect(await screen.findByText("home page")).toBeInTheDocument(); | ||
| }); | ||
|
|
||
| test("an admin sees the guarded page", async () => { | ||
| server.use(http.get("/api/session", () => sessionResponse(adminSession))); | ||
|
|
||
| renderGuarded(); | ||
|
|
||
| expect(await screen.findByText("admin page")).toBeInTheDocument(); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
src/main/java/org/patinanetwork/patchats/auth/repo/AdminRepo.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package org.patinanetwork.patchats.auth.repo; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.jdbc.core.simple.JdbcClient; | ||
| import org.springframework.stereotype.Repository; | ||
|
|
||
| /** | ||
| * Plain-SQL access to {@code admins}, the hand-maintained allowlist of administrator emails. There is deliberately no | ||
| * write path here: rows are inserted directly against the database, so this repository only ever asks the one question | ||
| * sign-in needs. | ||
| */ | ||
| @Repository | ||
| @RequiredArgsConstructor | ||
| public class AdminRepo { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if we're going to use the pattern of |
||
|
|
||
| private final JdbcClient jdbc; | ||
|
|
||
| /** | ||
| * Whether the address is on the admin allowlist. Accepts a raw address — member rows hold whatever sign-up was | ||
| * given, so the caller has no canonical form to offer. | ||
| * | ||
| * <p>Normalisation is deliberately left to the database's {@code normalize_email}, the same function the table's | ||
| * write trigger applies, rather than done here with {@code EmailNormalizer}. Two implementations of "canonical" | ||
| * would have to agree forever — and where they disagreed (Postgres {@code LOWER} and Java's | ||
| * {@code toLowerCase(Locale.ROOT)} part ways on some non-ASCII input) a correctly-listed admin would silently be | ||
| * granted nothing. One definition, used by both sides, cannot drift. | ||
| * | ||
| * <p>Wrapping the parameter rather than the column keeps the primary-key index usable: {@code normalize_email} is | ||
| * IMMUTABLE, so the planner folds it to a constant and does an index lookup. | ||
| */ | ||
| public boolean isAdmin(final String email) { | ||
| return Boolean.TRUE.equals(jdbc.sql("SELECT EXISTS(SELECT 1 FROM admins WHERE email = normalize_email(:email))") | ||
| .param("email", email) | ||
| .query(Boolean.class) | ||
| .single()); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we'll need a follow up item to add everyone to this table or else we won't be able to test out the admin endpoints. do you have access to the DB?
can you also add documentation on how to write to the DB (i.e. steps for authentication, the query, etc?) so people in the future know how to add themselves?