Skip to content

refactor(drogon): share client-credentials and device token payloads - #348

Merged
voidvec merged 3 commits into
masterfrom
refactor/token-success-payload-s08-b2
Nov 22, 2026
Merged

voidvec merged 3 commits into
masterfrom
refactor/token-success-payload-s08-b2

Conversation

@voidvec

@voidvec voidvec commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

Extract private client-credentials/device success payload builders while keeping protocol policy, persistence, signing, callback ownership and HTTP presentation at their existing call sites. This complements #346's authorization-code/refresh response extraction.

This PR also fixes #360: admin scopes PUT now reports success only after transaction commit and invokes the existing best-effort client-cache invalidation hook before responding. A new review fix explicitly rolls back if preparing replacement rows/mappers throws after DELETE; Drogon otherwise commits a transaction when its final owner is released. Error and success paths share an exactly-once response guard. Invoking the cache hook does not assert that Redis has acknowledged DEL.

Fixes #360

Scope and review

Three commits, eight files: the original payload extraction, the commit-ordering fix, and the preparation-error rollback/test-hardening fix. Rebased onto master 324fdf16; the original payload/controller/test files retain their previously reviewed content. No public API, error code, schema, configuration, SDK, frontend or grant-policy change.

Scope fixtures now use existing admin services and fail on setup errors. Scope reads distinguish failed HTTP/JSON from a valid empty list. Timeout callbacks own shared promise state.

The new PostgreSQL test checks the actual framework transaction contract: delete two seeded rows, throw during preparation, explicitly roll back, then use an independent Mapper row-lock barrier to verify both rows remain. It does not inject allocation failure into the production noexcept Mapper path; the production catch-to-rollback wiring was reviewed directly. Independent plan and implementation reviews passed locally.

Validation

  • Release / C++17 / WERROR build, all optional features enabled; local resource setting -O1 -DNDEBUG, examples disabled.
  • Full local CTest: 681 passed, zero failed. Full main binary: 767 cases / 63,073 assertions. All library suites passed.
  • Real isolated PostgreSQL/Redis; EndpointTests_OutOfProcess executed: OAuth 62 passing cases (the existing summary denominator is 63), admin 61/61; Social and FeatureSurface ran.
  • Focused scope tests: commit-ordered cache invalidation 6 assertions; immediate post-commit reads 19; preparation-error rollback preservation 14; all passed.
  • 13 repository static/contract checks passed. Runtime/flat config hashes and fixture ownership checked.
  • Actual tested product/library/test files are unchanged by the subsequent workflow-only master rebase. Fresh PR CI and SDK consumer checks are required on published head 603f8dc8. Client SDK workflow 44666032114 passed on that exact head.

The payload HTTP characterization retains its two per-run UUID clients and associated issued-token/device rows in the isolated functional fixture: hard client DELETE would hit existing token foreign keys. Repeated characterization runs accumulate fixture data until retirement; no shared records or canonical capacity fixture are purged. The new scope-only fixtures use existing admin services for cleanup.

The existing broker-profile CSP branch is outside this local wiring, and the managed wrapper skips its second memory-profile round. No capacity acceptance is claimed. Main's strict coverage and scheduled TSan findings remain tracked separately in #365 and #366; skipped PR gates are not reported as passes.

Checklist

  • Regression coverage and CHANGELOG updated.
  • Independent design/implementation review completed; rollback catches and asynchronous ownership inspected.
  • No baseline, security check or CI requirement weakened.
  • Fresh head CI passed: three platforms, SDK consumer, security, feature variants and ASan/UBSan; configured strict/nightly skips remain disclosed.
  • Real non-author approval on the updated head before rebase merge.

@voidvec
voidvec force-pushed the refactor/token-success-payload-s08-b2 branch from 11e4a36 to 3992ca3 Compare November 17, 2026 02:49
@voidvec

voidvec commented Nov 17, 2026

Copy link
Copy Markdown
Owner Author

必须处理项

评审基于 3992ca3f387bb7591b151f23f230e9cfeb9572ad。

本轮未发现需要阻断合并的新增缺陷。

已逐项对照抽取前后的赋值:CC 始终包含 scope 且不带 refresh_token/id_token;device 始终包含 refresh_token、仅在非空时包含 scope;expires_in 保留有符号 64 位整数。设备 ID-token 签名、持久化成功判断、一次性兑换、回调所有权和 HTTP/metrics 处理均仍在原位置,没有借抽取修改 grant 策略。新增实现会被现有 CMake 源码收集,私有头不进入安装 SDK。

七个纯 payload 测试覆盖字段集合、空值、Int64 序列化、转义/UTF-8 与对象独立性;HTTP characterization 覆盖 CC 显式/默认/拒绝 scope,以及 device 的空/profile/openid、pending/slow_down、批准、兑换与重放。一次性凭据 POST 没有透明重试,scope 配置等待只执行有总截止时间的读取;已声明的隔离 fixture 保留策略不作为隐藏缺陷。

当前 head 三平台、SDK smoke、ASan+UBSan 均成功。Windows/macOS 使用 memory 配置,HTTP PostgreSQL 用例在数据库不可用时返回,不能据此声称所有平台均执行了该链路。本轮未本地重编或启动数据库。advisory coverage 的工作流成功不等于内部 ratchet 通过;正文已披露 storage-memory 96.3% 低于 96.5%,严格 coverage gate/nightly TSan 跳过,本评审不将其描述为全部质量门禁通过。

@voidvec

voidvec commented Nov 17, 2026

Copy link
Copy Markdown
Owner Author

建议处理项

评审基于 3992ca3f387bb7591b151f23f230e9cfeb9572ad。

暂无需要另行追加的非阻断建议。实现和测试均与“私有、纯 payload、行为保持”的边界一致;不建议在这个 PR 顺带更改签名策略、错误响应头、fixture 删除语义或公共 API,也不把已有覆盖率告警重复归因于这次 payload 抽取。

wangrh0909
wangrh0909 previously approved these changes Nov 18, 2026
@wangrh0909
wangrh0909 force-pushed the refactor/token-success-payload-s08-b2 branch from 3992ca3 to 7f92105 Compare November 18, 2026 04:04
@voidvec

voidvec commented Nov 19, 2026 •

Copy link
Copy Markdown
Owner Author

Deep review: P0–P2 issue register

Reviewed head 7f921057 (1 commit / 6 files). No P0/P1/P2 introduced by this PR. Field-by-field behavior parity verified at both call sites (CC always-present scope incl. empty string, no refresh/id token; device always-present refresh token incl. empty string, scope only when non-empty; expires_in signed-Int64 semantics identical). Persistence gates, id-token signing, metrics, applyNoStoreHeaders and (*sharedCb) ownership are untouched. Architecture compliant: presentation stays in the adapter layer, src-local private header (no SDK/api-baseline surface), controllers::detail follows existing precedent, dependency direction controller → helper → jsoncpp/std only.

One pre-existing P2 was discovered during review; it is registered below and does not block this PR.

P2 — pre-existing, NOT introduced by this PR: admin scopes PUT responds before transaction commit

ClientManagementService::updateClientScopes sends the 200 response when the last INSERT completes (ClientManagementService.cc:881, comment at :867 acknowledges "the response goes out now"), and the empty-scopes branch responds after deleteBy (:843) — both before the newTransaction (:822) actually commits. Cache invalidation is correctly deferred to the commit callback (:829), but the response is not.

Impact: a client that receives 200 and immediately issues a grant or a scopes GET can observe the old scope set; a validateClient cache miss inside that window can refill the cache with the stale set for a full TTL. This PR's bounded read-only scopesVisible polling is a legitimate workaround for that race, not a masking of any refactor defect.

Suggested handling: open a separate tracking issue (per the repo tracking template) to move the success response into the commit callback; fix in its own PR. Do not mix into this behavior-preserving refactor.

Callback safety audit — no issues

  • Capture lists unchanged at both sites (TokenEndpointController.cc:1411 CC, :1799 device); sharedCb remains std::make_shared<std::function<...>> per db-operations (:1267/:1510); all captures by value; no [this] or [&] introduced.
  • The builders are pure functions: const-ref parameters, return-by-value, no statics or shared state — safe on any loop thread and non-blocking (DbLoop rule compliant).
  • Single-invocation ownership of (*sharedCb) preserved on success, persistence-failure (500 before payload) and atomic-consume-failure paths.
  • Exception surface identical to the previous inline construction (Json allocation only); no new throw source. Pre-existing note (unchanged by this PR): payload construction inside the async callbacks has no try/catch, so a bad_alloc would escape to the event loop — same exposure before and after.

Lifetime audit — no issues

  • No dangling references: builder parameters are const refs to value-captured strings whose lifetime covers the synchronous call.
  • Json::Value returned by value; id_token appended to the local object afterwards; no cross-callback sharing or static payload reuse.
  • plugin raw pointer is the process-lifetime Drogon singleton (project convention); no new async operation, callback registration or move introduced (no double-move risk).

voidvec added a commit that referenced this pull request Nov 19, 2026
#360)

updateClientScopes sent the 200 when the last INSERT completed, before
the destructor-time COMMIT: a caller issuing an immediate grant or
scopes GET could observe the old set, and a validateClient cache miss
in that window refilled the cache with stale scopes for a full TTL.

Both success branches (empty and non-empty) now respond from the
transaction commit callback, after cache invalidation. A failed COMMIT
returns DB_QUERY_ERROR; statement failures keep their single error
response via an exactly-once responded guard (rolled-back transactions
never fire the commit callback). Insert Mappers are pre-constructed so
a construction failure leaves the transaction pristine; Mapper
construction is try/catch-wrapped per db-operations.

Regression: the write-path invalidation test asserts the DEL fired
synchronously when the 200 arrives (polling removed), and a new case
reads scopes immediately after the 200 for both branches. Positive
control: against the pre-fix implementation the new test fails 5/5
runs deterministically.

Found in the PR #348 deep review (pre-existing, not introduced by the
payload refactor); tracked in #360.
voidvec added a commit that referenced this pull request Nov 19, 2026
#360)

updateClientScopes sent the 200 when the last INSERT completed, before
the destructor-time COMMIT: a caller issuing an immediate grant or
scopes GET could observe the old set, and a validateClient cache miss
in that window refilled the cache with stale scopes for a full TTL.

Both success branches (empty and non-empty) now respond from the
transaction commit callback, after cache invalidation. A failed COMMIT
returns DB_QUERY_ERROR; statement failures keep their single error
response via an exactly-once responded guard (rolled-back transactions
never fire the commit callback). Insert Mappers are pre-constructed so
a construction failure leaves the transaction pristine; Mapper
construction is try/catch-wrapped per db-operations.

Regression: the write-path invalidation test asserts the DEL fired
synchronously when the 200 arrives (polling removed), and a new case
reads scopes immediately after the 200 for both branches. Positive
control: against the pre-fix implementation the new test fails 5/5
runs deterministically.

Found in the PR #348 deep review (pre-existing, not introduced by the
payload refactor); tracked in #360.
@voidvec
voidvec force-pushed the refactor/token-success-payload-s08-b2 branch from 23be3cc to 6f5fbce Compare November 19, 2026 10:05
wangrh0909
wangrh0909 previously approved these changes Nov 19, 2026

@voidvec voidvec left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Merge review found a blocker in the #360 follow-up, separate from the payload extraction:

  • After the DELETE succeeds, the preparation catches return DB_QUERY_ERROR without transaction->rollback(). Drogon 1.9.13 commits an otherwise active transaction at destruction; responded=true also suppresses the commit callback's invalidation. A caught preparation failure can therefore commit the deletion while reporting failure and retaining stale cache state.
  • The new scope-order fixture records CHECK(true) and returns after setup failure.
  • Its getScopes helper maps transport/status/JSON failures to an empty vector, so the empty-scopes assertion can pass on a failed read.

The private payload builders/controller replacements have no blocking finding in this review. The transaction and regression-test findings need correction and fresh validation before merge; existing green CI does not exercise the caught preparation-failure path.

Extract pure private JSON construction while preserving scope presence,
refresh-token fields and signed 64-bit expiries. Leave device signing,
persistence gates, callbacks, metrics and HTTP presentation in place.

Protect both grant flows with real HTTP characterization before and
after extraction, plus payload boundary and serialization unit tests.
#360)

updateClientScopes sent the 200 when the last INSERT completed, before
the destructor-time COMMIT: a caller issuing an immediate grant or
scopes GET could observe the old set, and a validateClient cache miss
in that window refilled the cache with stale scopes for a full TTL.

Both success branches (empty and non-empty) now respond from the
transaction commit callback, after cache invalidation. A failed COMMIT
returns DB_QUERY_ERROR; statement failures keep their single error
response via an exactly-once responded guard (rolled-back transactions
never fire the commit callback). Insert Mappers are pre-constructed so
a construction failure leaves the transaction pristine; Mapper
construction is try/catch-wrapped per db-operations.

Regression: the write-path invalidation test asserts the DEL fired
synchronously when the 200 arrives (polling removed), and a new case
reads scopes immediately after the 200 for both branches. Positive
control: against the pre-fix implementation the new test fails 5/5
runs deterministically.

Found in the PR #348 deep review (pre-existing, not introduced by the
payload refactor); tracked in #360.
Request explicit rollback before reporting caught preparation or submission failures, including failures after the DELETE. Harden scope-order setup/readback assertions, own asynchronous promise lifetime, and verify the real transaction rollback outcome through a locking read barrier.

Fixes #360
@voidvec
voidvec force-pushed the refactor/token-success-payload-s08-b2 branch from 6f5fbce to 603f8dc Compare November 20, 2026 03:11
@voidvec
voidvec marked this pull request as ready for review November 20, 2026 03:15
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T03:16:36.621191Z 603f8dc Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@voidvec voidvec left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Code and integration review completed on this exact head. The post-DELETE preparation exception paths now explicitly and unconditionally request rollback before reporting a single failure; the normal success response stays behind COMMIT. Setup/read failures no longer masquerade as passing empty-scope tests, and timeout callbacks own shared state. The original payload extraction retains its behavior and current-master integration. Independent implementation review and full local regression passed (681 CTest; full main 767 cases / 63073 assertions; real PG/Redis and process-external endpoints). All current triggered CI checks completed successfully, including three platforms and the full-stack SDK consumer; documented strict/nightly skips are not claimed as passes. No unresolved blocking code-review findings remain. This COMMENT is a review record, not an approval: the current account is the PR author and a genuine non-author approval is still required by protection.

@voidvec
voidvec merged commit bded93a into master Nov 22, 2026
19 checks passed
voidvec added a commit that referenced this pull request Nov 22, 2026
#360)

updateClientScopes sent the 200 when the last INSERT completed, before
the destructor-time COMMIT: a caller issuing an immediate grant or
scopes GET could observe the old set, and a validateClient cache miss
in that window refilled the cache with stale scopes for a full TTL.

Both success branches (empty and non-empty) now respond from the
transaction commit callback, after cache invalidation. A failed COMMIT
returns DB_QUERY_ERROR; statement failures keep their single error
response via an exactly-once responded guard (rolled-back transactions
never fire the commit callback). Insert Mappers are pre-constructed so
a construction failure leaves the transaction pristine; Mapper
construction is try/catch-wrapped per db-operations.

Regression: the write-path invalidation test asserts the DEL fired
synchronously when the 200 arrives (polling removed), and a new case
reads scopes immediately after the 200 for both branches. Positive
control: against the pre-fix implementation the new test fails 5/5
runs deterministically.

Found in the PR #348 deep review (pre-existing, not introduced by the
payload refactor); tracked in #360.
@voidvec
voidvec deleted the refactor/token-success-payload-s08-b2 branch November 22, 2026 09:31
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.

P2: admin scopes PUT responds before transaction commit (updateClientScopes)

2 participants