Skip to content

feat(identity): social account link/unlink self-service (B2, v1.3.0) - #68

Merged
voidvec merged 8 commits into
masterfrom
feat/social-link-unlink
Aug 22, 2026
Merged

voidvec merged 8 commits into
masterfrom
feat/social-link-unlink

Conversation

@voidvec

@voidvec voidvec commented Aug 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes the IAM P1 gap from the architecture audit (§四: 「账号关联 link/unlink — 未实现」) — users can now view, link, and unlink their social identities (GitHub/Google/WeChat) from the self-service portal. (API supports all three providers; the UI ships a GitHub link button in this iteration -- Google/WeChat buttons are deferred, the API is ready for them.)

  • Design + implementation plan (deep-reviewed, 6 review findings incorporated): docs/productization-evolution/in-progress/social-link-unlink-{design,implementation-plan}.md
  • Upstream plan: next-phase-implementation-plan.md §三 B2

Backend

  • GET /api/me/social/links · POST /api/me/social/links/{provider} (code-verification link) · DELETE .../{provider} (unlink) — all behind OAuth2AuthFilter, profile scope, #ifdef WITH_SOCIAL route registration.
  • identity layer: new SocialLinkService (orchestration: verify code → 3-way conflict pre-checks → insert, UNIQUE(provider,subject) race backstop); ISocialAccountRepository extended with listForUser / insertLink / deleteLink / userHasUsablePassword (all Mapper+Criteria, zero new raw SQL); GitHubAuthService::fetchProfile() extracted so linking never triggers find-or-create.
  • Last-credential guard: unlink refused (409) when it would remove the user's only social link and password_hash lacks the $pbkdf2-sha256$ prefix (social-created accounts carry a random placeholder).
  • provider='local' exclusion: the seed/password flow plants a local subject mapping per user — not a social identity; excluded from listing and the guard count (found during implementation testing).
  • numeric-dispatch user resolution (mirrors userinfo): GitHub-session tokens store the internal id, so social-created users can actually call these endpoints ([High] Soft-deleted users can still obtain fresh tokens via GitHub social login (soft-delete contract bypass) #54/[Medium] deleteUser token revocation is fire-and-forget with fully swallowed errors (soft-deleted user's refresh token can stay valid forever) #56 dual-key context).
  • 4 audit events (social_account_{linked,link_failed,unlinked,unlink_blocked}).

Frontend (user portal)

  • SecurityPage "Connected Accounts" card (list / unlink-with-confirm / Link GitHub button gated on VITE_GITHUB_CLIENT_ID, authorize URL carries state=link; Google/WeChat buttons deferred).
  • GitHubCallbackPage: link branch short-circuits before the login POST (a link-flow visit must never mint a login session); absent state = login (current behavior).

Spec / SDK / version

  • openapi.yaml +3 paths + 3 schemas; Python & Go SDKs regenerated (drift gate green).
  • v1.3.0 (additive minor) synced across cmake/Version.cmake, CMakeLists.txt, conanfile.py, pyproject.toml, info.version.
  • Frozen baselines updated: Property4 kFingerprint (+3 ops), route-manifest golden, api-diff baseline (purely additive).

Test evidence

Suite Result
identity unit tests (SocialLinkServiceTest, 23 cases) ✅
HTTP integration (SocialLinkEndpointHttpTest, 10 cases, mock-injected service + PG) ✅
Full backend pipeline full_test.bat (8 steps: DB reset→ORM→build→ctest→server→59 OAuth2→52 admin→shutdown) ✅ ALL PASS
user frontend (vue-tsc + build + 103 e2e incl. 5 new + 21 unit) ✅
admin frontend (tsc+build + 168 e2e, 6 skipped as designed) ✅
CI static checks locally (arch-guard / migration-check / api-diff / naming / manage-parity / openapi_spec_validator / spec-governance + selftest / regen --check) ✅

Review notes

  • Known limitation (accepted in design §八.1): no server-side state session for the link flow — bearer-token authentication + single-use short-lived codes are the mitigations; full mitigation listed as follow-up.
  • Out of scope by design: Google/WeChat login consuming mappings (login parity), admin-side link management, (provider, internal_user_id) DB constraint.
  • Behavior nuance: fetchProfile now also rejects GitHub responses with id <= 0 (shared exchange path hardening; GitHub always returns a numeric id).
  • SoftDeleteSocialRepoTest has a pre-existing rerun-isolation flaw (fixed email x@example.com + unique index) that surfaces only when tests re-run without a DB reset — not addressed here; full pipeline resets the DB so it passes.

…2 M1-M2)

ISocialAccountRepository gains the mapping-lifecycle half of its bounded
concern: listForUser / insertLink / deleteLink / userHasUsablePassword
(all Mapper+Criteria, no raw SQL; listForUser excludes provider='local'
seed rows). GitHubAuthService::fetchProfile() extracts the code-exchange +
userinfo steps login() already ran, so linking an EXISTING user never
triggers find-or-create. SocialLinkService orchestrates verify ->
conflict pre-checks -> insert (UNIQUE(provider,subject) race backstop)
and unlink with the last-credential guard ($pbkdf2-sha256$ prefix test).
23 unit tests against the shared fakes.
Three OAuth2AuthFilter-protected routes (profile scope, WITH_SOCIAL
guarded): GET list, POST link (provider code verification), DELETE
unlink. User resolution mirrors userinfo's numeric dispatch (#54/#56
dual-key) so GitHub-session users can manage their own links. Audit
events social_account_{linked,link_failed,unlinked,unlink_blocked}.
IdentityAssembly wires the real service; SocialMockFixture gains
injectSocialLinkFake() for the 10-case HTTP integration suite.
… M5)

Three new paths (GET/POST/DELETE /api/me/social/links[/{provider}]) with
SocialLinkEntry/List/Result schemas; Property4 kFingerprint and the route
manifest golden re-baselined (+3 ops). Version 1.2.0 -> 1.3.0 (additive
minor) across cmake/Version.cmake, openapi.yaml info.version and
clients/python; Python + Go SDKs regenerated (drift gate green).
…nch (B2 M6)

SecurityPage gains a Connected Accounts card (list / unlink-with-confirm /
Link GitHub button gated on VITE_GITHUB_CLIENT_ID, authorize URL carries
state=link). GitHubCallbackPage short-circuits the link branch BEFORE the
login POST (a link-flow visit must never mint a login session) and returns
to /security. userService gains the three social-links API calls; e2e
mock routes + 5 new playwright specs (103 total green).
…e + docs (B2 M7)

api-diff version consistency spans cmake/Version.cmake, top-level
CMakeLists.txt and conanfile.py -- all now 1.3.0. The SDK API surface
baseline re-ratified (purely additive: SocialLinkService.h + repo/controller
declarations). Docs: iam-audit P1 gap closed, next-phase B2 ticked,
progress-status entry, design/implementation plan committed.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

…(B2)

Two review findings from PR #68:
- Drop the undocumented query-parameter 'code' fallback: codes carry
  provider credentials and must not ride query strings into access logs
  (spec documents requestBody only).
- Include 'subject' in the unlink 200 body (the service already resolves
  it), matching SocialLinkResult's schema description.
- Design doc: record the known unlink-guard check-then-act race (both
  concurrent unlinks of a 2-link user can pass the guard; self-inflicted,
  no cheap backstop -- accepted limitation).
@voidvec

voidvec commented Aug 21, 2026

Copy link
Copy Markdown
Owner Author

Self + agent review record

Design/plan review (pre-implementation, code-reviewer agent): APPROVE-WITH-CHANGES — 6 required fixes incorporated before coding started:

  1. Property4 kFingerprint baseline dependency added to the plan (would have failed AC4).
  2. 23505 SQLSTATE detection replaced with the in-repo duplicate key substring precedent (libpq's what() carries no SQLSTATE).
  3. Memory-leg test plan corrected — memory mode cannot produce a filter-valid bearer token (GitHub-login tokens are stored raw but validated by hash); all HTTP cases PG-guarded.
  4. Social-token dual-key gap ([High] Soft-deleted users can still obtain fresh tokens via GitHub social login (soft-delete contract bypass) #54/[Medium] deleteUser token revocation is fire-and-forget with fully swallowed errors (soft-deleted user's refresh token can stay valid forever) #56) addressed via userinfo-style numeric dispatch so GitHub-session users can call the new endpoints.
  5. e2e path (tests/e2e/) + redirect route (/security) corrected.
  6. Invented x-conditional spec claim dropped.

PR diff review (post-implementation): APPROVE-WITH-CHANGES — async lifetime discipline, db-operations compliance, error/catalog consistency, soft-delete contract, fake parity, and 5-way spec/route/fingerprint/manifest/client consistency all verified clean. Fixes landed in 42d2286:

  • Query-param code fallback removed (JSON-body only, per spec; codes must not leak into access logs).
  • subject added to the unlink 200 body (matches SocialLinkResult schema description).
  • Unlink-guard check-then-act race documented as a known limitation (design §3.3).

Follow-ups (not blocking): numeric-dispatch branch lacks a direct HTTP test case; SocialLinkService maps null-repo to InvalidProvider (unreachable via controller pre-validation).

@voidvec

voidvec commented Aug 22, 2026

Copy link
Copy Markdown
Owner Author

Follow-up issues registered

Everything deferred or surfaced by this PR is now tracked:

None block this PR's merge.

…rovider

Fixes #74. A missing account repository is a wiring defect, not a client
error: linkAccount now answers NotConfigured (controller -> 500) and
unlinkAccount answers RepositoryError (matching listAccounts), instead of
both rendering as 400 'unsupported provider'. Two unit tests pin the new
mapping.
@voidvec

voidvec commented Aug 22, 2026

Copy link
Copy Markdown
Owner Author

Independent review round — 3-perspective verification (completeness / correctness / impact)

Cross-verified the self-review record above against the diff (master...feat/social-link-unlink, 7 commits, +5314/−117). Verdict on the existing review opinions:

Self-review claims — verified TRUE ✅

New findings this round (independent of the self-review):

Warnings (SHOULD FIX)

W1. state=link without a local token silently falls through to login — and can auto-create an account
frontends/user/src/pages/oauth/GitHubCallbackPage.vue (~L26)
The guard is state === 'link' && getAccessToken(). If the token is absent (logged out in another tab / session expired during the GitHub round-trip), the condition is false and control falls into the existing POST /api/github/login — for an unmapped GitHub identity this runs find-or-create and mints a brand-new account + session, which is exactly what this branch's own comment says it must prevent. The PR description's absolute invariant ("a link-flow visit must never mint a login session") is provably violated by ?code=x&state=link with no token.
Fix: split the condition — state === 'link' with no token must short-circuit to an error ("please sign in and retry the link"), never fall through to login.

W2. Google/WeChat link paths can persist an empty subject
libs/identity/src/social/SocialLinkService.cc onSubject (~L81)
onSubject only checks errorCode.empty(). GitHub is guarded (githubId <= 0 rejected), but GoogleAuthService / WeChatAuthService both use .get("sub"/"openid", "") — a 200 userinfo response missing the identifier yields empty errorCode + empty subject → insertLink("google", "", userId) succeeds and permanently claims the UNIQUE(provider, subject='') slot (second user gets 409; login lookups with empty subject hit the wrong user).
Fix: treat empty subject as ExchangeFailed at the top of onSubject.

W3. Unlink does not disclose that existing sessions survive
unlinkAccount deletes the mapping row only; access/refresh tokens issued via that social session stay valid until expiry. The design doc records this decision (§risk list #4), but the downstream contract (openapi DELETE /api/me/social/links/{provider} description) doesn't say so. Either add "existing sessions are not revoked" to the spec description, or cascade-revoke like changePassword/revokeAuthorizedApp do.

W4. After unlinking GitHub, POST /api/github/login permanently returns DB_QUERY_ERROR
libs/identity/src/social/GitHubAuthService.cc (~L189-274)
New state this PR makes reachable: mapping deleted but the gh_<login> user row remains → next GitHub login: NoMapping → createLinkedUser → INSERT ... ON CONFLICT (username) DO NOTHING → empty result → login fails with DB_QUERY_ERROR (verified: repository comment itself documents "username conflict now yields an EMPTY result and the login fails"). Not self-healing without re-linking. Recommend distinguishing this case (actionable error, e.g. prompt to re-link) or surfacing it in the unlink confirm dialog.

W5. (pre-agreed) Unlink-guard TOCTOU race — concurrent unlinks of 2 links can bypass the last-credential guard. Consistent with what the self-review already registered as #73; re-confirmed during this round, no action needed beyond #73.

Suggestions (CONSIDER)

  • linked_at is serialized as "YYYY-MM-DD HH:MM:SS" (local, space-separated) while the repo contract comment says ISO-8601 — new Date(...) on this yields Invalid Date in Safari; e2e mocks use the T-form and mask it.
  • duplicate key substring detection follows the in-repo precedent, but drogon::DbException::sqlState() == "23505" would be locale-independent (lc_messages ≠ en breaks the substring match).
  • Concurrent same-user/same-provider links with different subjects have no DB backstop (UNIQUE covers only the same-subject race) — accepted in design D5; consider documenting the window explicitly.
  • userService.ts gains 3 social methods but the pages call raw http/axios directly — wire them or drop the methods.
  • UI only offers "Link GitHub"; PR summary says GitHub/Google/WeChat — matches the design (Google/WeChat link buttons deferred) but the PR summary wording invites a stricter acceptance reading.

Summary of changes

  • Backend delivers exactly the claimed scope: 3 self-service endpoints, SocialLinkService orchestration with 3-way conflict pre-checks + UNIQUE backstop, last-credential guard, local-provider exclusion, numeric-dispatch user resolution, 4 audit events.
  • fetchProfile extraction is behavior-preserving for GitHub login (error codes and find-or-create sequence unchanged); the id <= 0 rejection is a safety tightening.
  • Version bump, OpenAPI/SDK regen, and all 3 frozen baselines are internally consistent and purely additive; zero migrations, zero config changes.
  • Two genuinely new issues worth fixing before merge: W1 (link-flow fall-through can auto-create accounts) and W2 (empty-subject insert for Google/WeChat).

W1: GitHubCallbackPage link branch no longer falls through to login when
    the session is gone -- tryRestoreSession() first (the OAuth round-trip
    is a full reload, the in-memory access token is always lost), and an
    unrestorable session shows an error instead of minting a login
    session / auto-creating an account. New e2e pins 'no API call' behavior.
W2: SocialLinkService treats an empty provider subject (Google's missing
    sub / WeChat's missing openid on a 200 userinfo) as ExchangeFailed
    instead of inserting UNIQUE(provider, ''). Two unit tests.
W3: openapi DELETE description now discloses that existing sessions are
    NOT revoked and the identity cannot sign in until re-linked; SDKs
    regenerated.
W4: unlink confirm dialog warns about re-login behavior; design doc
    records the gh_<login> username-conflict aftermath (actionable-error
    refinement tracked on #70).
S1: linked_at serialized as ISO-8601 with 'T' (Safari-parsable) instead
    of toDbStringLocal's space-separated form; new real-PG lifecycle test
    covers listForUser (local-row exclusion + ISO), insertLink (Conflict
    path), deleteLink (Deleted/NoLink), userHasUsablePassword.
S2: unique-violation detection prefers SqlError::sqlState()==23505, then
    the never-localized constraint name (drogon's postgres ASYNC path
    delivers a plain Failure with a locale-dependent message -- verified
    on a zh_CN server), then the English substring precedent.
S3/S4: same-user same-provider different-subject race window documented
    (design D5 note); pages wired to userService methods (shared http
    interceptor: Bearer attach + 401 refresh) instead of raw http/axios.
PR body wording clarified (API: 3 providers; UI button: GitHub this
iteration).
@voidvec

voidvec commented Aug 22, 2026

Copy link
Copy Markdown
Owner Author

Review round disposition — all findings addressed in eb64be5

W1 (link-flow fall-through) — FIXED, plus a deeper trigger found. The guard now splits on state === 'link' alone: it first awaits tryRestoreSession() — necessary even for signed-in users, because the GitHub round-trip is a full page reload and the in-memory access token is always gone at mount — and only if the session cannot be restored shows "please sign in first, then retry". No path reaches the login POST with state=link. New e2e (state=link + no session → error, zero API calls) plus the existing positive case (now exercising the restore path) pin both sides.

W2 (empty subject) — FIXED. onSubject treats errorCode.empty() && subject.empty() as ExchangeFailed/VALIDATION_INVALID_INPUT; two unit tests (Google missing sub, WeChat missing openid).

W3 (session-survival disclosure) — FIXED. openapi DELETE description now states sessions are not revoked and the identity cannot sign in until re-linked; SDKs regenerated (drift gate green).

W4 (re-login after unlink) — UI + docs now, backend deferred with tracking. Unlink confirm dialog says "you will not be able to sign in with ${label} until it is linked to an account again"; design §3.3 documents the gh_<login> username-conflict aftermath (DB_QUERY_ERROR until re-linked). The actionable-error refinement belongs with the login-consumption rework — noted on #70 (see the scope-addition comment there; PAT scope blocked an issue comment, so the substance is: distinguish derived-username conflict from real DB failure, consider rename/re-link-to-existing semantics).

W5 — tracked as #73, unchanged.

Suggestions:

  • linked_at → FIXED: toCustomFormattedString("%Y-%m-%dT%H:%M:%SZ") (ISO-8601 with T, Safari-parsable); pinned by a new real-PG lifecycle test (Integration_P0_SocialRepo_LinkLifecycle_ListInsertDelete) that also gives the 4 new repository methods their first against-Postgres coverage: local-row exclusion, ISO timestamp, insertLink Conflict path, deleteLink Deleted/NoLink, userHasUsablePassword false for non-pbkdf2 hashes.
  • sqlState() → investigated, partially adopted: drogon's postgres async error path delivers a plain Failure(PQerrorMessage(...)), not a SqlError (PgConnection.cc handleFatalError) — so e.base().sqlState() is empty on every Mapper error callback and the suggestion can't work as stated. Detection now: sqlState (future-proof) → the never-localized constraint name oauth2_subject_mappings_provider_subject_key → English substring. Empirically validated on this zh_CN server (重复键违反唯一约束... — both original paths would have missed it; the constraint-name path catches it).
  • Same-user/same-provider/different-subject race → documented in design §3.2 (bounded consequence: two self-owned mappings; not a security hole).
  • userService methods → wired: SecurityPage + GitHubCallbackPage now call them (shared http interceptor brings Bearer-attach + 401 auto-refresh for free — the callback previously hand-built the header).
  • PR summary wording → clarified (API: 3 providers; UI button: GitHub this iteration).

Verification: clean-DB OAuth2Tests 510/510; identity unit 27/27; user frontend vue-tsc + build + 104 e2e (incl. 2 new) + unit all green; governance gate, SDK drift gate, api-diff, naming check all pass.

@voidvec
voidvec merged commit e991360 into master Aug 22, 2026
11 checks passed
voidvec added a commit that referenced this pull request Aug 22, 2026
…(B2)

Two review findings from PR #68:
- Drop the undocumented query-parameter 'code' fallback: codes carry
  provider credentials and must not ride query strings into access logs
  (spec documents requestBody only).
- Include 'subject' in the unlink 200 body (the service already resolves
  it), matching SocialLinkResult's schema description.
- Design doc: record the known unlink-guard check-then-act race (both
  concurrent unlinks of a 2-link user can pass the guard; self-inflicted,
  no cheap backstop -- accepted limitation).
@voidvec
voidvec deleted the feat/social-link-unlink branch August 22, 2026 12:03
voidvec added a commit that referenced this pull request Aug 22, 2026
Fixes #76. drogon's CHECK/REQUIRE expand their argument via
(Decomposer() <= expr); an unparenthesized boolean chain re-associates to
(Decomposer() <= a) || b and silently mis-evaluates (bit PR #68 as a
seemingly-flaky assertion). New static check
tools/test/scripts/drogon_macro_bool_check.py (with --selftest) flags
top-level bare operators; wired into CI static checks next to the naming
validator. Convention documented in docs/backend/testing-guide.md §2
with the safe forms ((bool)(...), outer parens, split assertions) and
the repo's existing FunctionalTest.cc precedent. Current tree scans
clean (109 files).
voidvec added a commit that referenced this pull request Aug 22, 2026
Fixes #76. drogon's CHECK/REQUIRE expand their argument via
(Decomposer() <= expr); an unparenthesized boolean chain re-associates to
(Decomposer() <= a) || b and silently mis-evaluates (bit PR #68 as a
seemingly-flaky assertion). New static check
tools/test/scripts/drogon_macro_bool_check.py (with --selftest) flags
top-level bare operators; wired into CI static checks next to the naming
validator. Convention documented in docs/backend/testing-guide.md §2
with the safe forms ((bool)(...), outer parens, split assertions) and
the repo's existing FunctionalTest.cc precedent. Current tree scans
clean (109 files).
voidvec added a commit that referenced this pull request Aug 22, 2026
Frontends' package.json synced to 1.3.0 (the cmake/CMakeLists/conanfile/
pyproject/openapi bumps landed with PR #68); CHANGELOG curated for the
two mainlines since v1.2.0: C1 client SDKs (Python authforge-oauth2 + Go,
PR #65) and B2 social account link/unlink (PR #68). 21 commits, purely
additive minor.
voidvec added a commit that referenced this pull request Aug 25, 2026
…log, next-phase plan

progress-status: Phase 0 verdicts refreshed to 2026-08-23 TTL=30
comparison (five-scenario lead, cold-start 1.26s); Phase 1 ~60% (PyPI
1.4.0 live, README badge done); Phase 2 ~50% (backchannel full-stack
PR #61 + social link/unlink PR #68); perf-optimization workstream added;
issue section rewritten to current 15 open issues in 4 categories;
milestones extended through v1.4.0 (2026-08-24).

iam-architecture-audit: Backchannel Logout upgraded from
'backend delivered' to full-stack (PR #61, #55/#57 hardening, leftover
#82); social link/unlink row annotated with 5 follow-up issues
(#69/#70/#71/#73/#54); footer baseline bumped to v1.4.0.

SUMMARY.md: staleness banner — numbers superseded by optimization
program + competitor comparison; points to COMPARISON.md as authority
(S2 8.9k→14.4k, S6 16.7k→49.3k etc.); original kept as pre-optimization
baseline record.

next-phase-implementation-plan (4th revision): all seven original
workstreams (A1/A2/A3-badge/B1/B2/C1/C3) marked delivered; new focus =
Tier1 security batch (#78 end_session signature verify, #79/#80 cache
refill race, #54 soft-delete social bypass) → Tier2 social fixes
(#69 token hash mismatch 401, #71 state validation, #70 mappings,
#73 guard race) → Tier3 blog (M1) + docs site (M2) → Tier4 hygiene
(#81/#72/#82/#83/#84/#66 + stale branch cleanup); parallel-safety map,
risks, and 4 decision items.
voidvec added a commit that referenced this pull request Aug 25, 2026
…y lookup path

GitHubController::issueTokensForUser persisted access/refresh tokens RAW
while every read path resolves the presented token via hashToken
(UPPER(SHA256 hex)) before the repository lookup. A GitHub social session
therefore 401'd on EVERY Bearer-authenticated endpoint, the refresh grant
returned invalid_grant, and the raw refreshToken.accessToken mirror could
never match revokeTokenFamily's hashed-column SQL — the social flow was
read-only login theater.

Storage now mirrors TokenService's grant issuance and
TokenEndpointController's controller-constructed pairs (CryptoUtils::
hashToken and TokenCrypto::hashToken are byte-identical). Response bodies
still return the raw strings; only persistence changes. No legacy
migration: the raw-stored tokens were unusable from the day they were
issued (issue #69's rationale; decision (b) in the task brief).

Tests (SocialLoginHttpTest): refresh grant with the social refresh token
(200 + rotated pair; every storage mode via vue-client public auth);
PG-backed chain — introspect active:true (backend-svc Basic), userinfo
200 with the social token, and the FULL /api/me/social/links lifecycle
(link -> list -> unlink) driven by the social token through the PR #68
numeric-dispatch branch, closing the #75 coverage gap.

Fixes #69
Fixes #54
Fixes #75
voidvec added a commit that referenced this pull request Aug 27, 2026
…injection (#71)

The link flow was two-legged with a client-chosen state ('link') that the
server never validated: anyone who could script a POST in the victim's
browser could graft the ATTACKER's provider identity onto the victim's
account (then sign in as the victim through that provider). Accepted at
design time (D3) for lack of TTL storage; this closes it.

Backend:
- New identity-layer port ISocialLinkStateStore (issue -> one-time token
  bound to (internal user id, provider); consume -> GETDEL semantics).
  Redis implementation (SET NX EX 600 / GETDEL, 128-bit random hex from
  ICryptoProvider) in libs/drogon adapters; in-memory implementation for
  tests. Fail-closed: no store -> begin/link answer NotConfigured, never
  a stateless link.
- SocialLinkService::beginLink mints the state; linkAccount now takes
  the state and consumes it BEFORE any upstream exchange (unknown/
  expired/replayed/foreign-bound -> new InvalidState status -> 400
  envelope, deliberately generic wording). The exchange continuation
  moved to a static proceedWithExchange taking every dependency
  explicitly (domain layer, no [this] in async chains).
- POST /api/me/social/links/{provider}/authorize: bearer-authed; mints
  the state and returns {state, authorize_url} built server-side from
  external_auth.{provider} (client ids never reach the SPA; the
  VITE_GITHUB_CLIENT_ID dependency is gone). redirect_uri from
  external_auth or frontend-url fallback; github/google/wechat URL
  shapes per their OAuth docs.
- IdentityAssembly wires the Redis store (warns + fail-closed when
  Redis is absent). Controller maps InvalidState to 400.

Frontend (user portal):
- SecurityPage links via the authorize endpoint (button, not a
  client-built URL) and sets a sessionStorage flow marker before
  redirecting; GitHubCallbackPage identifies the link flow by the marker
  OR a non-empty state (login sends none), passes {code, state} to the
  link POST, and clears the marker. The old 'state=link' constant is
  gone.

Contract (three-place sync per spec governance):
- openapi.yaml: new authorize operation; link request body requires
  [code, state]; 400 description updated. oasdiff-breaking-ignore.md
  carries the required-state entry with justification (PR #68-era
  endpoint, only this repo's SPA calls it, SDKs regen in the same PR).
- Fingerprint baseline (Property4) and OpenApiGenerator doc
  registrations updated; check_spec_governance green locally.

Tests: 8 new service-level cases (begin mint/invalid/no-store,
missing/unknown/foreign-user/foreign-provider/replayed state), HTTP
gate cases (missing state 400 envelope, foreign-bound state 400,
authorize behind auth filter), and all existing link/unlink HTTP tests
migrated to the minted-state flow via the fixture's Memory store.

api-diff baseline ratified (--force): constructor gained another
defaulted trailing arg (source-compatible, in-repo construction only);
everything else additive.
voidvec added a commit that referenced this pull request Aug 28, 2026
…injection (#71)

The link flow was two-legged with a client-chosen state ('link') that the
server never validated: anyone who could script a POST in the victim's
browser could graft the ATTACKER's provider identity onto the victim's
account (then sign in as the victim through that provider). Accepted at
design time (D3) for lack of TTL storage; this closes it.

Backend:
- New identity-layer port ISocialLinkStateStore (issue -> one-time token
  bound to (internal user id, provider); consume -> GETDEL semantics).
  Redis implementation (SET NX EX 600 / GETDEL, 128-bit random hex from
  ICryptoProvider) in libs/drogon adapters; in-memory implementation for
  tests. Fail-closed: no store -> begin/link answer NotConfigured, never
  a stateless link.
- SocialLinkService::beginLink mints the state; linkAccount now takes
  the state and consumes it BEFORE any upstream exchange (unknown/
  expired/replayed/foreign-bound -> new InvalidState status -> 400
  envelope, deliberately generic wording). The exchange continuation
  moved to a static proceedWithExchange taking every dependency
  explicitly (domain layer, no [this] in async chains).
- POST /api/me/social/links/{provider}/authorize: bearer-authed; mints
  the state and returns {state, authorize_url} built server-side from
  external_auth.{provider} (client ids never reach the SPA; the
  VITE_GITHUB_CLIENT_ID dependency is gone). redirect_uri from
  external_auth or frontend-url fallback; github/google/wechat URL
  shapes per their OAuth docs.
- IdentityAssembly wires the Redis store (warns + fail-closed when
  Redis is absent). Controller maps InvalidState to 400.

Frontend (user portal):
- SecurityPage links via the authorize endpoint (button, not a
  client-built URL) and sets a sessionStorage flow marker before
  redirecting; GitHubCallbackPage identifies the link flow by the marker
  OR a non-empty state (login sends none), passes {code, state} to the
  link POST, and clears the marker. The old 'state=link' constant is
  gone.

Contract (three-place sync per spec governance):
- openapi.yaml: new authorize operation; link request body requires
  [code, state]; 400 description updated. oasdiff-breaking-ignore.md
  carries the required-state entry with justification (PR #68-era
  endpoint, only this repo's SPA calls it, SDKs regen in the same PR).
- Fingerprint baseline (Property4) and OpenApiGenerator doc
  registrations updated; check_spec_governance green locally.

Tests: 8 new service-level cases (begin mint/invalid/no-store,
missing/unknown/foreign-user/foreign-provider/replayed state), HTTP
gate cases (missing state 400 envelope, foreign-bound state 400,
authorize behind auth filter), and all existing link/unlink HTTP tests
migrated to the minted-state flow via the fixture's Memory store.

api-diff baseline ratified (--force): constructor gained another
defaulted trailing arg (source-compatible, in-repo construction only);
everything else additive.
voidvec added a commit that referenced this pull request Aug 28, 2026
…injection (#71)

The link flow was two-legged with a client-chosen state ('link') that the
server never validated: anyone who could script a POST in the victim's
browser could graft the ATTACKER's provider identity onto the victim's
account (then sign in as the victim through that provider). Accepted at
design time (D3) for lack of TTL storage; this closes it.

Backend:
- New identity-layer port ISocialLinkStateStore (issue -> one-time token
  bound to (internal user id, provider); consume -> GETDEL semantics).
  Redis implementation (SET NX EX 600 / GETDEL, 128-bit random hex from
  ICryptoProvider) in libs/drogon adapters; in-memory implementation for
  tests. Fail-closed: no store -> begin/link answer NotConfigured, never
  a stateless link.
- SocialLinkService::beginLink mints the state; linkAccount now takes
  the state and consumes it BEFORE any upstream exchange (unknown/
  expired/replayed/foreign-bound -> new InvalidState status -> 400
  envelope, deliberately generic wording). The exchange continuation
  moved to a static proceedWithExchange taking every dependency
  explicitly (domain layer, no [this] in async chains).
- POST /api/me/social/links/{provider}/authorize: bearer-authed; mints
  the state and returns {state, authorize_url} built server-side from
  external_auth.{provider} (client ids never reach the SPA; the
  VITE_GITHUB_CLIENT_ID dependency is gone). redirect_uri from
  external_auth or frontend-url fallback; github/google/wechat URL
  shapes per their OAuth docs.
- IdentityAssembly wires the Redis store (warns + fail-closed when
  Redis is absent). Controller maps InvalidState to 400.

Frontend (user portal):
- SecurityPage links via the authorize endpoint (button, not a
  client-built URL) and sets a sessionStorage flow marker before
  redirecting; GitHubCallbackPage identifies the link flow by the marker
  OR a non-empty state (login sends none), passes {code, state} to the
  link POST, and clears the marker. The old 'state=link' constant is
  gone.

Contract (three-place sync per spec governance):
- openapi.yaml: new authorize operation; link request body requires
  [code, state]; 400 description updated. oasdiff-breaking-ignore.md
  carries the required-state entry with justification (PR #68-era
  endpoint, only this repo's SPA calls it, SDKs regen in the same PR).
- Fingerprint baseline (Property4) and OpenApiGenerator doc
  registrations updated; check_spec_governance green locally.

Tests: 8 new service-level cases (begin mint/invalid/no-store,
missing/unknown/foreign-user/foreign-provider/replayed state), HTTP
gate cases (missing state 400 envelope, foreign-bound state 400,
authorize behind auth filter), and all existing link/unlink HTTP tests
migrated to the minted-state flow via the fixture's Memory store.

api-diff baseline ratified (--force): constructor gained another
defaulted trailing arg (source-compatible, in-repo construction only);
everything else additive.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants