Skip to content

feat: AuthForge SDK refactor - productization + reusable SDK libraries (M0-M7) - #12

Merged
voidvec merged 193 commits into
masterfrom
feat/authforge-sdk-refactor
Jul 31, 2026
Merged

voidvec merged 193 commits into
masterfrom
feat/authforge-sdk-refactor

Conversation

@voidvec

@voidvec voidvec commented Jul 30, 2026

Copy link
Copy Markdown
Owner

Summary

将全栈 OAuth2/OIDC IdP 重构为「可生产交付的产品 + 可独立复用的 SDK 组」双形态(spec: .kiro/specs/authforge-sdk-refactor,里程碑 M0–M7,187 commits):

  • SDK 化分层:libs/{common,oauth2,identity,drogon,storage-postgres,storage-redis,storage-memory} 8 静态库 + 导出头 + authforge-*Config.cmake(cmake --install 可被第三方 find_package 消费,examples/full-stack-host 冒烟验证)
  • 构建体系:全平台 Conan 2 + cmake --preset;arch-guard / naming-validator / api-diff(API 面基线冻结)/ migration-check(迁移 5 规则 + SHA-256 基线)等 CI 门禁
  • 发布管线(release.yml):严格 SemVer tag 触发;amd64/arm64 原生构建三镜像 → ghcr 多架构 manifest;SDK tarball 挂 Release;cosign keyless 按 digest 签名 + syft SPDX SBOM(三镜像 + 源码树)+ git-cliff 自动 Release notes
  • 生产交付:deploy/helm/authforge chart(迁移 = hook Job 复用 SchemaManager,--migrate-only 独立入口 + 启动 schema 自检);生产 Compose 切 ghcr 镜像 + migrate profile + 加固;F10 legacy 密码平滑升级端到端测试
  • 项目更名:oauth2-plugin-example → authforge,v1.0.0 版本冻结

Test Plan

  • 本地全套 ctest 298/298 通过(Windows MSVC Release,含 Contract/SdkSmoke 标签)
  • Helm 实跑验收(Docker Desktop K8s kind):install 应用 22 迁移 → /health/ready db+redis connected → upgrade hook 幂等 → rollback 成功
  • helm lint 0 failed;生产 Compose docker compose config 通过
  • git-cliff / release.yml YAML 本地干跑验证
  • CI 三平台(Linux/Windows/macOS)绿灯(PR 触发后确认)
  • 首次打 tag 后验证 release 端到端(GHCR 推送、arm64 原生构建、签名/SBOM/Release 附件——已知缺口,如实记录于 tasks.md)

voidvec added 30 commits July 7, 2026 20:23
- conanfile.py replaces conanfile.txt (drogon/openssl/jsoncpp/hiredis/libcurl/gtest/brotli/zlib + with_identity/with_social/with_webauthn options)
- CMakePresets.json: linux-release/windows-msvc/macos-arm64 + asan/tsan variants
- OpenSSL 3.5 migration for JwkManager::getPublicKeyComponents (EVP_PKEY_get_bn_param)
- paths.env + cmake/Paths.cmake: centralize source/build/SQL/config paths
- CI: drop source-built Drogon on all 3 platforms, use conanfile.py + Conan cache

Spec: .kiro/specs/authforge-sdk-refactor/ (M0, tasks 1-6)
- conan.lock was generated only under the Windows profile and lacked
  Linux-only transitive deps (util-linux-libuuid) and macOS-only ones
  (libiconv), causing 'not in lockfile requires' errors on Linux CI.
  Regenerated via 'conan lock create' for Linux/macOS profiles and merged
  with 'conan lock merge' so all three platforms resolve from one lockfile.
  Verified locally: conan lock create succeeds (exit 0) for Linux, macOS
  and Windows profiles against the merged lockfile.
- macos-14 runner's Python is PEP 668 externally-managed; plain
  'pip3 install conan' fails with error: externally-managed-environment.
  Added --break-system-packages (safe on ephemeral CI VM).
First round of real 3-platform CI runs surfaced two more Conan-migration
gaps not visible from Windows-only local verification:

1. drogon_ctl not on PATH at build time. drogon_create_views()/
   drogon_create_model() invoke 'drogon_ctl' as a bare command during the
   CMake build (generating login.h/consent.h from .csp templates), relying
   on it being resolvable via PATH. The old source-built Drogon was
   installed to a well-known prefix (C:\Drogon added to GITHUB_PATH on
   Windows; /usr/local via sudo make/cmake install on Linux/macOS), so this
   was implicit. Conan's drogon package bin/ dir is not on PATH by default,
   so all 3 platforms need an explicit step that reads the resolved package
   folder from CMakeDeps' Drogon-*-data.cmake and appends bin/ to
   GITHUB_PATH before the build step. Windows CI failed with MSB8066/9009
   (command not found) confirming this.

2. conan.lock was generated with an implicit Windows-as-build-machine
   profile when cross-checking Linux/macOS, causing Conan to compute
   'winflexbison' (a Windows build tool) as the flex/bison provider even
   for Linux/macOS resolution, and then reject the *actually* needed
   'flex'/'bison' packages as 'not in lockfile build_requires' once a real
   Linux/macOS runner (which has no winflexbison profile match) resolved
   dependencies natively. Regenerated per-platform lockfiles with explicit
   matching build (-s:b) and host (-s:h) profiles so each platform's real
   native toolchain is captured, then merged into one lockfile covering
   Windows (winflexbison) and Linux/macOS (flex+bison) correctly. Verified
   via 'conan lock create' (exit 0, no ERROR) for all 3 platforms and a
   real 'conan install --build=missing' on Windows.
Tasks 7-11 complete:
- Task 7: Define IClientRepository, IUserRepository, ITokenRepository, IGrantRepository, IConsentRepository, IRoleRepository, ISubjectMappingRepository interfaces
- Task 8: Split MemoryOAuth2Storage into MemoryClientRepository, MemoryUserRepository, MemoryTokenRepository, etc.
- Task 9: Split PostgresOAuth2Storage into PostgresClientRepository, PostgresUserRepository, PostgresTokenRepository, etc. with PostgresRepositoryBase
- Task 10: Split RedisOAuth2Storage into RedisClientRepository, RedisUserRepository, RedisTokenRepository, etc. with RedisRepositoryBase
- Task 11: Implement CachedClientRepository decorator with LRU caching

All 243 unit/integration tests pass with 56906 assertions on Windows.
Awaiting CI validation on Linux/macOS before proceeding to Task 12 (contract tests).
… it caught

Task 12 complete: 43 DROGON_TEST contract test cases across
IClientRepository/IGrantRepository/ITokenRepository/IConsentRepository
x Postgres/Redis/Memory, registered under CTest label Contract.

The new contract tests caught two pre-existing defects in Redis storage
(present in RedisOAuth2Storage since before the M1 split, verbatim-copied
into the new split repositories):

1. RedisClientRepository::validateClient / RedisOAuth2Storage::validateClient
   crashed the process for a nonexistent client with a non-empty secret.
   HMGET on a missing hash key returns an array of kNil elements (not a
   top-level kNil reply); the code called RedisResult::asString() on those
   elements without checking their type first, and asString() throws for
   kNil. Fixed by checking arr[0]/arr[1].type() before calling asString().

2. RedisConsentRepository::hasUserConsent / RedisOAuth2Storage::hasUserConsent
   always returned true regardless of whether the consent key existed.
   EXISTS returns an integer reply (0 or 1), never a nil reply, so the
   
esult.type() != RedisResultType::kNil check was always true. Fixed
   to check 	ype() == kInteger && asInteger() == 1.

Both fixes applied to both the new split repository and the original
god-interface class (still in the production wiring path) to avoid
diverging behavior between the two.

Verified: full suite green after fix, 290 test cases / 57038 assertions
(Windows MSVC+ASAN, Debug). Contract label alone: 45/45 passed, repeated
runs stable (no flakiness).
Linux CI caught an intermittent failure in the new
Integration_P0_Contract_Atomicity_TokenRepository_Postgres_SaveTokenPair_HappyPathBothWritesSucceed
contract test: REQUIRE(fetchedAt.has_value()) failed sporadically when
running the full single-process OAuth2Tests suite (reproduced on Linux CI,
not reproduced in isolated per-test runs or on Windows/macOS in that CI run).

Root cause: PostgresTokenRepository::saveTokenPair (and the original
PostgresOAuth2Storage::saveTokenPair it was split from) called the caller's
callback directly from the second INSERT's success callback, while still
inside the transaction. Drogon's orm::Transaction only issues the actual
'commit' SQL when the last shared_ptr reference to the Transaction object
is released (see TransactionImpl::~TransactionImpl), which happens
asynchronously after that success callback returns. This left a race
window where a caller (e.g. this repository's own dbClientReader_, or a
contract test reading via a separate connection) could read immediately
after the callback fired and observe pre-commit state under Postgres MVCC
-- both rows simply not there yet. Timing-dependent, so it only reproduced
under some schedulers/environments (Linux CI runner) and not others.

Fix: use drogon::orm::DbClient::newTransaction(commitCallback) and fire the
caller's callback from the commit callback instead of from the second
insert's success callback, guaranteeing the callback only runs after
COMMIT actually completes. Insert error paths still invoke the callback
directly, since Drogon auto-rolls-back on error and its own documentation
states the commit callback 'will never be executed' after a rollback.

Applied to both PostgresTokenRepository.cc (the new split repository) and
PostgresOAuth2Storage.cc (still in the production wiring path) to avoid
diverging behavior between the two.

Verified: full suite green, 290 test cases / 57038 assertions, 8/8
consecutive full-suite runs passed with no flakiness (Windows MSVC+ASAN,
Debug).
Task 13 complete (design.md Section 4.1/5.1/6):

- Result<T,E>: minimal std::variant-based success/error union (defaults
  to authforge::common::error::Error), header-only, no combinators
- Framework-agnostic ErrorCatalog/Error/ErrorEnvelope: ported from
  oauth2::error (25 catalog entries + 13 OAuth2 protocol codes preserved
  verbatim) with the Drogon LOG_FATAL/abort dependency replaced by
  throwing std::logic_error
- 7 value objects: Subject, Scope, ClientId, RedirectUri, PkceChallenge,
  TokenValue, TenantId -- each a thin validating wrapper eliminating bare
  std::string mixups at Domain method boundaries
- 9 port interfaces (all async/callback-shaped to match the existing
  repository convention, not synchronous): ISubjectResolver, IRoleProvider,
  IUserInfoProvider, IClock, ICryptoProvider, IUuidGenerator, ILogger,
  IEmailSender, IMetrics
- AuditEvent observability model (data struct only; the Drogon-dependent
  sink stays Adapter-side per design.md Section 3.3)
- 40 gtest unit tests (Result/value objects/ErrorCatalog), all passing
- CMake: authforge-common static lib, zero Drogon dependency (only
  jsoncpp), wired into top-level CMakeLists.txt + paths.env
  (LIBS_COMMON_DIR)

Verified: libs/common compiles standalone; grep confirms no real
#include <drogon/...> anywhere under libs/common (only design-rationale
comments mention Drogon); full existing suite (290 cases) has zero
regression; new authforge-common-test target discovered via
gtest_discover_tests and registered individually in CTest.

Additive only: OAuth2Plugin/OAuth2Server do not yet consume libs/common
(that migration is Task 14+).
…ryptoProvider/IUuidGenerator/IClock

Task 14 (design.md Section 5.6) is scoped as the highest-risk migration
(going Drogon-free in the Domain layer). Per H6 guidance ('每类端口一个 PR、
单 PR 调用点数设上限、超限即停并汇报进度'), this is slice 1 of N: the
Adapter-side default implementations only, verified byte-for-byte against
the existing drogon::utils functions they will eventually replace. Call-site
migration (CryptoUtils.h's 14 includers, PasswordHasher, TotpUtils,
JwkManager, TokenService, AuditLogger, RequestId, and Domain-layer LOG_*
macro usage) is NOT done in this slice -- it remains as Task 14 follow-up
work.

Added (OAuth2Plugin/{include,src}/adapters/, no Drogon dependency):
- OpenSslCryptoProvider: implements authforge::common::ports::ICryptoProvider
  (sha256/sha256Hex/secureRandomBytes/base64UrlEncode/base64UrlDecode/
  hmacSha256/pbkdf2HmacSha256/rsaSign), pure OpenSSL, no drogon::utils calls
- OpenSslUuidGenerator: implements IUuidGenerator (RFC 4122 v4 UUID via
  RAND_bytes + version/variant bit fixup)
- SystemClock: implements IClock (std::chrono::system_clock wrapper)

Verified via 19 new DROGON_TEST cases (OAuth2Server/test/unit/utils/
OpenSslCryptoProviderTest.cc) cross-checking byte-for-byte equivalence
against drogon::utils::getSha256/base64EncodeUnpadded and an independent
EVP_DigestVerify check for rsaSign. Full suite green: 309 test cases /
57108 assertions (Windows MSVC+ASAN, Debug), zero regression.

Found (not fixed, out of this slice's scope): oauth2::utils::sha256()
in CryptoUtils.h has a genuine pre-existing bug -- it assumes
drogon::utils::getSha256() returns lowercase hex but it actually returns
uppercase, so the hand-rolled hex-to-bytes decoder silently produces wrong
bytes for any digest containing A-F. Confirmed dead code (zero call sites
in production outside this header); the real PKCE S256 path
(TokenService::generateSha256Hash) is a separate, unaffected implementation.
Documented in the new test file rather than fixed, since CryptoUtils.h's
migration/cleanup is later Task 14 work, not this slice.

Also: wired authforge::common into OAuth2Plugin's and OAuth2Server/test's
CMakeLists.txt (PUBLIC/PRIVATE link + adapters/*.cc glob), since the new
adapter classes implement common::ports interfaces.
…on::utils::getUuid()

Slice 2 of Task 14 (design.md Section 5.6). Migrated the two production
call sites of drogon::utils::getUuid() onto the Adapter-side
OpenSslUuidGenerator (added in slice 1):

- RequestId::generate() (OAuth2Plugin/src/error/RequestId.cc)
- AuditLogger::log's HttpRequestPtr overload, fallback when the inbound
  request has no X-Request-ID header (OAuth2Plugin/src/observability/
  AuditLogger.cc)

No public signature changes -- both call sites keep their exact existing
contract (RequestId::generate()/resolve() and AuditLogger::log() are
unchanged for all ~15+ call sites across the codebase). RequestId.h keeps
its drogon/HttpRequest.h include since resolve() genuinely needs to read
an HTTP header -- that is Adapter-shaped work (design.md's Adapter layer
is explicitly allowed to depend on Drogon), not part of this port
migration's scope.

Remaining IUuidGenerator call site (out of scope for this slice, folded
into the ICryptoProvider/CryptoUtils.h migration instead):
CryptoUtils.h's generateSecureToken() fallback path
(drogon::utils::getUuid() + drogon::utils::getUuid(), used only if
secureRandomBytes() itself fails) -- migrating this one in isolation
would split generateSecureToken()'s single function across two separate
slices for no benefit; it will move together with the rest of
CryptoUtils.h's ICryptoProvider migration.

Verified: full suite green, 309 test cases / 57108 assertions (Windows
MSVC+ASAN, Debug), zero regression. RequestIdPropertyTest and
UncaughtExceptionEnvelopeTest (which exercise RequestId::generate()/
resolve() directly) pass unchanged.
…oUtils.h

Slice 3 of Task 14 (design.md Section 5.6), the highest-value part: this
header is the one design.md explicitly calls out as needing migration
across its 14 existing #include sites (TokenService, JwkManager, and 9
OAuth2Server controllers).

Every function (base64UrlEncode x2, sha256, computeCodeChallenge,
isValidCodeVerifier, isValidCodeChallenge, generateSecureToken, hashToken)
now delegates to oauth2::adapters::OpenSslCryptoProvider /
OpenSslUuidGenerator (added in slice 1) instead of drogon::utils::*. Public
API (free-function names/signatures/semantics) is UNCHANGED, so all 14
existing includers compile and link with zero call-site edits -- verified
by rebuilding the full OAuth2Test_test target, which pulls in every one of
them.

Caught and fixed a byte-compatibility risk before it shipped: initially
assumed hashToken() should switch to lowercase hex (matching its own
long-standing but stale doc comment). Realized during review that
hashToken()'s actual production role is as the EXACT-MATCH database lookup
key for access/refresh tokens (WHERE token = , not a case-insensitive
comparison like RedisClientRepository::validateClient's secret-hash check)
-- drogon::utils::getSha256() actually returns UPPERCASE hex, so every
token already persisted in a production database was hashed uppercase.
Switching to lowercase would have silently broken every token lookup
against pre-existing data. Fixed by keeping hashToken()'s output uppercase
(explicit toupper pass over ICryptoProvider::sha256Hex()'s lowercase
output), preserving exact pre-migration behavior.

Also found (documented in slice 1's test file, not fixed here -- confirmed
dead code, zero production call sites): oauth2::utils::sha256() combined
with computeCodeChallenge() has a separate pre-existing bug assuming
lowercase hex from drogon::utils::getSha256(); out of scope since nothing
calls it.

Verified: full suite green, 309 test cases / 57108 assertions (Windows
MSVC+ASAN, Debug), zero regression. All 14 CryptoUtils.h includers rebuilt
successfully with no source changes needed on their end.
…n::utils

Slice 4 of Task 14 (design.md Section 5.6).

PasswordHasher.cc:
- hash(): drogon::utils::secureRandomBytes -> OpenSslCryptoProvider::secureRandomBytes
  (salt generation for PBKDF2). PBKDF2 itself was already direct OpenSSL
  (PKCS5_PBKDF2_HMAC), untouched.
- verify()'s legacy SHA-256 path: drogon::utils::getSha256 ->
  OpenSslCryptoProvider::sha256Hex. Safe case-difference (sha256Hex returns
  lowercase vs getSha256's uppercase): this comparison already lowercases
  both sides before comparing, unlike CryptoUtils.h's hashToken() which
  needed the uppercase-preservation fix in slice 3.

TotpUtils.cc:
- generateSecret() and generateBackupCodes(): both
  drogon::utils::secureRandomBytes call sites -> OpenSslCryptoProvider::
  secureRandomBytes, same RAND_bytes fallback shape preserved.

No public signature changes. Verified: full suite green, 309 test cases /
57108 assertions (Windows MSVC+ASAN, Debug), zero regression.
…ogon::utils

Slice 5 of Task 14 (design.md Section 5.6). JwkManager's actual RS256
signing logic (EVP_DigestSignInit/Update/Final) was already direct OpenSSL
before this migration -- only its two base64UrlEncode() private helpers
called drogon::utils::base64EncodeUnpadded. Migrated both onto
OpenSslCryptoProvider::base64UrlEncode.

<drogon/drogon.h> stays included for LOG_ERROR/LOG_WARN/LOG_INFO -- that
is ILogger port scope, deliberately deferred (design.md's own H6 guidance:
one port's call sites per slice).

Verified against the existing Property4_JwkBaselineTest.cc suite (JWKS
shape, id_token shape, same-instance kid/n consistency, deterministic
RS256 re-signing, randomized-claims round trip) -- all pass unchanged, so
JWKS/id_token output is confirmed byte-for-byte compatible with the
pre-migration base64url encoding. Full suite green: 309 test cases /
57108 assertions (Windows MSVC+ASAN, Debug), zero regression.
…ff drogon::utils

Slice 6 of Task 14 (design.md Section 5.6). Migrated
TokenService::generateSha256Hash (the PKCE S256 verification hash used by
validatePkceCodeVerifier) off drogon::utils::getSha256/base64Encode onto
OpenSslCryptoProvider, preserving its exact byte-for-byte pre-migration
output including the uppercase-hex intermediate step (getSha256 returned
uppercase; this function base64-encodes the hex STRING's ASCII bytes, not
the decoded digest, so hex case directly changes the output).

Verified via a new golden test (Unit_TokenService_GenerateSha256Hash_
MatchesPreMigrationAlgorithm) that reproduces the exact pre-migration
algorithm inline via drogon::utils and compares byte-for-byte against the
migrated production function across 5 inputs including an empty-string
edge case. Also re-ran the existing Unit_P0_PKCE_Legacy_Hashing test
(passes unchanged).

*** FLAGGING A PRE-EXISTING PRODUCTION DEFECT FOUND WHILE MIGRATING (NOT
FIXED, OUT OF THIS TASK'S SCOPE) ***
generateSha256Hash() does not implement RFC 7636 Section 4.2's
code_challenge = BASE64URL(SHA256(ASCII(code_verifier))). RFC 7636 requires
base64url-encoding the RAW 32 SHA-256 DIGEST BYTES; this function instead
base64url-encodes the ASCII TEXT of the 64-character hex digest STRING --
a completely different value for any given input. This means any
standard-conformant PKCE client (browser SDKs, mobile SDKs, standard OAuth2
libraries) computing code_challenge per the RFC will FAIL S256
verification against this server. This is invisible in the current test
suite because the one existing PKCE test (P0FunctionalityTest.cc's
Unit_P0_PKCE_Legacy_Hashing) is self-consistent: it generates the
challenge via this same non-conformant function and validates via the
same function, so it round-trips regardless of RFC conformance.

This defect existed before this migration (confirmed by reproducing the
exact pre-migration algorithm and diffing byte-for-byte, not introduced by
it) and is deliberately preserved as-is here, since fixing a PKCE protocol
interoperability bug is out of scope for a 'remove drogon::utils
dependency' task and would be an unauthorized, unreviewed behavior change.
Recommend opening a dedicated bugfix task to evaluate real-world impact
(deployed clients may already be relying on generateSha256Hash's exact
behavior if they were built to match this server rather than the RFC) and
plan a compatibility-safe fix (e.g. versioned/config-gated rollout) before
changing it.

Verified: full suite green, 310 test cases / 57113 assertions (Windows
MSVC+ASAN, Debug), zero regression.
…nService LOG_* off Drogon macros

Slice 7 of Task 14 (design.md Section 5.6): the ILogger port.

Added oauth2::adapters::DrogonLogger -- the Adapter-side default
implementation of authforge::common::ports::ILogger, forwarding to
Drogon's own LOG_* macros. Unlike OpenSslCryptoProvider/OpenSslUuidGenerator/
SystemClock, this Adapter implementation DOES depend on Drogon
(<drogon/drogon.h>) -- that is correct and expected, since design.md's
port table says the default ILogger implementation is 'Drogon 日志适配'.

Migrated call sites (all 10 LOG_* macros in JwkManager.cc, 2 of 2 in
TokenService.cc):
- JwkManager.cc: all init()/loadFromPem()/signJwt() logging. This file now
  has ZERO drogon:: symbol usage and no <drogon/...> include at all --
  fully Domain-shaped (previously only base64UrlEncode's drogon::utils
  dependency was migrated, in slice 5; this removes the remaining LOG_*
  dependency).
- TokenService.cc: the two LOG_WARN security-event sites (PKCE-less PUBLIC
  client, refresh-token-reuse detection).

Scope decision -- what was deliberately NOT migrated in this slice:
- AuditLogger.cc's 4 LOG_* sites: examined and intentionally left alone.
  This file is fundamentally Adapter-shaped code (drogon::app().
  getDbClient(), drogon::orm::DrogonDbException, drogon::HttpRequestPtr
  throughout) -- swapping just its LOG_* calls to ILogger would not make
  it Domain-layer-clean (it still depends on Drogon's DB/HTTP types for
  its actual job) and would be cosmetic progress, not real Task 14 value.
  Design.md groups audit *sinks* under the Adapter layer (Section 3.3:
  '导出器 -> 适配器'), consistent with leaving this file's Drogon
  dependency as-is until M3's Adapter-layer reorganization.
- TokenService.cc still calls drogon::app().getCustomConfig() (issuer
  lookup) and TokenService.h still includes <drogon/drogon.h> -- neither
  is LOG_* scope; config access would need its own port (not requested by
  design.md's current port table) and is out of scope here.

Verified: full suite green, 310 test cases / 57113 assertions (Windows
MSVC+ASAN, Debug), zero regression. JWKS/id_token baseline tests
(Property4_3_3_*) re-verified passing unchanged.
Slice 8 of Task 14 (design.md Section 5.6). Migrated all 4 remaining
LOG_* macro call sites in AuditLogger.cc onto the ILogger port
(DrogonLogger, same pattern as JwkManager.cc/TokenService.cc).

Reconsidered the scope decision from slice 7 (where this file's LOG_*
migration was deferred): design.md Section 5.6 explicitly names AuditLogger
as one of the ILogger call sites to migrate ('AuditLogger、RequestId'),
so completing it keeps Task 14 aligned with the design document's own
listed scope rather than second-guessing it. This does NOT change the
file's overall Adapter-shaped nature: drogon::app().getDbClient(),
drogon::orm::DrogonDbException, and drogon::HttpRequestPtr remain
untouched (that DB/HTTP dependency is a separate architectural concern for
a later M2a/M3 audit-sink split, not something Task 14's LOG_*/
drogon::utils migration is meant to address) -- only the logging calls
were swapped, which is the actual scope design.md's port table describes.

Verified: full suite green, 310 test cases / 57113 assertions (Windows
MSVC+ASAN, Debug), zero regression.
…of every port

Task 15 complete (design.md Section 6/8: '端口的 Adapter 实现 + 假实现(测试
用)... 生产实现放 Adapter;假实现放测试支持库').

New dedicated library libs/common/testing (authforge::common::testing),
separate from BOTH libs/common (ports only, no implementations) and
OAuth2Plugin's production Adapter implementations (OpenSslCryptoProvider/
OpenSslUuidGenerator/SystemClock/DrogonLogger, added in Task 14). This
three-way split matters because:
- Production binaries must never link test doubles.
- This library depends only on libs/common + OpenSSL, NOT OAuth2Plugin
  (which depends on Drogon) -- so future standalone Domain packages
  (libs/oauth2, libs/identity, M2b/M2.5) can use these fakes for
  deterministic unit tests without ever pulling in Drogon, which is the
  actual acceptance criterion: 'Domain 可用假时钟/假 crypto 做确定性单测'.

Added one fake per common::ports interface declared in Task 13:
- FakeClock: controllable time (setSeconds/advanceSeconds), never
  advances on its own -- drives expiry-boundary logic deterministically.
- FakeCryptoProvider: only secureRandomBytes() is actually faked
  (deterministic seeded xorshift64*, not a real CSPRNG); every other
  method (sha256/sha256Hex/base64url/hmacSha256/pbkdf2HmacSha256/rsaSign)
  is a REAL OpenSSL implementation, since faking pure hash/HMAC/signing
  functions would provide no test value (their output is already a
  deterministic function of input). Verified rsaSign produces a
  signature that independently verifies via EVP_DigestVerify.
- FakeUuidGenerator: sequential predictable ids ('fake-uuid-0', ...).
- FakeLogger: captures every log() call for assertion (level + message).
- FakeEmailSender: captures sent messages, configurable success/failure.
- FakeSubjectResolver / FakeRoleProvider / FakeUserInfoProvider: in-memory
  lookup tables for the oauth2<->identity decoupling ports (§5.2), ready
  for M2b's libs/oauth2 Domain tests once that package exists.
- FakeMetrics: captures counter/gauge/histogram samples.

38 new gtest unit tests (all passing), one file per fake, proving each
behaves deterministically and (for FakeCryptoProvider) that its real
crypto primitives are correct against known test vectors (e.g. SHA-256
FIPS 180-2 'abc' vector).

Verified: full suite green -- 124 total CTest cases (1 OAuth2Tests + 40
authforge-common-test + 38 authforge-common-testing-test + 45 Contract),
zero regression. Confirmed zero #include <drogon/...> anywhere under
libs/common/testing.
…ll against memory-only config crash

Found while validating Task 16's "manage build/test 可用" acceptance
criterion by running the full local test.bat two-config cycle (standard
config.json with Postgres+Redis, then config.ci.json with
storage_type=memory and empty db_clients/redis_clients arrays).

Root cause: getPostgresClientOrNull()/getRedisClientOrNull() (Task 12's
contract test fixtures) only had a try/catch around
drogon::app().getDbClient()/getRedisClient(), following half of the
pre-existing skip pattern from OAuth2Server/test/integration/storage/
{Postgres,Redis}StorageTest.cc. The other half of that pattern -- checking
plugin->getStorageType() == "memory" BEFORE ever calling getDbClient()/
getRedisClient() -- was missing. When redis_clients/db_clients is an empty
array (the memory-only run), Drogon's
drogon::nosql::RedisClientManager::getRedisClient() hits an internal
assert(redisClientsMap_.find(name) != redisClientsMap_.end()) -- an
uncatchable, process-terminating assert(), not a throw -- so the try/catch
never had a chance to run. This crashed the entire OAuth2Tests process
partway through the memory-only test run, taking down every contract test
that runs after the first Postgres/Redis contract test in registration
order along with it (looked like scattered unrelated failures/hangs when
observed via ctest's per-case timing, but was actually one crashed
process).

Fix: add the same storage-type guard the pre-existing StorageTest.cc files
already use, checked before the try/catch, in both fixture functions.

Verified: full two-config manage.ps1 test-backend cycle now passes
cleanly -- standard config.json (124/124 CTest cases, Postgres+Redis
reachable) and config.ci.json (memory-only, all Postgres/Redis contract
cases correctly skip with 0 assertions instead of crashing) both report
PASS. Confirmed via a clean full rebuild of the traditional (non-preset)
build/ directory that manage.ps1 build-backend/test-backend both work end
to end, satisfying Task 16's acceptance criterion.
Task 16 acceptance criteria verified via manage.ps1 build-backend/test-backend
full cycle on the traditional (non-preset) build/ directory:
- libs/common and libs/common/testing build cleanly alongside
  OAuth2Plugin/OAuth2Server (paths.env's LIBS_COMMON_DIR/
  LIBS_COMMON_TESTING_DIR keys parse correctly through all three existing
  loaders: bash source, PowerShell Import-PathsEnv, batch paths_env.bat --
  no script changes needed since M2a only added new directories, did not
  move/rename any existing path).
- Existing DROGON_TEST runner preserved unchanged (OAuth2Test_test still
  the single test binary; new libs/common and libs/common/testing tests
  run as separate gtest binaries via CTest, not mixed into the DROGON_TEST
  binary).
- Both existing manage.ps1 test-backend configs (standard config.json
  Postgres+Redis, and config.ci.json memory-only) pass cleanly end to end
  after the ContractFixtures.h crash fix (previous commit).
…xecution

Records milestone/task completion status, per-slice details for Task 14's
8-slice drogon::utils removal, discovered-but-not-fixed pre-existing
defects (PKCE RFC 7636 non-compliance in TokenService::generateSha256Hash,
dead-code hex-case bug in CryptoUtils.h's sha256()), local environment
notes (drogon_ctl PATH requirement, local Redis vs Docker conflict), and
next-step plan (M2b Task 17-18). Intended to let a future session /
context-compaction recover full state without re-reading every prior
commit message.
- New libs/oauth2 (authforge::oauth2) target: pure-function PKCE (RFC 7636)
  module (computeCodeChallenge/verifyCodeVerifier/isValidCodeVerifierFormat/
  isValidCodeChallengeFormat), depending only on libs/common (value objects
  + ICryptoProvider port). Zero Drogon dependency, zero OAuth2Plugin
  dependency (dependency direction is the other way per design.md).
- Wired into top-level build: paths.env gains LIBS_OAUTH2_DIR=libs/oauth2;
  CMakeLists.txt adds add_subdirectory(...) alongside libs/common, following
  the same pattern/ordering.
- New authforge-oauth2-test (gtest, mirrors libs/common/test's pattern: pure
  unit tests, no DB/no Drogon, not the DROGON_TEST framework) -- 13 tests
  including the exact RFC 7636 Appendix B known-answer vector, verified
  against FakeCryptoProvider's real OpenSSL-backed SHA-256/base64url (not a
  stub).
- Deliberately implements the CORRECT S256 algorithm (base64url of raw
  digest bytes), independent of and unaffected by the pre-existing
  TokenService::generateSha256Hash RFC 7636 non-conformance discovered in
  Task 14 (recorded in PROGRESS.md) -- no production code calls this module
  yet; wiring TokenService/AuthorizationService to use it is a later slice.

Verified: full solo + full-suite build (cmake --build build/windows-msvc-asan)
succeeds; ctest -C Debug run of all 137 registered tests (including the new
13 PkceTest cases at #79-91) passes 100%, zero regression.

This is slice 1 of Task 17 (M2b). Remaining slices: AuthorizationService/
TokenService migration, access/ (consent+scope decision engine), model/
aggregates, and the M1 repository interfaces (IClientRepository/
IGrantRepository/ITokenRepository/IConsentRepository) migrating into
authforge::oauth2.
…odel

- New libs/oauth2/include/authforge/oauth2/model/ClientType.h: ports
  oauth2::ClientType + string<->enum helpers (OAuth2Plugin/include/
  oauth2/types/OAuth2Types.h). GrantType/OAuth2Error deliberately NOT
  ported -- Task 13 already gave OAuth2 protocol error codes a superseding
  home in authforge::common::error::ErrorCatalog; porting the old enum
  here would create a second, competing error representation.
- New libs/oauth2/include/authforge/oauth2/model/Dto.h: ports
  OAuth2Client/OAuth2AuthCode/OAuth2AccessToken/OAuth2RefreshToken/
  TokenIntrospection/AuthorizationTransaction verbatim (fields unchanged)
  from their current home nested inside OAuth2Plugin/include/oauth2/
  storage/IOAuth2Storage.h -- design.md explicitly names that header (not
  OAuth2Types.h) as the Task 17 migration source. TokenIntrospection::
  toJson() ported as-is (Json::Value/jsoncpp is allowed in the Domain
  layer per design.md §4.1 rule 1).
- Deliberately NOT wrapping fields in value objects yet (Scope/ClientId/
  RedirectUri/PkceChallenge/TokenValue per design.md's Data Models table)
  -- that requires touching every production call site and is a separate,
  larger slice, mirroring Task 14's call-site-by-call-site discipline.
  This slice only relocates the plain-struct shape.
- 9 new gtest cases (ClientType round-trip/invalid-input, DTO default
  values, TokenIntrospection::toJson's RFC 7662 active/inactive field
  emission). authforge-oauth2-test now has 22 tests total (13 Pkce + 9
  Dto). Confirms jsoncpp is available transitively via authforge::common
  without needing a direct libs/oauth2 find_package(jsoncpp) call.
- Purely additive: IOAuth2Storage.h untouched, no production call site
  switched yet.

Verified: full build (cmake --build build/windows-msvc-asan) succeeds;
ctest -C Debug 146/146 tests pass, zero regression.
…ge::oauth2::repository

- New libs/oauth2/include/authforge/oauth2/model/UserRef.h: ports
  oauth2::UserRef (OAuth2Plugin/include/oauth2/storage/UserRef.h)
  unchanged -- the F4 opaque-user-reference placeholder IConsentRepository
  uses instead of exposing identity's internalUserId.
- New libs/oauth2/include/authforge/oauth2/repository/{IClientRepository,
  IGrantRepository,ITokenRepository,IConsentRepository}.h: port the 4 M1
  repository interfaces, now depending on authforge::oauth2::model's DTOs
  (Task 17 slice 2) instead of the old oauth2::* DTOs via IOAuth2Storage.h
  -- fully decoupled from OAuth2Plugin. Method shapes, docs, the
  saveTokenPair default sequential body, the supportsTransactions()/
  supportsCas() capability-flag contract, and the deliberate omission of
  purgeExpired() on IClientRepository/IConsentRepository are all carried
  over unchanged from the originals (see each header's comment for the
  specific rationale pointers).
- New RepositoryInterfacesTest.cc: 5 gtest cases using minimal in-memory
  fakes to prove each interface is usable through a base-class pointer
  (virtual dispatch), plus one behavioral assertion on
  ITokenRepository::saveTokenPair's default body (verifies it calls
  saveAccessToken then saveRefreshToken sequentially without an override).
  These are interface-shape tests, NOT full contract tests -- the existing
  OAuth2Server/test/contract/* suite continues exercising the
  OAuth2Plugin-side implementations until a later slice switches them
  over. authforge-oauth2-test now has 27 tests total.
- Purely additive: OAuth2Plugin's IClientRepository/IGrantRepository/
  ITokenRepository/IConsentRepository/UserRef and their existing Memory/
  Redis/Postgres implementations are untouched; there are now two parallel
  sets of these 4 interfaces (OAuth2Plugin's oauth2:: namespace and this
  new authforge::oauth2:: namespace) until a later slice migrates the
  concrete implementations over and retires the old ones.

Verified: full build (cmake --build build/windows-msvc-asan) succeeds;
ctest -C Debug 151/151 tests pass, zero regression.
…ervice::generateSha256Hash

On explicit user instruction, after confirming the fix cost is low: the
SPA frontend does not use PKCE yet (PRD/mfa_auth_code_pkce_design.md
Section 6.1's own audit confirms this), so no deployed client depends on
the old, non-conformant value.

- TokenService::generateSha256Hash now delegates to
  authforge::oauth2::pkce::computeCodeChallenge(input, 'S256', crypto)
  (the spec-correct implementation added in Task 17 slice 1) instead of
  base64-encoding the ASCII text of the hex digest string. RFC 7636 §4.2:
  code_challenge = BASE64URL(SHA256(ASCII(code_verifier))) -- base64url of
  the raw digest bytes.
- OAuth2Plugin now links authforge::oauth2 (correct dependency direction:
  Adapter-layer OAuth2Plugin depends on Domain-layer libs/oauth2, not the
  reverse). OAuth2Server/test also links authforge::oauth2 since its
  OAuth2Test_test binary compiles TokenService.cc directly.
- OpenSslCryptoProviderTest.cc: replaced the golden test that pinned the
  OLD (buggy) byte sequence
  (Unit_TokenService_GenerateSha256Hash_MatchesPreMigrationAlgorithm) with
  two tests asserting the NEW correct behavior:
  Unit_TokenService_GenerateSha256Hash_IsRfc7636Conformant (reimplements
  the correct algorithm independently and compares) and
  Unit_TokenService_GenerateSha256Hash_MatchesRfc7636AppendixBVector
  (cross-checks against the same RFC 7636 Appendix B known-answer vector
  libs/oauth2/test/PkceTest.cc already asserts for
  oauth2::pkce::computeCodeChallenge directly).
- P0FunctionalityTest.cc's Unit_P0_PKCE_Legacy_Hashing needed no change:
  it is self-consistent (generates+validates via the same function) and
  passes regardless of which conformant algorithm is used underneath.

Verified: full build (cmake --build build/windows-msvc-asan) succeeds;
ctest -C Debug 151/151 pass; OAuth2Test_test.exe directly run shows all
311 DROGON_TEST cases / 57114 assertions passing (was 310 cases before
this commit's 1 new test); authforge-oauth2-test 27/27 pass. Zero
regression.
Unblocks TokenService's Domain migration: TokenService currently calls
oauth2::observability::AuditLogger::log() directly, which depends on
drogon::app().getDbClient()/drogon::orm::DrogonDbException -- something
libs/oauth2 (Domain layer) must not depend on (design.md §4.1 rule 1).
design.md §3.3 splits Observability as 'model -> common, sink -> Adapter'
and Task 13 already ported the AuditEvent model, but no port existed yet
for the sink side (no Domain code needed to emit an audit event at the
time).

- New libs/common/include/authforge/common/ports/IAuditSink.h: small,
  generic port (one record() method taking the already-common
  AuditEvent), mirroring IMetrics.h's shape/rationale rather than porting
  AuditLogger's own hard-coded method names.
- New libs/common/testing/include/authforge/common/testing/
  FakeAuditSink.h: capturing test double, mirrors FakeLogger.h's pattern.
  4 new gtest cases in FakeAuditSinkTest.cc.
- New OAuth2Plugin/include/oauth2/adapters/DrogonAuditSink.h +
  src/adapters/DrogonAuditSink.cc: thin Adapter-side production
  implementation that translates authforge::common::observability::
  AuditEvent to the pre-existing oauth2::observability::AuditEvent and
  forwards to AuditLogger::log() field-for-field. AuditLogger itself is
  untouched (no duplicate DB-writing logic).
- Purely additive: no production call site wired to this port yet (that
  is part of the TokenService migration this unblocks).

Verified: full build (cmake --build build/windows-msvc-asan) succeeds;
ctest -C Debug 155/155 pass, zero regression.
…gregates

design.md's Data Models table names three oauth2::model aggregates
(Client / AuthorizationGrant / TokenPair) that were not yet created --
Task 17 slice 2 only ported the underlying plain DTOs (OAuth2Client/
AuthorizationTransaction/OAuth2AccessToken+OAuth2RefreshToken).

- New model/Client.h: thin wrapper around OAuth2Client adding
  isRegisteredRedirectUri()/allowsScope()/allowsAllScopes() -- membership
  checks call sites currently duplicate ad hoc (e.g. TokenService.cc's
  raw clientType==PUBLIC checks) as linear std::find loops.
- New model/AuthorizationGrant.h: thin wrapper around
  AuthorizationTransaction adding isExpired()/hasPkceChallenge()/
  verifyPkceCodeVerifier() -- the latter delegates to
  oauth2::pkce::verifyCodeVerifier (Task 17 slice 1), giving grants a
  single verification entry point instead of callers manually threading
  codeChallenge/codeChallengeMethod through validatePkceCodeVerifier.
- New model/TokenPair.h: thin wrapper around OAuth2AccessToken +
  OAuth2RefreshToken that VALIDATES the pairing invariant at construction
  (refreshToken.accessToken must reference accessToken.token; clientId/
  userId must match) -- an invariant every production call site
  (TokenService::exchangeCodeForToken/refreshAccessToken) already relies
  on by convention but never checks explicitly.
- All three are deliberately thin wrappers (hold the DTO by value, do not
  re-model fields as value objects) -- consistent with Dto.h's own
  decision to defer full value-object wrapping to a separate slice.
- 14 new gtest cases in AggregateTest.cc, including a PKCE round-trip
  through AuthorizationGrant::verifyPkceCodeVerifier using the RFC 7636
  Appendix B vector, and all 4 TokenPair invariant-violation cases.
  authforge-oauth2-test now has 41 tests total.
- Purely additive: no production call site uses these aggregates yet.

Verified: full build (cmake --build build/windows-msvc-asan) succeeds;
ctest -C Debug 169/169 pass, zero regression.
…engine

design.md's directory layout names an access/ module ('consent + scope
分层策略 + 决策引擎') that did not exist yet -- the existing production
logic implements this same three-tier decision (client allowlist -> admin
role -> user consent) as an implicit sequence of separate service calls
(ClientService::validateClientScopes, IdentityService::
validateUserRolesForScopes + scopeRequiresAdminRole,
OAuth2StandardController::checkUserConsentAndProceed's recursive
hasUserConsent walk) rather than a single typed decision.

- New access/ScopeDecision.h: ScopeDecision enum (Valid/Invalid/
  ConsentRequired), ScopeCheckResult (single-scope outcome +
  machine-readable reason code), ScopeValidationSummary (aggregated
  result with canProceed()/needsConsent()/hasErrors() helpers). Mirrors
  the shape of a previously-drafted-but-never-implemented design
  (docs/design/superpowers/.../oauth2-security-compliance-design-v5.1.md's
  ScopeValidationStatus/ScopeCheckResult/ScopeValidationSummary) with a
  fresh Domain-layer (Drogon-free) implementation -- not a copy of that
  draft's code, which targeted the old undivided IOAuth2Storage.
- New access/ScopeDecisionEngine.h/.cc: isAdminScope() reproduces
  IdentityService::scopeRequiresAdminRole's exact hardcoded scope list
  and prefix-match semantics; evaluateScope()/evaluateScopes() implement
  the pure, synchronous 3-tier evaluation (client allowlist -> admin role
  -> consent), deliberately NOT performing the async I/O itself (role/
  consent lookup stays the caller's job, e.g. a future
  AuthorizationService) -- this keeps the engine trivially unit-testable
  and lets the async orchestration strategy change independently.
  evaluateScopes() reproduces the existing short-circuit behavior:
  consent is never checked for a scope already Invalid on tiers 1-2.
- 18 new gtest cases (isAdminScope exact/prefix/negative matches, all 3
  per-scope decision outcomes, summary aggregation including the
  short-circuit and empty-list cases). authforge-oauth2-test now has 54
  tests total.
- Purely additive: no production call site uses this engine yet (wiring
  it into AuthorizationService, once that service is created, is a later
  slice).

Verified: full build (cmake --build build/windows-msvc-asan) succeeds;
ctest -C Debug 182/182 pass, zero regression.
voidvec added 17 commits July 29, 2026 17:59
…Task 28a)

Packaging foundation: add cmake/AuthForgePackage.cmake helper (authforge_package) + AuthForgePackageConfig.cmake.in template. All 8 SDK packages (common, common-testing, oauth2, identity, storage-{memory,redis,postgres}, drogon) now emit both install-tree (lib/cmake/<pkg>/) and build-tree (\/authforge-cmake/<pkg>/) Config+ConfigVersion+Targets with find_dependency closures. Fixes export name to canonical authforge::<alias> (was authforge::authforge-<pkg>) via per-target EXPORT_NAME.

Full-stack smoke: add examples/full-stack-host (standalone project, not add_subdirectory) that consumes the entire product stack via find_package(authforge-drogon CONFIG) from the build-tree, reuses apps/server bootstrap + OrganizationController + drogon_create_views(apps/server/views), boots a real HTTP server on a memory backend (hermetic) and asserts route registration, config-driven OAuth2Plugin instantiation, login.csp view rendering, and auth-code flow entry.

CTest: register SdkSmoke.FullStack via ctest --build-and-test (forwards Conan toolchain + CMAKE_PREFIX_PATH), labelled SdkSmoke (satisfies M8 Task 39). Verified: configure clean, full build green, SdkSmoke.FullStack passes 100% on Windows/MSVC Release.
…gating (Task 32)

Replace the three standalone ci-{linux,windows,macos}.yml files with one
orchestrator (ci.yml) plus three workflow_call reusable workflows, chained as
serial fail-fast needs gates:

- FAST gate: static-checks (source-only arch-guard/naming/parity/OpenAPI) +
  frontend (_frontend.yml, vitest error-mapping property tests, run once)
- MAIN gate: build-test (_build-test.yml x {linux,windows,macos} matrix) --
  a single parameterized job body; underscore-only input names avoid '-' being
  parsed as subtraction; Linux uses real Postgres/Redis via docker run gated on
  use_database (matrix-conditionable, unlike service containers), Windows/macOS
  use memory config; Req 12.7 named gates controlled by run_named_test_gates
  (Linux+Windows only), behavior unchanged
- RELEASE gate: sdk-smoke (_sdk-smoke.yml, Linux only, ctest -L SdkSmoke)

Also add workflow_dispatch + concurrency cancel-in-progress, and fix the stale
performance-report upload path (build/tests -> \/tests).
The docker-run migration (0ddb623) dropped the service containers' health gate; the wait loop then ended with 'sleep 2' (exit 0), so an unready Postgres/Redis passed silently. Probe readiness with a real 'psql SELECT 1' (pg_isready can pass during postgres:15-alpine's temporary init server), exit 1 on timeout, and dump container logs for diagnosis.
…ctivate naming gate

- Rename 130 non-compliant DROGON_TEST names across 30 .cc files to [Category]_[Priority]_[Module]_[Feature]_[Scenario] (PropertyN token moves to the Feature slot; priorities assigned per family)
- Fix naming_validator.sh: default to tests/, multiline-aware extraction (grep -rzoP) that survives clang-format wrapping and skips comment mentions; ci.yml static-checks now passes tests explicitly
- Sync all references: _build-test.yml -r gate names, TSan/ASan findings docs, mfa spec naming-convention text, sdk-refactor tasks.md, pr6-review-fixes-plan.md
- CategoryC_ASanFindings.md: annotate 11 removed repro tests as historical record (names intentionally left as-is)
- Verified: zero old-name residue, validator PASS + negative-case FAIL, Release build OK, all 30 -r gate names reachable in binary, ctest 296/296 passed, workflow YAML parse OK
… 43)

- backend-builder: drop in-container Drogon source build + bare cmake;
  reuse scripts/backend/build.sh Release (conan install + cmake
  --preset linux-release + drogon_ctl PATH wiring) so the container
  build cannot drift from host/CI; add BuildKit cache mount for
  /root/.conan2 so transient network failures don't restart hours of
  --build=missing dependency compilation
- backend-base: install cmake via pip alongside conan (apt cmake 3.22
  cannot read the Conan-generated CMakeUserPresets.json schema v4)
- backend-runtime: binary now from build/linux-release/apps/server/;
  apt runtime lib list recomputed from in-image ldd - Conan links
  everything statically, only ca-certificates + curl remain
- docker-quick-verify-debug.sh: sync stale Drogon-header check (conan)
  and build dir (build/linux-debug)
- .gitattributes: pin paths.env to LF (CRLF Windows checkout broke
  'source paths.env' inside the image with \$'\r': command not found)

Verified: image builds, ldd clean, docker compose up backend
/health + /health/ready both 200 (database connected).
Pure formatting (line wrapping) - no semantic changes. Long
DROGON_TEST names from the naming normalization now wrap onto
their own lines per .clang-format column limit.
…ty.yml)

- tools/migration-check/migration_check.py: 5 rules (M1 strict V<NNN> naming,
  M2 unique+contiguous versions, M3 idempotency, M4 forward-only non-destructive,
  M5 sha256 immutability baseline) covering assumptions SchemaManager and the
  CI psql glob rely on but never verify; comments/strings/dollar-quoted bodies
  stripped before matching; baseline.json committed (22 migrations, LF-normalized)
- tools/security/dependency_eol_check.py: conan.lock requires+overrides vs
  offline policy floors (openssl>=3.0, zlib>=1.2.13, libcurl>=8.4.0)
- .github/workflows/security.yml: dependency-eol + secret-hygiene jobs,
  push/PR + weekly cron + dispatch
- ci.yml FAST gate: add migration-check step after arch-guard

Verified: 22 existing migrations pass clean; 8 injected violation classes and
a fake openssl/1.1.1w lock all exit 1; both workflows yaml-parse clean.
- rename root project() oauth2-plugin-example -> authforge
- README/README.zh-CN: AuthForge title, ci.yml+security.yml badges,
  compose command with deploy path, admin port 8081, footer v1.0.0;
  drop stale hardcoded test counts (kept scope descriptions only)
- CLAUDE/CODEBUDDY: rewrite Storage Strategy to RepositoryBundle +
  separate identity backing store; update Layer Separation
- add docs/backend/sdk-runtime-contract.md (F9 thread/ABI/exception/
  logging/deps contracts + H1 plugin registration / whole-archive)
- frontends: fix crossAppConsistency dynamic-import candidates to
  ../../../admin/... (broken since M8 rename); normalize
  OAuth2Frontend/OAuth2Admin comment references in 7 files
- admin package.json+lock version 0.0.0 -> 1.0.0
- docs/backend: fix stale OAuth2Server/OAuth2Frontend/OAuth2Admin
  paths in ci-cd/api-reference/testing/docker guides

Verified: user vitest 15/15 (incl. cross-app 2), admin vitest 2/2,
cmake --preset windows-msvc reconfigure OK, zero old-name residue.
- tools/api-diff/api_diff.py: declaration-skeleton snapshot of the 164
  exported SDK headers (libs/*/include, 7 libs); comment/body stripping
  keeps impl-only edits silent while signature/default-arg/include
  changes trip the guard
- ADDITIVE vs BREAKING classification; --update-baseline refuses
  breaking drift unless the major version was bumped (or --force)
- cross-checks cmake/Version.cmake vs root CMakeLists vs conanfile.py
- wired into ci.yml FAST gate after migration-check
- verified: clean pass 164 headers; additive/breaking/refuse/version-
  drift negatives all firing; comment+body edits produce zero drift
- release.yml: strict SemVer tag trigger (v1.2.3 only) + dispatch dry-run
  * version-check: tag == cmake/Version.cmake + api-diff surface freeze
  * sdk-package: cmake --install tarball (8 libs + headers + cmake
    configs) validated by building examples/full-stack-host against the
    INSTALLED prefix; conan cache key gains runner.arch dimension
  * images: backend/frontend/admin x {amd64, arm64} on NATIVE runners
    (ubuntu-24.04-arm instead of QEMU), pushed as <ver>-<arch> to ghcr
  * manifest: imagetools merge -> <ver> + latest multi-arch tags
  * github-release: SDK tarball + sha256 attached
- docs/backend/sdk-integration-guide.md: artifact list, ABI caveats,
  find_package walkthrough, whole-archive stance calibrated to the
  OBJECT-lib reality, image usage, maintainer release steps
- README/README.zh-CN: link SDK integration guide + runtime contract
- verified locally: YAML parses; cmake --install (windows tree) yields
  8 libs + 8 config sets + 174 headers matching the documented layout
…on runner (Task 37, F10)

- authforge-server --migrate-only: standalone migration entrypoint with real
  exit codes; startup schema self-check when OAUTH2_AUTO_MIGRATE=false
  (LOG_ERROR only, no crashloop during rolling upgrades); auto-migrate
  failure now exits instead of serving traffic on a half-migrated schema
- SchemaManager: unify checksum on OpenSslCryptoProvider::sha256Hex
  (replaces non-Windows std::hash placeholder; output identical to the old
  BCrypt path); add migrate(db, dir) overload + countPendingMigrations
- deploy/helm/authforge: 16-resource chart; migrations as hook Job with
  hook-scoped config/secret copies (shared helpers prevent drift) and
  conditional hook events (built-in PG: post-install, external: pre-install);
  fixed-name alias Service oauth2-backend for the hardcoded nginx upstream;
  values-local.yaml for Docker Desktop kind acceptance
- docker-compose.prod.yml: ghcr image refs, AUTO_MIGRATE=false by default,
  one-shot migrate profile service, resource limits, prometheus on loopback
- F10: two end-to-end migration-compat tests (re-login after rehash via
  PBKDF2, wrong password leaves legacy hash untouched); identity 85/85

Acceptance on Docker Desktop K8s (kind): install applies all 22 migrations,
/health/ready db+redis connected, upgrade re-runs hook idempotently,
rollback to rev 1 succeeds.
…s (Task 38)

- manifest job: cosign keyless (GitHub OIDC, id-token: write) signs the
  three multi-arch manifests by digest; syft v1.19.0 generates SPDX JSON
  SBOMs per image from the pushed manifests
- github-release job: source-tree SBOM (conan.lock + frontend lockfiles),
  release notes via git-cliff (--latest, cliff.toml) replacing
  --generate-notes, verification instructions appended to the notes,
  all SBOMs attached as release assets
- cliff.toml: conventional-commit grouping into Keep a Changelog sections;
  strict SemVer tag_pattern matching release.yml's trigger; spec/release
  chore commits skipped. CHANGELOG.md stays curated -- maintainers prepend
  locally before tagging (documented in sdk-integration-guide §6)

Validated locally: release.yml YAML parse, git-cliff 2.13.1 dry run over
full history, notes heredoc rendering under bash. End-to-end run awaits
the first real tag (same gap as Task 36).
@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.

voidvec and others added 5 commits July 30, 2026 23:08
…ke_minimum_required with presets (3.21)

- libs/common, libs/oauth2, apps/server: MSVC-only PRIVATE _CRT_SECURE_NO_WARNINGS
  (same pattern as tests/; never leaks into exported SDK interface)
- root CMakeLists: 3.10 -> 3.21 to match CMakePresets.json cmakeMinimumRequired
- AuthorizationService.cc: drop unused exception binding (C4101)
- READMEs (en/zh, line-aligned): drop PRD/ from tree, add examples/deploy/tests,
  remove dead PRD link, CMake requirement 3.20+ -> 3.23+
- ops docs: OAuth2Server/sql/* -> apps/server/{migrations,seed},
  OAuth2Frontend -> frontends/user, OAuth2Plugin/src -> libs/drogon/src,
  OAuth2Admin -> frontends/admin
- api-reference.md: ErrorCatalog.h path in intro note (table rows untouched;
  ErrorCatalogDoc tests pass)
- scripts/backend/README: ci-linux/macos/windows.yml -> ci.yml + _build-test.yml
- security-check.sh: match only files literally named .env (paths.env is a
  legit tracked file); exact-line match so frontends/user/.env.example no
  longer trips the frontends/user/.env check; tolerate CRLF .gitignore on
  Windows checkouts
- .gitignore: OAuth2Frontend/.env -> frontends/user/.env (post-rename) and
  add frontends/user/public/config.json required by the gate

Fixes the 3 errors in the 'Secret & Sensitive-File Hygiene' job on PR #12.
Three consecutive Linux CI runs failed with the same signature: loopback
requests (127.0.0.1:5555) timing out at exactly 10s during the first ~40s
of the test binary, with the failing case drifting between runs
(MfaCrossClientAuthFix Property1/5/6, DeviceCodeClientAuth, PKCE
passthrough). Windows/macOS skip these (memory storage), so only the
Linux+Postgres leg is exposed to the 2-core runner contention. 30s keeps
well under the 120s ctest timeout while absorbing the startup-window
stalls.
…outs

The Linux+Postgres CI leg kept failing 3 integration cases
(MfaCrossClientAuthFix Property1/Property6, AuthorizePkce passthrough) with
0 != nullptr — loopback HTTP requests to the in-process server returning
after the 30s client timeout, then EDEADLK at teardown. Commit a9841d3
raised the client timeout 10s->30s but the failures persisted and "drifted
between runs", which rules out a logic bug and points to resource
contention.

Root cause: config sets app.number_of_threads=0 -> hardware_concurrency()
= 2 IO threads on the 2-core runner. The embedded server, the test
thread, and the DB pool thread contend for the same 2 cores; during the
dense integration-test window an IO worker is starved past the client
budget, so sendRequest times out and the helper returns nullptr. Win/macOS
(memory storage) never hit it.

Fix 1 (_build-test.yml): add a step gated on inputs.use_database that
patches the EPHEERAL work-copy build/<preset>/tests/config.json (the copy
the binary loads) to set number_of_threads=4, giving the HTTP listener
headroom independent of core count. The repo's apps/server/config/config.json
is never modified.

Fix 3 (Property1 test): move the in-flow blocking sync
UPDATE...mfa_pending_*=NULL out of the test body into a pre-flow
clearAdminPendingBinding() helper, so no blocking sync DB call interleaves
with the loopback requests. The indispensable mid-state readPendingBinding()
reads and all fixtures are left intact (the project's own TestBase.h uses
execSqlSync, so the promise/future pattern is the accepted idiom; Fix 1
carries the load).

Verified locally: build-backend succeeds; the refactored Property1 case
passes via -r. Authoritative 2-core contention check is the Linux CI leg
(re-run 2-3x to confirm determinism).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@voidvec
voidvec merged commit b455e6d into master Jul 31, 2026
8 checks passed
@voidvec
voidvec deleted the feat/authforge-sdk-refactor branch July 31, 2026 06:17
voidvec added a commit that referenced this pull request Aug 30, 2026
…loor, bootstrap self-heal, review cleanups

Address PR #141 review (1 must-fix, 8 should-fix, quick considers):

- #1 consent_csrf declared as a required query parameter in openapi.yaml
  and the C++ endpoint doc registration; apps/server/docs/api/openapi.json
  regenerated from a live server run; Python/Go clients regenerated.
- #2 nonce one-shot is now atomic: the find/verify/erase sequence is
  serialized by a process-wide mutex (consent traffic is tiny; in-process
  session storage).
- #3 identity AuthService no longer captures this in the async validateUser
  callback — the legacy-hash policy flag is value-captured
  (db-operations rule 4).
- #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin
  user row is reused and role/mapping completed (partial failures self-heal
  on restart); the random password is printed only after the insert
  succeeded; a mapping failure no longer reports created=true.
- #5 POST /api/admin/users enforces auth.min_password_length
  (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass.
- #6 consent integration tests reworked: missing-nonce now drives the real
  authorize-minted slot (400), deny-to-unregistered-uri (400, no Location)
  and deny-to-registered-uri (302 access_denied) branches are covered.
- #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT
  removed (PBKDF2 keeps salt empty); website i18n error table mirrored
  (3014/4007).
- #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on
  failure instead of a single silent 2s probe.
- #13 unique-violation detection layered (SqlError 23505 -> constraint
  name -> english/zh localized text), mirroring the
  PostgresSocialAccountRepository pattern.
- #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged;
  #17 AGENTS.md consent.csp entry removed.

Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14
admin UI hardcode (server now enforces; hint stays), #18 MFA-pending
session through consent (pre-existing authorize behavior, tracked).
voidvec added a commit that referenced this pull request Aug 30, 2026
…loor, bootstrap self-heal, review cleanups

Address PR #141 review (1 must-fix, 8 should-fix, quick considers):

- #1 consent_csrf declared as a required query parameter in openapi.yaml
  and the C++ endpoint doc registration; apps/server/docs/api/openapi.json
  regenerated from a live server run; Python/Go clients regenerated.
- #2 nonce one-shot is now atomic: the find/verify/erase sequence is
  serialized by a process-wide mutex (consent traffic is tiny; in-process
  session storage).
- #3 identity AuthService no longer captures this in the async validateUser
  callback — the legacy-hash policy flag is value-captured
  (db-operations rule 4).
- #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin
  user row is reused and role/mapping completed (partial failures self-heal
  on restart); the random password is printed only after the insert
  succeeded; a mapping failure no longer reports created=true.
- #5 POST /api/admin/users enforces auth.min_password_length
  (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass.
- #6 consent integration tests reworked: missing-nonce now drives the real
  authorize-minted slot (400), deny-to-unregistered-uri (400, no Location)
  and deny-to-registered-uri (302 access_denied) branches are covered.
- #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT
  removed (PBKDF2 keeps salt empty); website i18n error table mirrored
  (3014/4007).
- #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on
  failure instead of a single silent 2s probe.
- #13 unique-violation detection layered (SqlError 23505 -> constraint
  name -> english/zh localized text), mirroring the
  PostgresSocialAccountRepository pattern.
- #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged;
  #17 AGENTS.md consent.csp entry removed.

Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14
admin UI hardcode (server now enforces; hint stays), #18 MFA-pending
session through consent (pre-existing authorize behavior, tracked).
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