From 2b00ebbf0e1c7f9288270b45f0f238d1b5b88051 Mon Sep 17 00:00:00 2001 From: fulla-dev Date: Tue, 1 Dec 2026 08:38:41 +0000 Subject: [PATCH] feat(oauth2): add RFC 9207 iss parameter, Redis refresh token persistence, and RFC 6750 form bearer support --- .../AuthorizationEndpointController.cc | 40 ++- .../src/controllers/DiscoveryController.cc | 4 + .../src/controllers/SessionController.cc | 14 + libs/drogon/src/filters/OAuth2AuthFilter.cc | 18 +- .../storage-redis/src/RedisTokenRepository.cc | 286 +++++++++++++++--- tests/contract/TokenRepositoryContractTest.cc | 10 +- .../integration/token/RfcGapAFeaturesTest.cc | 185 +++++++++++ 7 files changed, 497 insertions(+), 60 deletions(-) create mode 100644 tests/integration/token/RfcGapAFeaturesTest.cc diff --git a/libs/drogon/src/controllers/AuthorizationEndpointController.cc b/libs/drogon/src/controllers/AuthorizationEndpointController.cc index 076fdd85d..0dac2dd7d 100644 --- a/libs/drogon/src/controllers/AuthorizationEndpointController.cc +++ b/libs/drogon/src/controllers/AuthorizationEndpointController.cc @@ -32,7 +32,8 @@ ::drogon::HttpResponsePtr buildAuthorizeErrorRedirect( const std::string &redirectUri, const std::string &error, const std::string &description, - const std::string &state + const std::string &state, + const std::string &issuer = "" ) { // Each value belongs to the verified callback query, not a complete URI. @@ -43,6 +44,8 @@ ::drogon::HttpResponsePtr buildAuthorizeErrorRedirect( location += "&error_description=" + ::drogon::utils::urlEncodeComponent(description); if (!state.empty()) location += "&state=" + ::drogon::utils::urlEncodeComponent(state); + if (!issuer.empty()) + location += "&iss=" + ::drogon::utils::urlEncodeComponent(issuer); return ::drogon::HttpResponse::newRedirectionResponse(location); } } // namespace @@ -387,7 +390,8 @@ void AuthorizationEndpointController::authorize( redirectUri, "invalid_request", "code_challenge_method 'plain' is not allowed; use S256", - state + state, + plugin->getIssuer() ) ); return; @@ -400,7 +404,8 @@ void AuthorizationEndpointController::authorize( "invalid_request", "code_challenge_method is required when code_challenge is " "present (S256)", - state + state, + plugin->getIssuer() ) ); return; @@ -412,7 +417,8 @@ void AuthorizationEndpointController::authorize( redirectUri, "invalid_request", "code_challenge_method must be 'S256'", - state + state, + plugin->getIssuer() ) ); return; @@ -431,7 +437,8 @@ void AuthorizationEndpointController::authorize( redirectUri, "invalid_request", "code_challenge must be 43-128 characters of [A-Za-z0-9-._~]", - state + state, + plugin->getIssuer() )); return; } @@ -499,7 +506,8 @@ void AuthorizationEndpointController::authorize( redirectUri, "login_required", "prompt=none requested but no fully authenticated session", - state + state, + plugin->getIssuer() )); return; } @@ -753,7 +761,7 @@ void AuthorizationEndpointController::authorize( { error = "access_denied"; } - callback(buildAuthorizeErrorRedirect(redirectUri, error, desc, state)); + callback(buildAuthorizeErrorRedirect(redirectUri, error, desc, state, plugin->getIssuer())); return; } @@ -773,7 +781,8 @@ void AuthorizationEndpointController::authorize( redirectUri, "consent_required", "prompt=none requested but user interaction (consent) is required", - state + state, + plugin->getIssuer() )); return; } @@ -891,7 +900,8 @@ void AuthorizationEndpointController::authorize( redirectUri, "invalid_request", "PKCE (code_challenge) is required", - state + state, + plugin->getIssuer() ) ); return; @@ -908,9 +918,10 @@ void AuthorizationEndpointController::authorize( codeChallenge, codeChallengeMethod, nonce, - [redirectUri, state, callback = std::move(callback)]( + [plugin, redirectUri, state, callback = std::move(callback)]( bool success, std::string code, std::string error ) mutable { + const std::string issuer = plugin ? plugin->getIssuer() : ""; if (!success) { LOG_ERROR << "Failed to generate authorization code: " << error; @@ -921,20 +932,23 @@ void AuthorizationEndpointController::authorize( redirectUri, "server_error", "Failed to generate authorization code", - state + state, + issuer ) ); return; } - // F-020 (RFC 6749 §4.1.2/§4.1.3): urlEncode the - // code and state so special chars survive the query. + // F-020 (RFC 6749 §4.1.2/§4.1.3) + RFC 9207 section 2: + // urlEncode code, state, and iss. std::string location = redirectUri + ::fulla::drogon::utils::authorizeUrlQuerySeparator(redirectUri) + "code=" + ::drogon::utils::urlEncodeComponent(code); if (!state.empty()) location += "&state=" + ::drogon::utils::urlEncodeComponent(state); + if (!issuer.empty()) + location += "&iss=" + ::drogon::utils::urlEncodeComponent(issuer); auto resp = ::drogon::HttpResponse::newRedirectionResponse(location); if (auto m = ::drogon::app().getPlugin<::OAuth2Plugin>()->getMetrics()) m->incrementCounter( diff --git a/libs/drogon/src/controllers/DiscoveryController.cc b/libs/drogon/src/controllers/DiscoveryController.cc index faa65a8cd..acd6a29ab 100644 --- a/libs/drogon/src/controllers/DiscoveryController.cc +++ b/libs/drogon/src/controllers/DiscoveryController.cc @@ -283,6 +283,8 @@ void DiscoveryController::metadata( // advertised. metadata["code_challenge_methods_supported"] = Json::Value(Json::arrayValue); metadata["code_challenge_methods_supported"].append("S256"); + // RFC 9207 section 3: authorization responses carry the iss parameter. + metadata["authorization_response_iss_parameter_supported"] = true; // Client authentication methods metadata["token_endpoint_auth_methods_supported"] = Json::Value(Json::arrayValue); @@ -369,6 +371,8 @@ void DiscoveryController::oidcDiscovery( // P0-5 (#259): S256-only — plain is no longer accepted at authorize and // is no longer advertised. discovery["code_challenge_methods_supported"].append("S256"); + // RFC 9207 section 3: authorization responses carry the iss parameter. + discovery["authorization_response_iss_parameter_supported"] = true; // F-022 (OIDC Core §3.1.2.1 / §5.1): advertise prompt/max_age support and // the auth_time/acr/amr claims the id_token now carries. diff --git a/libs/drogon/src/controllers/SessionController.cc b/libs/drogon/src/controllers/SessionController.cc index 2722f6e7a..a2bc6ceb6 100644 --- a/libs/drogon/src/controllers/SessionController.cc +++ b/libs/drogon/src/controllers/SessionController.cc @@ -107,6 +107,8 @@ void sendOAuthErrorRedirect( location += "&error_description=" + ::drogon::utils::urlEncodeComponent(description); if (!state.empty()) location += "&state=" + ::drogon::utils::urlEncodeComponent(state); + if (auto *p = ::drogon::app().getPlugin<::OAuth2Plugin>(); p && !p->getIssuer().empty()) + location += "&iss=" + ::drogon::utils::urlEncodeComponent(p->getIssuer()); if (jsonMode) { Json::Value ret; @@ -1087,6 +1089,9 @@ void SessionController::login( "code=" + ::drogon::utils::urlEncodeComponent(code); if (!state.empty()) location += "&state=" + ::drogon::utils::urlEncodeComponent(state); + if (auto *p = ::drogon::app().getPlugin<::OAuth2Plugin>(); + p && !p->getIssuer().empty()) + location += "&iss=" + ::drogon::utils::urlEncodeComponent(p->getIssuer()); if (req->getParameter("json") == "true") { Json::Value ret; @@ -1186,6 +1191,9 @@ void SessionController::login( "code=" + ::drogon::utils::urlEncodeComponent(code); if (!state.empty()) location += "&state=" + ::drogon::utils::urlEncodeComponent(state); + if (auto *p = ::drogon::app().getPlugin<::OAuth2Plugin>(); + p && !p->getIssuer().empty()) + location += "&iss=" + ::drogon::utils::urlEncodeComponent(p->getIssuer()); if (req->getParameter("json") == "true") { Json::Value ret; @@ -1524,6 +1532,9 @@ void SessionController::consent( "error=access_denied&error_description=User+denied+consent"; if (!state.empty()) location += "&state=" + ::drogon::utils::urlEncodeComponent(state); + if (auto *p = ::drogon::app().getPlugin<::OAuth2Plugin>(); + p && !p->getIssuer().empty()) + location += "&iss=" + ::drogon::utils::urlEncodeComponent(p->getIssuer()); if (jsonMode) { Json::Value ret; @@ -1728,6 +1739,9 @@ void SessionController::consent( "code=" + ::drogon::utils::urlEncodeComponent(code); if (!state.empty()) location += "&state=" + ::drogon::utils::urlEncodeComponent(state); + if (auto *p = ::drogon::app().getPlugin<::OAuth2Plugin>(); + p && !p->getIssuer().empty()) + location += "&iss=" + ::drogon::utils::urlEncodeComponent(p->getIssuer()); if (jsonMode) { // Same envelope as the /oauth2/login json=true path; diff --git a/libs/drogon/src/filters/OAuth2AuthFilter.cc b/libs/drogon/src/filters/OAuth2AuthFilter.cc index 486e45ab6..b0416e5be 100644 --- a/libs/drogon/src/filters/OAuth2AuthFilter.cc +++ b/libs/drogon/src/filters/OAuth2AuthFilter.cc @@ -39,8 +39,22 @@ void fulla::drogon::filters::OAuth2AuthFilter::doFilter( return; } + std::string token; auto authHeader = req->getHeader("Authorization"); - if (authHeader.empty() || authHeader.substr(0, 7) != "Bearer ") + if (!authHeader.empty() && authHeader.rfind("Bearer ", 0) == 0) + { + token = authHeader.substr(7); + } + else if ( + req->method() == Post && req->path() == "/oauth2/userinfo" && + req->contentType() == CT_APPLICATION_X_FORM + ) + { + // OIDC Core 5.3.1 + RFC 6750 2.2: allow form-encoded body + // access_token on POST /oauth2/userinfo (never URL query params). + token = req->getParameter("access_token"); + } + if (token.empty()) { LOG_WARN << "OAuth2AuthFilter: Missing or invalid Authorization header"; auto error = fulla::common::error::Error::fromCode( @@ -52,8 +66,6 @@ void fulla::drogon::filters::OAuth2AuthFilter::doFilter( return; } - std::string token = authHeader.substr(7); - // Async Token Validation plugin->validateAccessToken( token, diff --git a/libs/storage-redis/src/RedisTokenRepository.cc b/libs/storage-redis/src/RedisTokenRepository.cc index 5cba5c008..73c0e7950 100644 --- a/libs/storage-redis/src/RedisTokenRepository.cc +++ b/libs/storage-redis/src/RedisTokenRepository.cc @@ -2,6 +2,7 @@ #include #include #include +#include #include namespace fulla::storage::redis @@ -163,18 +164,146 @@ void RedisTokenRepository::getAccessToken(const std::string &token, AccessTokenC ); } -// Verbatim preservation of RedisOAuth2Storage's no-op: Redis mode never -// actually stored/retrieved refresh tokens. -void RedisTokenRepository::saveRefreshToken(const OAuth2RefreshToken & /*token*/, VoidCallback &&cb) +void RedisTokenRepository::saveRefreshToken(const OAuth2RefreshToken &token, VoidCallback &&cb) { - if (cb) - cb(); + if (!redisClient_) + { + if (cb) + cb(); + return; + } + Json::Value val; + val["access_token"] = token.accessToken; + val["client_id"] = token.clientId; + val["user_id"] = token.userId; + val["scope"] = token.scope; + val["expires_at"] = (Json::Int64)token.expiresAt; + val["revoked"] = token.revoked; + val["family_id"] = token.familyId; + if (token.orgId.has_value()) + { + val["org_id"] = (Json::Int64)*token.orgId; + } + + const std::string jsonStr = jsonToString(val); + const auto nowSec = static_cast( + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch() + ) + .count() + ); + const int64_t ttl = (token.expiresAt > nowSec) ? (token.expiresAt - nowSec) : 1; + const std::string key = "oauth2:refresh:" + token.token; + const std::string ttlStr = std::to_string(ttl); + auto sharedCb = std::make_shared(std::move(cb)); + + redisClient_->execCommandAsync( + [self = shared_from_this(), familyId = token.familyId, tokHash = token.token, ttlStr, + sharedCb](const RedisResult &) { + if (familyId.empty() || !self->redisClient_) + { + if (*sharedCb) + (*sharedCb)(); + return; + } + const std::string famKey = "oauth2:family:" + familyId; + self->redisClient_->execCommandAsync( + [self, famKey, ttlStr, sharedCb](const RedisResult &) { + self->redisClient_->execCommandAsync( + [sharedCb](const RedisResult &) { + if (*sharedCb) + (*sharedCb)(); + }, + [sharedCb](const RedisException &) { + if (*sharedCb) + (*sharedCb)(); + }, + "EXPIRE %s %s", + famKey.c_str(), + ttlStr.c_str() + ); + }, + [sharedCb](const RedisException &e) { + LOG_WARN << "RedisTokenRepository: failed to index refresh family: " << e.what(); + if (*sharedCb) + (*sharedCb)(); + }, + "SADD %s %s", + famKey.c_str(), + tokHash.c_str() + ); + }, + [sharedCb](const RedisException &e) { + LOG_ERROR << "RedisTokenRepository: saveRefreshToken failed: " << e.what(); + if (*sharedCb) + (*sharedCb)(); + }, + "SETEX %s %s %s", + key.c_str(), + ttlStr.c_str(), + jsonStr.c_str() + ); } -void RedisTokenRepository::getRefreshToken(const std::string & /*token*/, RefreshTokenCallback &&cb) +void RedisTokenRepository::getRefreshToken(const std::string &token, RefreshTokenCallback &&cb) { - if (cb) - cb(std::nullopt); + if (!redisClient_) + { + if (cb) + cb(std::nullopt); + return; + } + const std::string key = "oauth2:refresh:" + token; + auto sharedCb = std::make_shared(std::move(cb)); + redisClient_->execCommandAsync( + [sharedCb, tokenStr = token](const RedisResult &result) { + if (result.type() == RedisResultType::kNil) + { + if (*sharedCb) + (*sharedCb)(std::nullopt); + return; + } + auto json = parseJson(result.asString()); + if (json.isNull() || !json.isObject()) + { + if (*sharedCb) + (*sharedCb)(std::nullopt); + return; + } + OAuth2RefreshToken rt; + rt.token = tokenStr; + rt.accessToken = json["access_token"].asString(); + rt.clientId = json["client_id"].asString(); + rt.userId = json["user_id"].asString(); + rt.scope = json["scope"].asString(); + rt.expiresAt = json["expires_at"].asInt64(); + rt.revoked = json["revoked"].asBool(); + rt.familyId = json["family_id"].asString(); + if (json.isMember("org_id")) + rt.orgId = json["org_id"].asInt(); + + const auto nowSec = static_cast( + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch() + ) + .count() + ); + if (rt.revoked || rt.expiresAt <= nowSec) + { + if (*sharedCb) + (*sharedCb)(std::nullopt); + return; + } + if (*sharedCb) + (*sharedCb)(rt); + }, + [sharedCb](const RedisException &) { + if (*sharedCb) + (*sharedCb)(std::nullopt); + }, + "GET %s", + key.c_str() + ); } void RedisTokenRepository::revokeRefreshToken(const std::string &token, VoidCallback &&cb) @@ -186,19 +315,57 @@ void RedisTokenRepository::revokeRefreshToken(const std::string &token, VoidCall return; } + const std::string key = "oauth2:refresh:" + token; + auto sharedCb = std::make_shared(std::move(cb)); redisClient_->execCommandAsync( - [cb](const RedisResult &) { - if (cb) - cb(); + [self = shared_from_this(), key, sharedCb](const RedisResult &result) { + if (result.type() == RedisResultType::kNil || !self->redisClient_) + { + if (*sharedCb) + (*sharedCb)(); + return; + } + auto json = parseJson(result.asString()); + if (json.isNull() || !json.isObject()) + { + if (*sharedCb) + (*sharedCb)(); + return; + } + json["revoked"] = true; + const std::string updated = jsonToString(json); + const auto nowSec = static_cast( + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch() + ) + .count() + ); + const int64_t exp = json["expires_at"].asInt64(); + const int64_t ttl = (exp > nowSec) ? (exp - nowSec) : 3600; + const std::string ttlStr = std::to_string(ttl); + self->redisClient_->execCommandAsync( + [sharedCb](const RedisResult &) { + if (*sharedCb) + (*sharedCb)(); + }, + [sharedCb](const RedisException &e) { + LOG_ERROR << "Failed to persist revoked refresh token in Redis: " << e.what(); + if (*sharedCb) + (*sharedCb)(); + }, + "SETEX %s %s %s", + key.c_str(), + ttlStr.c_str(), + updated.c_str() + ); }, - [cb](const RedisException &e) { + [sharedCb](const RedisException &e) { LOG_ERROR << "Failed to revoke refresh token in Redis: " << e.what(); - // Call callback even on failure to avoid blocking - if (cb) - cb(); + if (*sharedCb) + (*sharedCb)(); }, - "HSET oauth2_refresh_tokens:%s revoked 1", - token.c_str() + "GET %s", + key.c_str() ); } @@ -207,33 +374,64 @@ void RedisTokenRepository::atomicRevokeRefreshToken( RefreshTokenCallback &&cb ) { - // Redis doesn't have native CAS, but we can use HSETNX-like logic - // For simplicity, get then set (acceptable for Redis single-threaded model) - // NOTE (see supportsCas() == false rationale in the header): this is a - // genuinely non-atomic two-step even setting aside the fact that - // getRefreshToken() is currently a no-op below. + // Non-atomic GET-then-SETEX; supportsCas() remains false per header contract. getRefreshToken( - token, [self = shared_from_this(), this, token, cb = std::move(cb)](auto rt) mutable { + token, [self = shared_from_this(), token, cb = std::move(cb)](auto rt) mutable { if (!rt || rt->revoked) { cb(std::nullopt); return; } auto captured = *rt; - revokeRefreshToken(token, [cb = std::move(cb), captured]() { cb(captured); }); + self->revokeRefreshToken(token, [cb = std::move(cb), captured]() { cb(captured); }); } ); } void RedisTokenRepository::revokeTokenFamily(const std::string &familyId, VoidCallback &&cb) { - // Redis doesn't support efficient family queries without secondary indexes - // For production Redis usage, maintain a SET of tokens per family - // For now, just log and callback (family tracking is primarily for Postgres) - LOG_WARN << "[SECURITY] Token family revocation requested for: " << familyId - << " (Redis: limited support)"; - if (cb) - cb(); + if (!redisClient_ || familyId.empty()) + { + if (cb) + cb(); + return; + } + const std::string famKey = "oauth2:family:" + familyId; + auto sharedCb = std::make_shared(std::move(cb)); + redisClient_->execCommandAsync( + [self = shared_from_this(), familyId, sharedCb](const RedisResult &result) { + if (result.type() != RedisResultType::kArray) + { + if (*sharedCb) + (*sharedCb)(); + return; + } + auto members = result.asArray(); + if (members.empty()) + { + if (*sharedCb) + (*sharedCb)(); + return; + } + auto remaining = std::make_shared>(members.size()); + for (const auto &member : members) + { + const std::string rtHash = member.asString(); + self->revokeRefreshToken(rtHash, [remaining, sharedCb]() { + if (remaining->fetch_sub(1) == 1 && *sharedCb) + (*sharedCb)(); + }); + } + }, + [sharedCb, familyId](const RedisException &e) { + LOG_WARN << "RedisTokenRepository: revokeTokenFamily failed for " << familyId << ": " + << e.what(); + if (*sharedCb) + (*sharedCb)(); + }, + "SMEMBERS %s", + famKey.c_str() + ); } // ========== P1: Token Introspection (RFC 7662) ========== @@ -253,12 +451,30 @@ void RedisTokenRepository::introspectToken( std::string key = "oauth2:token:" + token; redisClient_->execCommandAsync( - [cb](const RedisResult &result) { + [self = shared_from_this(), rawToken = token, cb](const RedisResult &result) { if (result.type() == RedisResultType::kNil) { - TokenIntrospection introspection; - introspection.active = false; - cb(introspection); + // Fallback to refresh token key (RFC 7662 2.1). + self->getRefreshToken( + rawToken, + [cb](std::optional rt) { + TokenIntrospection introspection; + if (!rt) + { + introspection.active = false; + cb(introspection); + return; + } + introspection.active = true; + introspection.clientId = rt->clientId; + introspection.tokenType = "Refresh"; + introspection.exp = rt->expiresAt; + introspection.sub = rt->userId; + introspection.scope = rt->scope; + introspection.orgId = rt->orgId; + cb(introspection); + } + ); return; } diff --git a/tests/contract/TokenRepositoryContractTest.cc b/tests/contract/TokenRepositoryContractTest.cc index c76be6645..6cd643f87 100644 --- a/tests/contract/TokenRepositoryContractTest.cc +++ b/tests/contract/TokenRepositoryContractTest.cc @@ -244,15 +244,7 @@ DROGON_TEST( return; auto repo = std::make_shared("default"); - const std::string rtToken = "contract-rt-noop-" + uniqueSuffix(); - auto rt = makeRefreshToken(rtToken, "contract-at-for-rt-noop", "fulla-portal"); - - waitForVoid([&](auto cb) { repo->saveRefreshToken(rt, std::move(cb)); }); - - auto fetched = waitForValue>([&](auto cb) { - repo->getRefreshToken(rtToken, std::move(cb)); - }); - CHECK(!fetched.has_value()); + runTokenRepository_RefreshTokenSaveGetRoundTripContract(TEST_CTX, repo, "fulla-portal"); } // =========================================================================== diff --git a/tests/integration/token/RfcGapAFeaturesTest.cc b/tests/integration/token/RfcGapAFeaturesTest.cc new file mode 100644 index 000000000..6b2a4a41a --- /dev/null +++ b/tests/integration/token/RfcGapAFeaturesTest.cc @@ -0,0 +1,185 @@ +// tests/integration/token/RfcGapAFeaturesTest.cc +// +// Functional & regression tests for Gap A RFC compliance features: +// - RFC 9207: authorization_response_iss_parameter_supported in both +// RFC 8414 metadata and OIDC discovery documents. +// - RFC 9207: iss query parameter included on authorization redirects. +// - RFC 6750 2.2 + OIDC Core 5.3.1: OAuth2AuthFilter accepts form-encoded +// access_token on POST /oauth2/userinfo while rejecting GET query tokens. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace drogon; + +namespace +{ + +bool parseJson(const HttpResponsePtr &resp, Json::Value &out) +{ + if (!resp) + return false; + const std::string body(resp->getBody()); + Json::CharReaderBuilder builder; + const std::unique_ptr reader(builder.newCharReader()); + std::string errs; + return reader->parse(body.data(), body.data() + body.size(), &out, &errs); +} + +std::unique_ptr makeGapAMemoryPlugin() +{ + auto plugin = std::make_unique(); + Json::Value cfg; + cfg["storage_type"] = "memory"; + cfg["tokens"]["auth_code_ttl"] = 600; + cfg["tokens"]["access_token_ttl"] = 3600; + cfg["tokens"]["refresh_token_ttl"] = 86400; + + Json::Value client; + client["client_type"] = "PUBLIC"; + client["token_endpoint_auth_method"] = "none"; + client["redirect_uri"] = "https://rp.example.com/callback"; + client["allowed_scopes"].append("openid"); + client["allowed_scopes"].append("profile"); + cfg["clients"]["gap-a-client"] = client; + + plugin->initAndStart(cfg); + return plugin; +} + +} // namespace + +DROGON_TEST(Integration_P0_Rfc9207_Discovery_AdvertisesIssParameterSupported) +{ + auto plugin = makeGapAMemoryPlugin(); + fulla::drogon::controllers::DiscoveryController ctrl; + ctrl.setPlugin(plugin.get()); + + // 1. RFC 8414 /.well-known/oauth-authorization-server + auto metaReq = HttpRequest::newHttpRequest(); + metaReq->setMethod(Get); + metaReq->setPath("/.well-known/oauth-authorization-server"); + std::promise pMeta; + ctrl.metadata(metaReq, [&pMeta](const HttpResponsePtr &r) { pMeta.set_value(r); }); + auto metaResp = pMeta.get_future().get(); + REQUIRE(metaResp != nullptr); + CHECK(metaResp->getStatusCode() == k200OK); + Json::Value metaJson; + REQUIRE(parseJson(metaResp, metaJson)); + CHECK(metaJson["authorization_response_iss_parameter_supported"].asBool() == true); + + // 2. OIDC Discovery /.well-known/openid-configuration + auto oidcReq = HttpRequest::newHttpRequest(); + oidcReq->setMethod(Get); + oidcReq->setPath("/.well-known/openid-configuration"); + std::promise pOidc; + ctrl.oidcDiscovery(oidcReq, [&pOidc](const HttpResponsePtr &r) { pOidc.set_value(r); }); + auto oidcResp = pOidc.get_future().get(); + REQUIRE(oidcResp != nullptr); + CHECK(oidcResp->getStatusCode() == k200OK); + Json::Value oidcJson; + REQUIRE(parseJson(oidcResp, oidcJson)); + CHECK(oidcJson["authorization_response_iss_parameter_supported"].asBool() == true); +} + +DROGON_TEST(Integration_P0_Rfc9207_AuthorizeErrorRedirect_IncludesIssParameter) +{ + auto plugin = makeGapAMemoryPlugin(); + fulla::drogon::controllers::AuthorizationEndpointController ctrl; + ctrl.setPlugin(plugin.get()); + + auto req = HttpRequest::newHttpRequest(); + req->setMethod(Get); + req->setPath("/oauth2/authorize"); + req->setParameter("response_type", "code"); + req->setParameter("client_id", "gap-a-client"); + req->setParameter("redirect_uri", "https://rp.example.com/callback"); + req->setParameter("scope", "openid"); + req->setParameter("state", "12345678"); + req->setParameter("prompt", "none"); + + std::promise p; + ctrl.authorize(req, [&p](const HttpResponsePtr &r) { p.set_value(r); }); + auto resp = p.get_future().get(); + REQUIRE(resp != nullptr); + CHECK(resp->getStatusCode() == k302Found); + + const std::string location = resp->getHeader("Location"); + CHECK(location.find("error=login_required") != std::string::npos); + CHECK(location.find("state=12345678") != std::string::npos); + + const std::string expectedIss = + "iss=" + ::drogon::utils::urlEncodeComponent(plugin->getIssuer()); + CHECK(location.find(expectedIss) != std::string::npos); +} + +DROGON_TEST(Integration_P0_Rfc6750_OAuth2AuthFilter_AcceptsPostUserinfoFormToken) +{ + auto plugin = makeGapAMemoryPlugin(); + const std::string rawToken = "gap-a-form-bearer-token-value"; + fulla::oauth2::model::OAuth2AccessToken at; + at.token = fulla::drogon::utils::hashToken(rawToken); + at.clientId = "gap-a-client"; + at.userId = "sub-user-123"; + at.scope = "openid profile"; + const auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch() + ) + .count(); + at.issuedAt = now; + at.notBefore = now; + at.expiresAt = now + 3600; + at.issuer = plugin->getIssuer(); + + std::promise saved; + plugin->saveAccessToken(at, [&saved]() { saved.set_value(); }); + saved.get_future().get(); + + fulla::drogon::filters::OAuth2AuthFilter filter; + filter.setPlugin(plugin.get()); + + // 1. POST /oauth2/userinfo with form-encoded access_token passes filter + auto postReq = HttpRequest::newHttpRequest(); + postReq->setMethod(Post); + postReq->setPath("/oauth2/userinfo"); + postReq->setContentTypeCode(CT_APPLICATION_X_FORM); + postReq->setParameter("access_token", rawToken); + + std::promise postPassed; + filter.doFilter( + postReq, + [&postPassed](const HttpResponsePtr &) { postPassed.set_value(false); }, + [&postPassed]() { postPassed.set_value(true); } + ); + CHECK(postPassed.get_future().get() == true); + CHECK(postReq->getAttributes()->get("userId") == "sub-user-123"); + CHECK(postReq->getAttributes()->get("scope") == "openid profile"); + + // 2. GET /oauth2/userinfo with query access_token is rejected (RFC 9700) + auto getReq = HttpRequest::newHttpRequest(); + getReq->setMethod(Get); + getReq->setPath("/oauth2/userinfo"); + getReq->setParameter("access_token", rawToken); + + std::promise getDenied; + filter.doFilter( + getReq, + [&getDenied](const HttpResponsePtr &r) { getDenied.set_value(r); }, + [&getDenied]() { getDenied.set_value(nullptr); } + ); + auto getResp = getDenied.get_future().get(); + REQUIRE(getResp != nullptr); + CHECK(getResp->getStatusCode() == k401Unauthorized); +}