diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index b80be4cf1..72c74f3cc 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -361,7 +361,9 @@ there was no history to recover — the same honest shape as the symbol index. with the platform because a bare `providerUserId` is not a person: the same id on two SCMs belongs to two unrelated humans. Admin-managed; inferring the link by matching usernames is refused, since a coincidental match shows one person another person's performance data with nothing on screen -looking wrong. +looking wrong. **V116** adds `author_handle` TEXT NULL: the login the forge reported when the operator +proved the account by signing in (never an email address), null for a link made by hand. Display +data only; `author_id` stays the key. `review_event` (flattened timeline for the dashboard): `id` BIGINT PK, `review_id`, `type`, `at`, `summary` — non-sensitive projection of the log for the UI (no payloads). diff --git a/docs/HISTORY.md b/docs/HISTORY.md index ace589132..73a620925 100644 --- a/docs/HISTORY.md +++ b/docs/HISTORY.md @@ -2515,3 +2515,16 @@ lives in `docs/`, the locked decisions in `docs/DECISIONS.md`, and claims no tes `fsGroup`, so on a root-owned volume (Longhorn, EBS, Ceph; kind's local-path volumes are world-writable) neither could write its data: both pods now set `fsGroup` with `fsGroupChangePolicy: OnRootMismatch`. render.sh `check_first_install` asserts both and its self-test breaks both. + +- **Operator names on the first install (2026-11-15, Part of #391).** Two People-tab defects from the first + production install. Nothing called `OperatorDirectory.seen`, so `operator_seen` stayed empty: Settings → Operators + said "Nobody has signed in yet" and a linked operator rendered as the raw OIDC subject twice. `/api/me` now records + the signed-in operator; the live socket's close handler asks it before every reconnect, so an identical sighting + within 60 s is skipped in memory and a changed name is written at once (a failure is logged and the probe still + answers). Email is never stored: on that realm `preferred_username` is the email address, so `OperatorNames` drops + any value with an `@` and the username is stored empty, the display name is the `name` claim, and a subject that is + itself an email is not recorded. Second, a linked SCM account showed its numeric id twice, because the only handle + came from authors observed in reviews. V116 adds `operator_identity.author_handle`: the connect callback stores the + login the forge reported (`Author.username`, never the email, dropped if it looks like one), the identity list + returns it, and the People table and the My activity chips show it with the id as fallback; a link made by hand + keeps null, and a hand relink of the same account keeps the observed login. A name equal to its id is shown once. diff --git a/docs/UNVERIFIED.md b/docs/UNVERIFIED.md index a952e89d2..f6d26dfa3 100644 --- a/docs/UNVERIFIED.md +++ b/docs/UNVERIFIED.md @@ -1209,6 +1209,7 @@ Each has a runbook mode. None has been run by an operator. | **GitHub review fallbacks and the dismissal** (ADR-047, 2026-10-15) | none yet | WireMock and fakes prove the self-authored refusal (422 "own pull request" → posted again as Comment), the rejected anchor (body only, then inline one by one, then a body update), the dismissal of the bot's own standing Request changes when the setting is off, the crash window between a review post and its idempotency mark (the review is found again by head and header), and the reviewer request refused for a non-collaborator. The dismissal met GitHub on 2026-10-18: on `spire-test` PR 55 a re-run with the setting off posted Comment review 5563717456 and dismissed the bot's own Request changes 5554693017 with a message naming the new review (`factory/GITHUB-REVIEWS-ACCEPTANCE.md`); the look-first on a redelivery is proven by the same re-runs. The rest has not. Evidence needed: a PR opened by the reviewer account; a finding whose anchor GitHub rejects; a worker killed between the post and the mark; a reviewer login that is not a collaborator. Whether a dismissal needs write access is API knowledge, not measured. GitLab and Bitbucket native reviews are absent by design. A legacy summary issue comment posted before this slice stays on the PR unchanged beside the new review; nothing edits it (M-10) | | **The factory land gate at Block approval at Major or Minor** (PR #420, 2026-11-14) | none yet | `WorkReview` tests prove a MAJOR-only review holds land at Major and completes at Blocker. The verdict at both levels is live on `spire-test` #106; no factory item has landed, or been held, at a level other than Blocker. | | **OIDC sessions actually renew instead of re-authenticating** | **Mode J check 11** (2026-09-10) | The bug it fixes needs a real browser, a real Keycloak and **fifteen elapsed minutes**. No suite here has any of the three: there are zero WebSocket client tests, and nothing observes a token reaching its `exp`. `OidcSessionsAreRenewedTest` asserts the four `application.yml` files *say* renewal is on — it cannot assert Quarkus *does* it | +| **Operator names on a live realm** (2026-11-15) | none yet | `/api/me` recording the operator and dropping an email `preferred_username` is proven by a unit test with a hand-built JWT and a `@TestSecurity` test that has no JWT; no real Keycloak token has been through it. The connect callback storing the forge login is proven against a fake `OperatorOAuth`, not a real GitHub sign-in | **Evidence needed.** An operator pass per mode. These are cheap and the runbooks are written. diff --git a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/analytics/OperatorIdentities.java b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/analytics/OperatorIdentities.java index b985afa29..58a825a4b 100644 --- a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/analytics/OperatorIdentities.java +++ b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/analytics/OperatorIdentities.java @@ -38,8 +38,12 @@ public class OperatorIdentities { *

{@code providerType} is not decoration: a bare {@code providerUserId} is not a person. The * same numeric id on GitHub and GitLab belongs to two unrelated humans, and this project has * already been bitten twice by treating a workspace name as unique across platforms. + * + *

{@code authorHandle} is the login the forge reported when the operator proved the account by + * signing in (V116), or null for a link an admin made by hand. Display data only: nothing keys on + * it, and it is never an email address. */ - public record Link(String oidcSubject, String providerType, String authorId) { + public record Link(String oidcSubject, String providerType, String authorId, String authorHandle) { } @Inject @@ -50,11 +54,11 @@ public List all() { List links = new ArrayList<>(); try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement( - "SELECT oidc_subject, provider_type, author_id FROM operator_identity" + "SELECT oidc_subject, provider_type, author_id, author_handle FROM operator_identity" + " ORDER BY oidc_subject, provider_type"); ResultSet rs = ps.executeQuery()) { while (rs.next()) { - links.add(new Link(rs.getString(1), rs.getString(2), rs.getString(3))); + links.add(new Link(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } } catch (SQLException e) { throw new IllegalStateException("could not read operator identities", e); @@ -70,12 +74,12 @@ public List forSubject(String oidcSubject) { List links = new ArrayList<>(); try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement( - "SELECT oidc_subject, provider_type, author_id FROM operator_identity" + "SELECT oidc_subject, provider_type, author_id, author_handle FROM operator_identity" + " WHERE oidc_subject = ? ORDER BY provider_type")) { ps.setString(1, oidcSubject); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { - links.add(new Link(rs.getString(1), rs.getString(2), rs.getString(3))); + links.add(new Link(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4))); } } } catch (SQLException e) { @@ -122,17 +126,28 @@ public Optional firstFor(String oidcSubject) { return forSubject(oidcSubject).stream().findFirst(); } + /** + * Writes the link. + * + *

A relink to the SAME account with no handle (an admin repairing it by hand) keeps the handle a + * sign-in observed; a link to a different account takes the new handle, null included, because the + * old login names somebody else's account. + */ public void link(Link link) { String sql = """ - INSERT INTO operator_identity (oidc_subject, provider_type, author_id) - VALUES (?, ?, ?) + INSERT INTO operator_identity (oidc_subject, provider_type, author_id, author_handle) + VALUES (?, ?, ?, ?) ON CONFLICT (oidc_subject, provider_type) - DO UPDATE SET author_id = EXCLUDED.author_id + DO UPDATE SET author_id = EXCLUDED.author_id, + author_handle = CASE WHEN operator_identity.author_id = EXCLUDED.author_id + THEN COALESCE(EXCLUDED.author_handle, operator_identity.author_handle) + ELSE EXCLUDED.author_handle END """; try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) { ps.setString(1, link.oidcSubject()); ps.setString(2, link.providerType()); ps.setString(3, link.authorId()); + ps.setString(4, link.authorHandle()); ps.executeUpdate(); } catch (SQLException e) { throw new IllegalStateException("could not link the operator identity", e); diff --git a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/analytics/OperatorIdentityResource.java b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/analytics/OperatorIdentityResource.java index 2c6ddaa4f..3fc7212fd 100644 --- a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/analytics/OperatorIdentityResource.java +++ b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/analytics/OperatorIdentityResource.java @@ -85,7 +85,7 @@ public Response link(LinkRequest request) { return Response.status(Response.Status.BAD_REQUEST).entity(rejection).build(); } identities.link(new OperatorIdentities.Link(request.oidcSubject().trim(), - request.providerType().trim(), request.authorId().trim())); + request.providerType().trim(), request.authorId().trim(), null)); return Response.noContent().build(); } diff --git a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/operator/OperatorConnectResource.java b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/operator/OperatorConnectResource.java index 28d36b479..f75d3516d 100644 --- a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/operator/OperatorConnectResource.java +++ b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/operator/OperatorConnectResource.java @@ -6,6 +6,7 @@ import dev.codespire.contract.scm.OAuthApp; import dev.codespire.orchestrator.analytics.OperatorIdentities; import dev.codespire.orchestrator.security.OidcSubjects; +import dev.codespire.orchestrator.security.OperatorNames; import io.quarkus.security.identity.SecurityIdentity; import jakarta.annotation.security.RolesAllowed; import jakarta.inject.Inject; @@ -191,10 +192,22 @@ public Response callback(@PathParam("type") String type, return back("noaccount"); } - identities.link(new OperatorIdentities.Link(attempt.oidcSubject(), type, author.providerUserId())); + identities.link(linkOf(attempt, type, author)); return back("connected"); } + /** + * The proved link, with the login the forge just reported kept beside the id so the dashboard can + * show {@code artyomsv} rather than {@code 3218389}. The login is display data only, never a key. + * Only {@code username}: the author's email is never stored, and a login that looks like an email + * is dropped too (null, as for a link made by hand). + */ + static OperatorIdentities.Link linkOf(ConnectStates.Pending attempt, String type, Author author) { + String handle = OperatorNames.withoutEmail(author.username()); + return new OperatorIdentities.Link(attempt.oidcSubject(), type, author.providerUserId(), + handle.isEmpty() ? null : handle); + } + /** * This deployment's own callback address, as the browser reached it. * diff --git a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/AuthResource.java b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/AuthResource.java index 1688ca91f..b0a222c04 100644 --- a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/AuthResource.java +++ b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/AuthResource.java @@ -28,9 +28,17 @@ @Produces(MediaType.APPLICATION_JSON) public class AuthResource { + private static final org.jboss.logging.Logger LOG = org.jboss.logging.Logger.getLogger(AuthResource.class); + @Inject SecurityIdentity identity; + @Inject + OperatorDirectory directory; + + @Inject + RecentOperatorSightings sightings; + @ConfigProperty(name = "spire.security.auth-enabled", defaultValue = "true") boolean authEnabled; @@ -57,6 +65,9 @@ public record Me(boolean authEnabled, boolean authenticated, String user, ListOn the session probe because every dashboard load asks it, which is exactly "who has been + * here". The live socket's close handler ({@code useLiveSocket}) asks it too, before every + * reconnect, so {@link RecentOperatorSightings} skips an identical sighting within 60 s: a + * flapping socket must not become a write stream, while a changed name is written at once. Names + * go through {@link OperatorNames}, which drops every email address: on a realm whose login is + * the email, the username is stored empty and the {@code name} claim is shown. A subject that is + * itself an email (no JWT, a principal named by email) is not recorded at all. * - *

Falls back to the principal name rather than to blank: the picker exists so a person can be - * recognised, and a row showing only an opaque subject would send an admin back to the database - * this whole change removes. + *

{@link OperatorDirectory#seen} never throws by design; the catch keeps that promise here too, + * because a dashboard that cannot load its session over a display table is the worse outcome. */ - private static String displayName(SecurityIdentity identity) { - if (identity.getPrincipal() instanceof org.eclipse.microprofile.jwt.JsonWebToken jwt) { - Object name = jwt.getClaim("name"); - if (name instanceof String text && !text.isBlank()) { - return text; - } + private void recordSignedIn() { + String subject = OidcSubjects.of(identity); + if (OperatorNames.withoutEmail(subject).isEmpty()) { + return; + } + String username = OperatorNames.username(identity); + String displayName = OperatorNames.displayName(identity); + if (!sightings.isNew(subject, username, displayName)) { + return; + } + try { + directory.seen(subject, username, displayName); + sightings.remember(subject, username, displayName); + } catch (RuntimeException e) { + LOG.warn("could not record the signed-in operator", e); } - return identity.getPrincipal().getName(); } /** Only this application's own roles; an operator's other realm roles are not our business. */ diff --git a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/OperatorNames.java b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/OperatorNames.java new file mode 100644 index 000000000..2a0b4bfb4 --- /dev/null +++ b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/OperatorNames.java @@ -0,0 +1,55 @@ +package dev.codespire.orchestrator.security; + +import io.quarkus.security.identity.SecurityIdentity; +import org.eclipse.microprofile.jwt.JsonWebToken; + +/** + * The names a signed-in operator is shown by, with every email address taken out. + * + *

Email is never persisted (CLAUDE.md), and an identity provider does not promise that its name + * claims are not emails: on the first production realm {@code preferred_username} IS the email + * address, and the principal name follows it. So any value with an {@code @} is dropped, and the + * caller gets an empty string instead. The dashboard then shows the display name, or the subject. + */ +public final class OperatorNames { + + private static final String NAME_CLAIM = "name"; + private static final String USERNAME_CLAIM = "preferred_username"; + + private OperatorNames() { + } + + /** The login, or empty when the provider's login is an email address or there is none. */ + public static String username(SecurityIdentity identity) { + if (identity == null || identity.isAnonymous()) { + return ""; + } + String claimed = claim(identity, USERNAME_CLAIM); + return withoutEmail(claimed.isEmpty() ? identity.getPrincipal().getName() : claimed); + } + + /** The {@code name} claim, else the login, else empty. Never an email address. */ + public static String displayName(SecurityIdentity identity) { + if (identity == null || identity.isAnonymous()) { + return ""; + } + String name = withoutEmail(claim(identity, NAME_CLAIM)); + return name.isEmpty() ? username(identity) : name; + } + + /** {@code value} trimmed, or empty when it is blank or looks like an email address. */ + public static String withoutEmail(String value) { + if (value == null || value.isBlank() || value.contains("@")) { + return ""; + } + return value.trim(); + } + + private static String claim(SecurityIdentity identity, String claimName) { + if (identity.getPrincipal() instanceof JsonWebToken jwt + && jwt.getClaim(claimName) instanceof String text) { + return text.trim(); + } + return ""; + } +} diff --git a/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/RecentOperatorSightings.java b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/RecentOperatorSightings.java new file mode 100644 index 000000000..d6c73e591 --- /dev/null +++ b/spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/RecentOperatorSightings.java @@ -0,0 +1,45 @@ +package dev.codespire.orchestrator.security; + +import jakarta.enterprise.context.ApplicationScoped; + +import java.time.Duration; +import java.time.Instant; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** + * Which operators this process recorded a moment ago, so {@code /api/me} does not write the same row + * again. + * + *

The session probe is not only asked once per dashboard load: the live socket's close handler + * ({@code useLiveSocket}) asks it on every close before it reconnects, so a flapping socket would turn + * {@code operator_seen} into a write stream. An identical sighting within {@link #WINDOW} is skipped; + * a changed username or display name is written at once. Per process and in memory: a second + * instance or a restart writes once more, which is harmless. + */ +@ApplicationScoped +public class RecentOperatorSightings { + + static final Duration WINDOW = Duration.ofSeconds(60); + + private record Sighting(String username, String displayName, Instant at) { + } + + private final Map recent = new ConcurrentHashMap<>(); + + Supplier clock = Instant::now; + + /** Whether this sighting differs from the last one recorded, or that one is older than the window. */ + public boolean isNew(String subject, String username, String displayName) { + Sighting last = recent.get(subject); + return last == null + || !last.username().equals(username) + || !last.displayName().equals(displayName) + || last.at().plus(WINDOW).isBefore(clock.get()); + } + + public void remember(String subject, String username, String displayName) { + recent.put(subject, new Sighting(username, displayName, clock.get())); + } +} diff --git a/spire-orchestrator/src/main/resources/db/migration/V116__operator_identity_author_handle.sql b/spire-orchestrator/src/main/resources/db/migration/V116__operator_identity_author_handle.sql new file mode 100644 index 000000000..0a07e4a5c --- /dev/null +++ b/spire-orchestrator/src/main/resources/db/migration/V116__operator_identity_author_handle.sql @@ -0,0 +1,10 @@ +-- The SCM login an operator proved by signing in, shown beside the stable id (FR-11). +-- +-- A fresh install showed a linked account as its numeric id twice ("3218389 / 3218389"): the only +-- handle the dashboard knew came from authors observed in reviews, and there were none yet. The connect +-- callback has just been told the login by the forge itself, so it is kept with the link. +-- +-- Display data only, never a key: author_id stays the identity. NULL for a link an admin made by hand +-- (no login was observed); the dashboard then falls back to the observed authors, then to the id. +-- Never an email address: the callback refuses to store one. +ALTER TABLE operator_identity ADD COLUMN author_handle TEXT; diff --git a/spire-orchestrator/src/test/java/dev/codespire/orchestrator/operator/OperatorConnectHandleTest.java b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/operator/OperatorConnectHandleTest.java new file mode 100644 index 000000000..a5f4676d1 --- /dev/null +++ b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/operator/OperatorConnectHandleTest.java @@ -0,0 +1,143 @@ +package dev.codespire.orchestrator.operator; + +import dev.codespire.contract.port.OperatorOAuth; +import dev.codespire.contract.port.ScmType; +import dev.codespire.contract.scm.Author; +import dev.codespire.contract.scm.OAuthApp; +import dev.codespire.orchestrator.analytics.OperatorIdentities; +import io.quarkus.test.junit.QuarkusMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.security.TestSecurity; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; +import java.util.Optional; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * The SCM login a finished sign-in keeps beside the proved id (V116). + * + *

Found on the first production install: a linked account read {@code 3218389} over {@code 3218389}, + * because the only handle came from authors observed in reviews. The id stays the key; the login is + * display data. The forge is a fake {@link OperatorOAuth}, so no test reaches the internet. Same fixture + * as {@link OperatorConnectResourceTest}. + */ +@QuarkusTest +class OperatorConnectHandleTest { + + private static final String ALICE = "TEST-SUBJECT-ALICE"; + + @Inject + ScmOAuthApps apps; + + @Inject + ConnectStates states; + + @Inject + OperatorIdentities identities; + + @Inject + DataSource dataSource; + + @BeforeEach + void clean() { + exec("DELETE FROM scm_oauth_app WHERE provider_type = 'github'"); + exec("DELETE FROM oauth_connect_state WHERE oidc_subject LIKE 'TEST-SUBJECT-%'"); + exec("DELETE FROM operator_identity WHERE oidc_subject LIKE 'TEST-SUBJECT-%' OR oidc_subject = ''"); + } + + @Test + @TestSecurity(user = ALICE, roles = "spire-viewer") + void aFinishedSignInStoresTheObservedLoginBesideTheId() { + connectAs(Author.of("TEST-900001", "TEST-alice-login", "TEST Alice")); + + assertEquals(List.of(new OperatorIdentities.Link(ALICE, "github", "TEST-900001", "TEST-alice-login")), + identities.forSubject(ALICE)); + } + + /** A login that is an email address is not stored, nor is the author's email: the handle stays empty. */ + @Test + @TestSecurity(user = ALICE, roles = "spire-viewer") + void aLoginThatIsAnEmailIsNotStored() { + connectAs(new Author("TEST-900002", "test-alice@example.invalid", "TEST Alice", "test-alice@example.invalid")); + + assertEquals(List.of(new OperatorIdentities.Link(ALICE, "github", "TEST-900002", null)), + identities.forSubject(ALICE)); + } + + /** An admin's repair of the same account by hand keeps the observed login; a different account drops it. */ + @Test + void aManualRelinkKeepsTheLoginOnlyForTheSameAccount() { + identities.link(new OperatorIdentities.Link(ALICE, "github", "TEST-900001", "TEST-alice-login")); + + identities.link(new OperatorIdentities.Link(ALICE, "github", "TEST-900001", null)); + assertEquals("TEST-alice-login", identities.forSubject(ALICE).getFirst().authorHandle()); + + identities.link(new OperatorIdentities.Link(ALICE, "github", "TEST-900003", null)); + assertNull(identities.forSubject(ALICE).getFirst().authorHandle()); + } + + @Test + @TestSecurity(user = "TEST-SUBJECT-ADMIN", roles = {"spire-viewer", "spire-admin"}) + void theAdminListReturnsTheObservedLogin() { + identities.link(new OperatorIdentities.Link(ALICE, "github", "TEST-900001", "TEST-alice-login")); + + given().when().get("/api/operator-identities") + .then().statusCode(200) + .body("find { it.oidcSubject == '" + ALICE + "' }.authorHandle", is("TEST-alice-login")); + } + + /** Runs a whole connect for ALICE against a forge that answers with {@code author}. */ + private void connectAs(Author author) { + apps.save(new ScmOAuthApps.Input("github", null, null, "TEST-CLIENT", "TEST-SECRET")); + QuarkusMock.installMockForType(new OperatorConnects() { + @Override + public Optional forType(ScmType type) { + return Optional.of(forgeAnswering(author)); + } + }, OperatorConnects.class); + String mine = states.start(ALICE, "github", "https://spire.example.invalid/cb"); + + given().redirects().follow(false) + .when().get("/api/operator-connect/github/callback?code=TEST-CODE&state=" + mine) + .then().statusCode(303).header("Location", containsString("connect=connected")); + } + + private static OperatorOAuth forgeAnswering(Author author) { + return new OperatorOAuth() { + @Override + public ScmType type() { + return ScmType.GITHUB; + } + + @Override + public String authorizeUrl(OAuthApp app, String state, String redirectUri) { + return "https://forge.example.invalid/authorize"; + } + + @Override + public Author identify(OAuthApp app, String code, String redirectUri) { + return author; + } + }; + } + + private void exec(String sql) { + try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) { + ps.executeUpdate(); + } catch (SQLException e) { + throw new IllegalStateException("setup failed: " + sql, e); + } + } +} diff --git a/spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceOperatorSeenTest.java b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceOperatorSeenTest.java new file mode 100644 index 000000000..85f0bd914 --- /dev/null +++ b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceOperatorSeenTest.java @@ -0,0 +1,76 @@ +package dev.codespire.orchestrator.security; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.security.TestSecurity; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The session probe writes the operator directory through the real bean and the real table, and the + * admin picker reads the row back. The claim handling is in {@link AuthResourceRecordsOperatorTest}; + * {@code @TestSecurity} yields no JWT, so the subject and the login are both the principal name here. + */ +@QuarkusTest +class AuthResourceOperatorSeenTest { + + private static final String OPERATOR = "TEST-SUBJECT-SEEN-OPERATOR"; + + @Inject + DataSource dataSource; + + @BeforeEach + void clean() { + try (Connection c = dataSource.getConnection(); + PreparedStatement ps = c.prepareStatement("DELETE FROM operator_seen WHERE oidc_subject LIKE 'TEST-SUBJECT-SEEN-%'")) { + ps.executeUpdate(); + } catch (SQLException e) { + throw new IllegalStateException("could not clean operator_seen", e); + } + } + + @Test + @TestSecurity(user = OPERATOR, roles = "spire-viewer") + void aSignedInSessionProbeRecordsTheOperator() { + given().when().get("/api/me").then().statusCode(200).body("subject", is(OPERATOR)); + + assertEquals(List.of(List.of(OPERATOR, OPERATOR, OPERATOR)), seenRows()); + } + + @Test + @TestSecurity(user = "TEST-SUBJECT-SEEN-ADMIN", roles = {"spire-viewer", "spire-admin"}) + void theAdminPickerListsAnOperatorOnceTheyHaveSignedIn() { + given().when().get("/api/me").then().statusCode(200); + + given().when().get("/api/operator-identities/operators") + .then().statusCode(200) + .body("find { it.subject == 'TEST-SUBJECT-SEEN-ADMIN' }.username", is("TEST-SUBJECT-SEEN-ADMIN")); + } + + private List> seenRows() { + List> rows = new ArrayList<>(); + try (Connection c = dataSource.getConnection(); + PreparedStatement ps = c.prepareStatement( + "SELECT oidc_subject, username, display_name FROM operator_seen WHERE oidc_subject LIKE 'TEST-SUBJECT-SEEN-%'"); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + rows.add(List.of(rs.getString(1), rs.getString(2), rs.getString(3))); + } + } catch (SQLException e) { + throw new IllegalStateException("could not read operator_seen", e); + } + return rows; + } +} diff --git a/spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceRecordsOperatorTest.java b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceRecordsOperatorTest.java new file mode 100644 index 000000000..5a1c58b94 --- /dev/null +++ b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceRecordsOperatorTest.java @@ -0,0 +1,185 @@ +package dev.codespire.orchestrator.security; + +import dev.codespire.orchestrator.operator.OperatorDirectory; +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.runtime.QuarkusSecurityIdentity; +import org.eclipse.microprofile.jwt.Claims; +import org.eclipse.microprofile.jwt.JsonWebToken; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@code /api/me} records the signed-in operator, and never their email address. + * + *

Found on the first production install: nothing called {@link OperatorDirectory#seen}, so + * Settings → Operators said "Nobody has signed in yet" to an operator who had. A plain unit test + * because the JWT branch never runs under {@code @TestSecurity} (see {@link OidcSubjectsTest}), and + * the email case lives only there: on that realm {@code preferred_username} is the email address. + */ +class AuthResourceRecordsOperatorTest { + + private static final String SUBJECT = "TEST-SUBJECT-0001"; + + @Test + void recordsTheNameAndAnEmptyUsernameWhenTheLoginIsAnEmail() { + RecordingDirectory directory = new RecordingDirectory(); + + resource(directory, identityOf(jwt(Map.of( + Claims.sub.name(), SUBJECT, + "preferred_username", "test-operator@example.invalid", + "name", "TEST Operator"), "test-operator@example.invalid"))).me(); + + assertEquals(List.of(List.of(SUBJECT, "", "TEST Operator")), directory.seen); + } + + @Test + void recordsAPlainLoginAsTheUsername() { + RecordingDirectory directory = new RecordingDirectory(); + + resource(directory, identityOf(jwt(Map.of( + Claims.sub.name(), SUBJECT, + "preferred_username", "test-operator", + "name", "TEST Operator"), "test-operator"))).me(); + + assertEquals(List.of(List.of(SUBJECT, "test-operator", "TEST Operator")), directory.seen); + } + + /** No {@code name} claim and an email login: nothing is left to show but the subject. */ + @Test + void neverFallsBackToAnEmailForTheDisplayName() { + RecordingDirectory directory = new RecordingDirectory(); + + resource(directory, identityOf(jwt(Map.of( + Claims.sub.name(), SUBJECT, + "preferred_username", "test-operator@example.invalid"), "test-operator@example.invalid"))).me(); + + assertEquals(List.of(List.of(SUBJECT, "", "")), directory.seen); + } + + /** No JWT and a principal named by email: the subject itself would be the email, so nothing is written. */ + @Test + void recordsNothingWhenTheSubjectIsAnEmail() { + RecordingDirectory directory = new RecordingDirectory(); + + resource(directory, QuarkusSecurityIdentity.builder() + .setPrincipal(new io.quarkus.security.runtime.QuarkusPrincipal("test-operator@example.invalid")) + .build()).me(); + + assertTrue(directory.seen.isEmpty()); + } + + @Test + void recordsNothingForAnAnonymousCaller() { + RecordingDirectory directory = new RecordingDirectory(); + + resource(directory, QuarkusSecurityIdentity.builder().setAnonymous(true).build()).me(); + + assertTrue(directory.seen.isEmpty()); + } + + /** {@code seen} never throws by design, and the session probe must answer even if it did. */ + @Test + void stillAnswersWhenRecordingFails() { + OperatorDirectory failing = new OperatorDirectory() { + @Override + public void seen(String subject, String username, String displayName) { + throw new IllegalStateException("TEST failure"); + } + }; + + AuthResource.Me me = resource(failing, identityOf(jwt(Map.of(Claims.sub.name(), SUBJECT), "test-operator"))).me(); + + assertEquals(SUBJECT, me.subject()); + } + + /** The live socket's close handler asks {@code /api/me} before every reconnect; the same sighting is written once. */ + @Test + void anIdenticalProbeWithinTheWindowWritesNothing() { + RecordingDirectory directory = new RecordingDirectory(); + RecentOperatorSightings sightings = new RecentOperatorSightings(); + Instant[] now = {Instant.parse("1970-01-01T00:00:00Z")}; + sightings.clock = () -> now[0]; + SecurityIdentity identity = identityOf(jwt(Map.of(Claims.sub.name(), SUBJECT, "name", "TEST Operator"), "test-operator")); + + resource(directory, identity, sightings).me(); + now[0] = now[0].plusSeconds(59); + resource(directory, identity, sightings).me(); + assertEquals(1, directory.seen.size()); + + now[0] = now[0].plusSeconds(2); + resource(directory, identity, sightings).me(); + assertEquals(2, directory.seen.size(), "past the window the sighting is written again"); + } + + @Test + void aChangedDisplayNameIsWrittenAtOnce() { + RecordingDirectory directory = new RecordingDirectory(); + RecentOperatorSightings sightings = new RecentOperatorSightings(); + sightings.clock = () -> Instant.parse("1970-01-01T00:00:00Z"); + + resource(directory, identityOf(jwt(Map.of(Claims.sub.name(), SUBJECT, "name", "TEST Operator"), "test-operator")), + sightings).me(); + resource(directory, identityOf(jwt(Map.of(Claims.sub.name(), SUBJECT, "name", "TEST Operator Renamed"), "test-operator")), + sightings).me(); + + assertEquals(List.of( + List.of(SUBJECT, "test-operator", "TEST Operator"), + List.of(SUBJECT, "test-operator", "TEST Operator Renamed")), directory.seen); + } + + private static AuthResource resource(OperatorDirectory directory, SecurityIdentity identity) { + return resource(directory, identity, new RecentOperatorSightings()); + } + + private static AuthResource resource(OperatorDirectory directory, SecurityIdentity identity, + RecentOperatorSightings sightings) { + AuthResource resource = new AuthResource(); + resource.directory = directory; + resource.sightings = sightings; + resource.identity = identity; + resource.authEnabled = true; + return resource; + } + + private static SecurityIdentity identityOf(JsonWebToken jwt) { + return QuarkusSecurityIdentity.builder().setPrincipal(jwt).build(); + } + + /** Overrides the one method {@code me} reaches, so no database is opened (CLAUDE.md, saga fakes). */ + private static final class RecordingDirectory extends OperatorDirectory { + final List> seen = new ArrayList<>(); + + @Override + public void seen(String subject, String username, String displayName) { + seen.add(List.of(subject, username, displayName)); + } + } + + private static JsonWebToken jwt(Map claims, String principalName) { + return new JsonWebToken() { + @Override + public String getName() { + return principalName; + } + + @Override + public Set getClaimNames() { + return claims.keySet(); + } + + @Override + @SuppressWarnings("unchecked") + public T getClaim(String claimName) { + return (T) claims.get(claimName); + } + }; + } +} diff --git a/spire-ui/src/api.ts b/spire-ui/src/api.ts index d6dbfe2a9..052a9ef00 100644 --- a/spire-ui/src/api.ts +++ b/spire-ui/src/api.ts @@ -1615,6 +1615,12 @@ export interface OperatorIdentityLink { oidcSubject: string; providerType: string; authorId: string; + /** + * The login the forge reported when the operator signed in to prove the account (V116). Null for + * a link an admin made by hand. Shown, never keyed on; the server never sends an email here. + * Optional because a link the dashboard sends has none. + */ + authorHandle?: string | null; } export const analyticsOverviewKey = ['analytics', 'overview'] as const; diff --git a/spire-ui/src/components/Analytics.test.tsx b/spire-ui/src/components/Analytics.test.tsx index be5e8134f..47681cb11 100644 --- a/spire-ui/src/components/Analytics.test.tsx +++ b/spire-ui/src/components/Analytics.test.tsx @@ -92,6 +92,26 @@ describe('MyAnalytics', () => { expect(screen.getByText('NAMING')).toBeInTheDocument(); }); + /** The account chip names the login a sign-in observed, and the id only when there is none. */ + it('shows the observed login on the account chip, with the id as the fallback', async () => { + vi.spyOn(api, 'fetchMyActivity').mockResolvedValue({ + linked: true, + identities: [ + { oidcSubject: 'TEST-SUBJECT-1', providerType: 'github', authorId: '900001', authorHandle: 'TEST-login' }, + { oidcSubject: 'TEST-SUBJECT-1', providerType: 'gitlab', authorId: '900002', authorHandle: null }, + ], + totals: { ...EMPTY_TOTALS }, + breakdown: [], + }); + vi.spyOn(api, 'fetchConnectablePlatforms').mockResolvedValue([]); + + renderWithQuery(); + + expect(await screen.findByText('github · TEST-login')).toBeInTheDocument(); + expect(screen.getByText('gitlab · 900002')).toBeInTheDocument(); + expect(screen.queryByText(/900001/)).toBeNull(); + }); + /** An error must not read as "no activity" either — three states, three sentences. */ it('reports a failed load as an error rather than as no activity', async () => { vi.spyOn(api, 'fetchMyActivity').mockRejectedValue(new Error('TEST-BOOM')); diff --git a/spire-ui/src/components/Analytics.tsx b/spire-ui/src/components/Analytics.tsx index 6ebde87e1..a6a6275fd 100644 --- a/spire-ui/src/components/Analytics.tsx +++ b/spire-ui/src/components/Analytics.tsx @@ -320,7 +320,7 @@ function MyActivityBody({ state, subject }: { state: LoadState; subj

{state.value.identities.map((id) => ( - {id.providerType} · {id.authorId} + {id.providerType} · {id.authorHandle || id.authorId} ))}
diff --git a/spire-ui/src/components/NameWithId.tsx b/spire-ui/src/components/NameWithId.tsx new file mode 100644 index 000000000..c9f010fd0 --- /dev/null +++ b/spire-ui/src/components/NameWithId.tsx @@ -0,0 +1,17 @@ +/** + * A name with its id beneath, and the id once when there is no name: a row reading `3218389` over + * `3218389` (first production install) says nothing twice. + */ +interface NameWithIdProps { + name: string; + id: string; +} + +export function NameWithId({ name, id }: NameWithIdProps) { + return ( + <> + {name} + {name !== id &&
{id}
} + + ); +} diff --git a/spire-ui/src/components/SettingsOperators.test.tsx b/spire-ui/src/components/SettingsOperators.test.tsx index 79e1b18ad..91a697f9a 100644 --- a/spire-ui/src/components/SettingsOperators.test.tsx +++ b/spire-ui/src/components/SettingsOperators.test.tsx @@ -132,6 +132,58 @@ describe('SettingsOperators', () => { await waitFor(() => expect(screen.getAllByText('TEST-SUBJECT-1').length).toBe(2)); }); + /** First production install: the account read `3218389` over `3218389` with no review yet. */ + it('shows the login a sign-in observed, with the id beneath', async () => { + vi.spyOn(api, 'fetchOperatorCandidates').mockResolvedValue([]); + vi.spyOn(api, 'fetchOperatorIdentities').mockResolvedValue([ + { oidcSubject: 'TEST-SUBJECT-1', providerType: 'github', authorId: '900001', authorHandle: 'TEST-login' }, + ]); + + render(, { wrapper: queryWrapper() }); + + const row = (await screen.findByText('TEST-login')).closest('tr') as HTMLElement; + expect(within(row).getByText('900001')).toBeTruthy(); + }); + + /** A link made by hand has no observed login and no review names it: the id once, not twice. */ + it('shows the id once when nothing names the account', async () => { + vi.spyOn(api, 'fetchOperatorCandidates').mockResolvedValue([]); + vi.spyOn(api, 'fetchOperatorIdentities').mockResolvedValue([ + { oidcSubject: 'TEST-SUBJECT-1', providerType: 'github', authorId: '900001', authorHandle: null }, + ]); + + render(, { wrapper: queryWrapper() }); + + await waitFor(() => expect(screen.getAllByText('900001').length).toBe(1)); + }); + + /** An operator whose login was an email has an empty username: the name alone, no trailing separator. */ + it('names an operator with no username by their display name', async () => { + vi.spyOn(api, 'fetchSeenOperators').mockResolvedValue([ + { subject: 'TEST-SUBJECT-7', username: '', displayName: 'TEST Operator Seven' }, + ]); + vi.spyOn(api, 'fetchOperatorIdentities').mockResolvedValue([ + { oidcSubject: 'TEST-SUBJECT-7', providerType: 'github', authorId: '3218389' }, + ]); + + render(, { wrapper: queryWrapper() }); + + const row = (await screen.findByText('TEST-SUBJECT-7')).closest('tr') as HTMLElement; + expect(within(row).getByText('TEST Operator Seven')).toBeTruthy(); + expect(screen.getByRole('option', { name: 'TEST Operator Seven' })).toBeTruthy(); + }); + + /** An operator never seen here is shown by subject, once. */ + it('shows an unseen operator subject once', async () => { + vi.spyOn(api, 'fetchOperatorIdentities').mockResolvedValue([ + { oidcSubject: 'TEST-SUBJECT-UNSEEN', providerType: 'github', authorId: '3218389' }, + ]); + + render(, { wrapper: queryWrapper() }); + + await waitFor(() => expect(screen.getAllByText('TEST-SUBJECT-UNSEEN').length).toBe(1)); + }); + it('says what an empty list means', async () => { vi.spyOn(api, 'fetchOperatorIdentities').mockResolvedValue([]); diff --git a/spire-ui/src/components/SettingsOperators.tsx b/spire-ui/src/components/SettingsOperators.tsx index c37d9b62f..a672c64dd 100644 --- a/spire-ui/src/components/SettingsOperators.tsx +++ b/spire-ui/src/components/SettingsOperators.tsx @@ -14,6 +14,7 @@ import { } from '../api'; import { invalidateLive } from '../liveCache'; import AccountsTabs from './AccountsTabs'; +import { NameWithId } from './NameWithId'; import { ScmConnections } from './ScmConnections'; /** @@ -180,13 +181,11 @@ export function SettingsOperators() { {links.map((link) => ( - {operatorName(operators, link.oidcSubject)} -
{link.oidcSubject}
+ {link.providerType} - {nameFor(candidates, link)} -
{link.authorId}
+