From 0d286c1d7b67fc36265ef0b7d263d6f9644072f7 Mon Sep 17 00:00:00 2001 From: Artjoms Stukans Date: Sun, 15 Nov 2026 21:07:27 +0100 Subject: [PATCH 1/4] Record the signed-in operator on the session probe OperatorDirectory.seen had no caller, so operator_seen stayed empty on the first production install: Settings > Operators said nobody had signed in, the picker was empty, and a linked operator showed as the raw OIDC subject. /api/me now records the caller once per dashboard load. Email is never persisted. On that realm preferred_username is the email address, so OperatorNames drops any value containing '@': the username is stored empty, the display name is the name claim, and a subject that is itself an email is not recorded. A recording failure is logged and the probe still answers. Part of #391 --- .../orchestrator/security/AuthResource.java | 38 +++-- .../orchestrator/security/OperatorNames.java | 55 +++++++ .../AuthResourceOperatorSeenTest.java | 76 ++++++++++ .../AuthResourceRecordsOperatorTest.java | 143 ++++++++++++++++++ 4 files changed, 300 insertions(+), 12 deletions(-) create mode 100644 spire-orchestrator/src/main/java/dev/codespire/orchestrator/security/OperatorNames.java create mode 100644 spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceOperatorSeenTest.java create mode 100644 spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceRecordsOperatorTest.java 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..9fd72d665 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,14 @@ @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; + @ConfigProperty(name = "spire.security.auth-enabled", defaultValue = "true") boolean authEnabled; @@ -57,6 +62,9 @@ public record Me(boolean authEnabled, boolean authenticated, String user, ListOn the session probe because every dashboard load asks it once, which is exactly "who has + * been here". One UPSERT per load is cheap, so it is not throttled. 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; + } + try { + directory.seen(subject, OperatorNames.username(identity), OperatorNames.displayName(identity)); + } 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/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..cd3149352 --- /dev/null +++ b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/security/AuthResourceRecordsOperatorTest.java @@ -0,0 +1,143 @@ +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.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()); + } + + private static AuthResource resource(OperatorDirectory directory, SecurityIdentity identity) { + AuthResource resource = new AuthResource(); + resource.directory = directory; + 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); + } + }; + } +} From 5bdf05bb283962b1d3d7fd8019a8dbfa9a08b28f Mon Sep 17 00:00:00 2001 From: Artjoms Stukans Date: Sun, 15 Nov 2026 21:07:28 +0100 Subject: [PATCH 2/4] Show the SCM login a sign-in observed beside the id A linked SCM account showed its numeric id twice on a fresh install, because the only handle came from authors observed in reviews. The connect callback has just been told the login by the forge, so V116 keeps it as operator_identity.author_handle (display data, never a key; never the email, and dropped if it looks like one). The identity list returns it; the People table and the My activity chips show it with the id as fallback. A hand-made link keeps null, and a hand relink of the same account keeps the observed login. The People table also names an operator with an empty username by the display name alone, and shows a name equal to its id only once. Part of #391 --- docs/DATA-MODEL.md | 4 +- docs/HISTORY.md | 12 +++ docs/UNVERIFIED.md | 1 + .../analytics/OperatorIdentities.java | 31 +++++-- .../analytics/OperatorIdentityResource.java | 2 +- .../operator/OperatorConnectResource.java | 15 +++- .../V116__operator_identity_author_handle.sql | 10 +++ .../operator/OperatorConnectResourceTest.java | 87 +++++++++++++++++++ spire-ui/src/api.ts | 6 ++ spire-ui/src/components/Analytics.test.tsx | 20 +++++ spire-ui/src/components/Analytics.tsx | 2 +- .../src/components/SettingsOperators.test.tsx | 52 +++++++++++ spire-ui/src/components/SettingsOperators.tsx | 41 +++++++-- 13 files changed, 263 insertions(+), 20 deletions(-) create mode 100644 spire-orchestrator/src/main/resources/db/migration/V116__operator_identity_author_handle.sql 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..9f64b2637 100644 --- a/docs/HISTORY.md +++ b/docs/HISTORY.md @@ -2515,3 +2515,15 @@ 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 (one UPSERT per dashboard load, not throttled; 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..6132d8f2e 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(new OperatorIdentities.Link(attempt.oidcSubject(), type, author.providerUserId(), + observedHandle(author))); return back("connected"); } + /** + * The login the forge just reported, kept beside the id so the dashboard can show {@code artyomsv} + * rather than {@code 3218389}. 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 String observedHandle(Author author) { + String handle = OperatorNames.withoutEmail(author.username()); + return handle.isEmpty() ? null : handle; + } + /** * This deployment's own callback address, as the browser reached it. * 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/OperatorConnectResourceTest.java b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/operator/OperatorConnectResourceTest.java index 40fea37f5..9846dddcd 100644 --- a/spire-orchestrator/src/test/java/dev/codespire/orchestrator/operator/OperatorConnectResourceTest.java +++ b/spire-orchestrator/src/test/java/dev/codespire/orchestrator/operator/OperatorConnectResourceTest.java @@ -1,5 +1,11 @@ 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 io.restassured.RestAssured; @@ -11,6 +17,8 @@ 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; @@ -43,6 +51,9 @@ class OperatorConnectResourceTest { @Inject DataSource dataSource; + @Inject + OperatorIdentities identities; + @BeforeEach void clean() { exec("DELETE FROM scm_oauth_app WHERE provider_type = 'github'"); @@ -237,6 +248,82 @@ void refusesAFirstApplicationWithNoSecret() { .then().statusCode(400); } + /** + * A finished sign-in keeps the login the forge reported, so the dashboard shows {@code artyomsv} + * rather than the numeric id twice (first production install). The id stays the key. + */ + @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)); + assertEquals(null, 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(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; + } + }); + } + }, 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 int blankSubjectLinks() { try (Connection c = dataSource.getConnection(); PreparedStatement ps = c.prepareStatement( 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/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..836bcdc6c 100644 --- a/spire-ui/src/components/SettingsOperators.tsx +++ b/spire-ui/src/components/SettingsOperators.tsx @@ -180,13 +180,11 @@ export function SettingsOperators() { {links.map((link) => ( - {operatorName(operators, link.oidcSubject)} -
{link.oidcSubject}
+ {link.providerType} - {nameFor(candidates, link)} -
{link.authorId}
+