Repository navigation
feat(identity): social account link/unlink self-service (B2, v1.3.0) - #68
Conversation
…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.
|
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).
Self + agent review recordDesign/plan review (pre-implementation, code-reviewer agent): APPROVE-WITH-CHANGES — 6 required fixes incorporated before coding started:
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:
Follow-ups (not blocking): numeric-dispatch branch lacks a direct HTTP test case; |
…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.
Independent review round — 3-perspective verification (completeness / correctness / impact)Cross-verified the self-review record above against the diff ( Self-review claims — verified TRUE ✅
New findings this round (independent of the self-review): Warnings (SHOULD FIX)W1. W2. Google/WeChat link paths can persist an empty W3. Unlink does not disclose that existing sessions survive W4. After unlinking GitHub, 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)
Summary of changes
|
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).
Review round disposition — all findings addressed in eb64be5W1 (link-flow fall-through) — FIXED, plus a deeper trigger found. The guard now splits on W2 (empty subject) — FIXED. 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 W5 — tracked as #73, unchanged. Suggestions:
Verification: clean-DB |
…(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).
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).
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).
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.
…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.
…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
…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.
…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.
…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.
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.)
docs/productization-evolution/in-progress/social-link-unlink-{design,implementation-plan}.mdBackend
GET /api/me/social/links·POST /api/me/social/links/{provider}(code-verification link) ·DELETE .../{provider}(unlink) — all behindOAuth2AuthFilter,profilescope,#ifdef WITH_SOCIALroute registration.SocialLinkService(orchestration: verify code → 3-way conflict pre-checks → insert,UNIQUE(provider,subject)race backstop);ISocialAccountRepositoryextended withlistForUser/insertLink/deleteLink/userHasUsablePassword(all Mapper+Criteria, zero new raw SQL);GitHubAuthService::fetchProfile()extracted so linking never triggers find-or-create.password_hashlacks 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).social_account_{linked,link_failed,unlinked,unlink_blocked}).Frontend (user portal)
VITE_GITHUB_CLIENT_ID, authorize URL carriesstate=link; Google/WeChat buttons deferred).state= login (current behavior).Spec / SDK / version
openapi.yaml+3 paths + 3 schemas; Python & Go SDKs regenerated (drift gate green).cmake/Version.cmake,CMakeLists.txt,conanfile.py,pyproject.toml,info.version.kFingerprint(+3 ops), route-manifest golden, api-diff baseline (purely additive).Test evidence
SocialLinkServiceTest, 23 cases)SocialLinkEndpointHttpTest, 10 cases, mock-injected service + PG)full_test.bat(8 steps: DB reset→ORM→build→ctest→server→59 OAuth2→52 admin→shutdown)Review notes
statesession for the link flow — bearer-token authentication + single-use short-lived codes are the mitigations; full mitigation listed as follow-up.(provider, internal_user_id)DB constraint.fetchProfilenow also rejects GitHub responses withid <= 0(shared exchange path hardening; GitHub always returns a numeric id).SoftDeleteSocialRepoTesthas a pre-existing rerun-isolation flaw (fixed emailx@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.