Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions db/migration/V0010__Create_admins_table.sql
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" (

Copy link
Copy Markdown

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?

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.
6 changes: 6 additions & 0 deletions db/repeated/R__Mock_V0002_Insert_test_admins.sql
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;
47 changes: 47 additions & 0 deletions js/src/app/router/guards/RequireAdmin.test.tsx
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();
});
6 changes: 6 additions & 0 deletions js/src/features/auth/api/auth.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ export const memberSession: Session = {
isAdmin: false,
};

/** Same member, but on the `admins` allowlist — exercises the admin-only routes. */
export const adminSession: Session = {
...memberSession,
isAdmin: true,
};

export const invalidLinkResponse = () =>
HttpResponse.json(
{
Expand Down
35 changes: 28 additions & 7 deletions src/main/java/org/patinanetwork/patchats/auth/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@
import org.patinanetwork.patchats.auth.dto.RequestLinkRequest;
import org.patinanetwork.patchats.auth.dto.SessionResponse;
import org.patinanetwork.patchats.auth.dto.VerifyRequest;
import org.patinanetwork.patchats.auth.repo.AdminRepo;
import org.patinanetwork.patchats.auth.security.AuthenticatedMember;
import org.patinanetwork.patchats.common.dto.ApiResponder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
Expand All @@ -43,8 +46,12 @@ public class AuthController {
/** Success copy for a link that was actually sent; an unregistered email fails with 404 instead. */
private static final String GENERIC_REQUEST_MESSAGE = "Check your email for a sign-in link.";

private static final GrantedAuthority MEMBER = new SimpleGrantedAuthority("ROLE_MEMBER");
private static final GrantedAuthority ADMIN = new SimpleGrantedAuthority("ROLE_ADMIN");

private final AuthService authService;
private final MemberRepo members;
private final AdminRepo admins;
private final SecurityContextRepository securityContextRepository;

@Operation(summary = "Email a single-use sign-in link")
Expand All @@ -62,8 +69,8 @@ public ResponseEntity<ApiResponder<SessionResponse>> verify(
final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse) {
final Member member = authService.verify(request.token());
login(member, httpRequest, httpResponse);
return ResponseEntity.ok(ApiResponder.success("Signed in.", SessionResponse.of(member)));
final boolean isAdmin = login(member, httpRequest, httpResponse);
return ResponseEntity.ok(ApiResponder.success("Signed in.", SessionResponse.of(member, isAdmin)));
}

/**
Expand All @@ -78,9 +85,13 @@ public ResponseEntity<ApiResponder<SessionResponse>> verify(
@Operation(summary = "The currently signed-in member")
@GetMapping("/session")
public ResponseEntity<ApiResponder<SessionResponse>> session(
@AuthenticationPrincipal final AuthenticatedMember principal, final HttpServletRequest httpRequest) {
@AuthenticationPrincipal final AuthenticatedMember principal,
final Authentication authentication,
final HttpServletRequest httpRequest) {
final boolean isAdmin = authentication.getAuthorities().contains(ADMIN);
return members.getMemberByEmail(principal.email())
.map(account -> ResponseEntity.ok(ApiResponder.success("Signed in.", SessionResponse.of(account))))
.map(account ->
ResponseEntity.ok(ApiResponder.success("Signed in.", SessionResponse.of(account, isAdmin))))
.orElseGet(() -> {
invalidateSession(httpRequest);
SecurityContextHolder.clearContext();
Expand All @@ -100,16 +111,26 @@ public ResponseEntity<ApiResponder<Void>> logout(final HttpServletRequest httpRe
* Programmatic login: store the authenticated principal in the {@link SecurityContextRepository}, which Spring
* Session persists and turns into the session cookie. {@code changeSessionId} rotates any pre-existing session so a
* client-supplied id can never survive into an authenticated session (fixation defense).
*
* <p>The {@code admins} allowlist is consulted exactly once, here, and the result is carried for the life of the
* session by the granted authorities (which Spring Session already serialises — nothing has to be added to
* {@link AuthenticatedMember}). Allowlist edits therefore take effect at the member's next sign-in; revoking an
* admin mid-session means deleting their {@code spring_session} rows as well.
*
* @return whether this session was granted {@code ROLE_ADMIN}
*/
private void login(final Member member, final HttpServletRequest request, final HttpServletResponse response) {
private boolean login(final Member member, final HttpServletRequest request, final HttpServletResponse response) {
if (request.getSession(false) != null) {
request.changeSessionId();
}
final boolean isAdmin = admins.isAdmin(member.getEmail());
final List<GrantedAuthority> authorities = isAdmin ? List.of(MEMBER, ADMIN) : List.of(MEMBER);
final SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(UsernamePasswordAuthenticationToken.authenticated(
AuthenticatedMember.of(member), null, List.of(new SimpleGrantedAuthority("ROLE_MEMBER"))));
context.setAuthentication(
UsernamePasswordAuthenticationToken.authenticated(AuthenticatedMember.of(member), null, authorities));
SecurityContextHolder.setContext(context);
securityContextRepository.saveContext(context, request, response);
return isAdmin;
}

private void invalidateSession(final HttpServletRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@

/**
* The signed-in member as seen by the frontend. Members always have a complete profile (the sign-up form is the only
* way one is created), so {@code name} is always present. {@code isAdmin} is always false until the admin domain lands.
* way one is created), so {@code name} is always present.
*
* <p>{@code isAdmin} is passed in rather than read off the member because the member row knows nothing about admin
* status — it comes from the {@code admins} allowlist, resolved once at sign-in and carried by the session's granted
* authorities. Callers must derive it from those authorities so the flag the SPA renders and the rule the backend
* enforces can never disagree.
*/
public record SessionResponse(String id, String name, String email, boolean isAdmin) {

public static SessionResponse of(final Member member) {
public static SessionResponse of(final Member member, final boolean isAdmin) {
final String name = "%s %s".formatted(member.getFirstName(), member.getLastName());
return new SessionResponse(member.getId().toString(), name, member.getEmail(), true);
return new SessionResponse(member.getId().toString(), name, member.getEmail(), isAdmin);
}
}
37 changes: 37 additions & 0 deletions src/main/java/org/patinanetwork/patchats/auth/repo/AdminRepo.java
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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we're going to use the pattern of Repo/SqlRepo for members/matches/etc, we should also do it here. for consistency purposes.


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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@ public SecurityContextRepository securityContextRepository() {
/**
* Default/production chain.
*
* <p>NOTE: the admin role is not yet assigned anywhere, so the email rule still fails closed — every caller is
* denied until an admin domain lands. Other endpoints keep their prior open posture.
* <p>{@code ROLE_ADMIN} is granted at magic-link sign-in to members whose email appears in the hand-maintained
* {@code admins} table (no API or UI writes to it). It is resolved once per sign-in and carried by the session's
* authorities, so allowlist edits take effect at the member's next login. Other endpoints keep their prior open
* posture.
*/
@Bean
@Profile("!dev")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.junit.jupiter.api.Test;
import org.patinanetwork.patchats.api.member.db.models.Member;
import org.patinanetwork.patchats.api.member.db.repos.MemberRepo;
import org.patinanetwork.patchats.auth.repo.AdminRepo;
import org.patinanetwork.patchats.common.web.ApiExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
Expand All @@ -38,6 +39,9 @@ class AuthControllerTest {
@MockitoBean
private MemberRepo members;

@MockitoBean
private AdminRepo admins;

@MockitoBean
private SecurityContextRepository securityContextRepository;

Expand Down Expand Up @@ -78,13 +82,8 @@ void requestLinkRejectsMalformedEmail() throws Exception {

@Test
void verifyReturnsSessionPayloadAndSavesContext() throws Exception {
final Member member = Member.builder()
.id(UUID.randomUUID())
.email("ann@example.com")
.firstName("Ann")
.lastName("Example")
.build();
when(authService.verify("raw-token")).thenReturn(member);
when(authService.verify("raw-token")).thenReturn(ann());
when(admins.isAdmin("ann@example.com")).thenReturn(false);

mockMvc.perform(post("/api/auth/verify")
.contentType(MediaType.APPLICATION_JSON)
Expand All @@ -93,11 +92,32 @@ void verifyReturnsSessionPayloadAndSavesContext() throws Exception {
.andExpect(jsonPath("$.success").value(true))
.andExpect(jsonPath("$.payload.email").value("ann@example.com"))
.andExpect(jsonPath("$.payload.name").value("Ann Example"))
.andExpect(jsonPath("$.payload.isAdmin").value(true));
.andExpect(jsonPath("$.payload.isAdmin").value(false));

verify(securityContextRepository).saveContext(any(), any(), any());
}

@Test
void verifyFlagsAnAllowlistedMemberAsAdmin() throws Exception {
when(authService.verify("raw-token")).thenReturn(ann());
when(admins.isAdmin("ann@example.com")).thenReturn(true);

mockMvc.perform(post("/api/auth/verify")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"token\":\"raw-token\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.payload.isAdmin").value(true));
}

private static Member ann() {
return Member.builder()
.id(UUID.randomUUID())
.email("ann@example.com")
.firstName("Ann")
.lastName("Example")
.build();
}

@Test
void verifyMapsInvalidTokenToBadRequestEnvelope() throws Exception {
when(authService.verify("spent")).thenThrow(new InvalidMagicLinkException());
Expand Down
Loading
Loading