diff --git a/apps/server/docs/api/openapi.json b/apps/server/docs/api/openapi.json index b093e3762..c9f2f503d 100644 --- a/apps/server/docs/api/openapi.json +++ b/apps/server/docs/api/openapi.json @@ -5167,6 +5167,16 @@ { "type" : "string" } + }, + { + "description" : "RFC 8707 resource indicator (optional, all grants): binds the issued access token's audience (introspection aud) to this absolute URI, overriding the default aud = client id. Malformed values are rejected with invalid_target.", + "in" : "query", + "name" : "resource", + "required" : false, + "schema" : + { + "type" : "string" + } } ], "responses" : diff --git a/apps/server/openapi.yaml b/apps/server/openapi.yaml index 097405412..af7a863bd 100644 --- a/apps/server/openapi.yaml +++ b/apps/server/openapi.yaml @@ -1133,6 +1133,13 @@ components: type: string description: Required for the device_code grant (from /oauth2/device_authorization). + resource: + type: string + description: 'RFC 8707 §2.1 resource indicator (optional, all grants): + an absolute URI (scheme required, no fragment, max 255 chars) + that the issued access token''s audience (introspection `aud`) + is bound to, overriding the default aud = client id. A malformed + indicator is rejected with invalid_target.' required: - grant_type type: object @@ -7809,7 +7816,8 @@ paths: $ref: '#/components/schemas/OAuth2Error' description: >- invalid_request / invalid_grant / unsupported_grant_type / - invalid_scope; device grant also returns authorization_pending, + invalid_scope / invalid_target (malformed RFC 8707 resource + indicator); device grant also returns authorization_pending, slow_down (plus non-standard interval field), expired_token, or access_denied here. '401': diff --git a/clients/go/generated/client.gen.go b/clients/go/generated/client.gen.go index d87015122..2b61324ca 100644 --- a/clients/go/generated/client.gen.go +++ b/clients/go/generated/client.gen.go @@ -993,6 +993,9 @@ type TokenRequest struct { // RefreshToken Required for grant_type=refresh_token (rotated on use). RefreshToken *string `json:"refresh_token,omitempty"` + // Resource RFC 8707 §2.1 resource indicator (optional, all grants): an absolute URI (scheme required, no fragment, max 255 chars) that the issued access token's audience (introspection `aud`) is bound to, overriding the default aud = client id. A malformed indicator is rejected with invalid_target. + Resource *string `json:"resource,omitempty"` + // Scope Space-separated scopes (client_credentials grant only). Scope *string `json:"scope,omitempty"` } diff --git a/clients/python/src/fulla/generated/models/token_request.py b/clients/python/src/fulla/generated/models/token_request.py index bdd8bbbb2..9cee1baa5 100644 --- a/clients/python/src/fulla/generated/models/token_request.py +++ b/clients/python/src/fulla/generated/models/token_request.py @@ -32,6 +32,9 @@ class TokenRequest: token_endpoint_auth_method=client_secret_post; FORBIDDEN for PUBLIC clients whose method is 'none' (F-017). scope (str | Unset): Space-separated scopes (client_credentials grant only). device_code (str | Unset): Required for the device_code grant (from /oauth2/device_authorization). + resource (str | Unset): RFC 8707 §2.1 resource indicator (optional, all grants): an absolute URI (scheme + required, no fragment, max 255 chars) that the issued access token's audience (introspection `aud`) is bound to, + overriding the default aud = client id. A malformed indicator is rejected with invalid_target. """ grant_type: TokenRequestGrantType @@ -43,6 +46,7 @@ class TokenRequest: client_secret: str | Unset = UNSET scope: str | Unset = UNSET device_code: str | Unset = UNSET + resource: str | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -64,6 +68,8 @@ def to_dict(self) -> dict[str, Any]: device_code = self.device_code + resource = self.resource + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( @@ -87,6 +93,8 @@ def to_dict(self) -> dict[str, Any]: field_dict["scope"] = scope if device_code is not UNSET: field_dict["device_code"] = device_code + if resource is not UNSET: + field_dict["resource"] = resource return field_dict @@ -111,6 +119,8 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: device_code = d.pop("device_code", UNSET) + resource = d.pop("resource", UNSET) + token_request = cls( grant_type=grant_type, code=code, @@ -121,6 +131,7 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: client_secret=client_secret, scope=scope, device_code=device_code, + resource=resource, ) token_request.additional_properties = d diff --git a/clients/ts/src/generated/types.gen.ts b/clients/ts/src/generated/types.gen.ts index f74956d95..5730eebe4 100644 --- a/clients/ts/src/generated/types.gen.ts +++ b/clients/ts/src/generated/types.gen.ts @@ -736,6 +736,10 @@ export type TokenRequest = { * Required for the device_code grant (from /oauth2/device_authorization). */ device_code?: string; + /** + * RFC 8707 §2.1 resource indicator (optional, all grants): an absolute URI (scheme required, no fragment, max 255 chars) that the issued access token's audience (introspection `aud`) is bound to, overriding the default aud = client id. A malformed indicator is rejected with invalid_target. + */ + resource?: string; }; /** @@ -6323,7 +6327,7 @@ export type PostOauth2TokenData = { export type PostOauth2TokenErrors = { /** - * invalid_request / invalid_grant / unsupported_grant_type / invalid_scope; device grant also returns authorization_pending, slow_down (plus non-standard interval field), expired_token, or access_denied here. + * invalid_request / invalid_grant / unsupported_grant_type / invalid_scope / invalid_target (malformed RFC 8707 resource indicator); device grant also returns authorization_pending, slow_down (plus non-standard interval field), expired_token, or access_denied here. */ 400: OAuth2Error; /** diff --git a/docs/domains/api-reference.md b/docs/domains/api-reference.md index 6c3c2933d..a2343594c 100644 --- a/docs/domains/api-reference.md +++ b/docs/domains/api-reference.md @@ -428,6 +428,7 @@ OAuth2 protocol endpoints (OAuth2_Protocol_Endpoint) keep the RFC 6749 §5.2 err | `unauthorized_client` | 400 | 客户端无权使用该授权类型 | | `unsupported_grant_type` | 400 | 不支持的授权类型 | | `invalid_scope` | 400 | 请求的 scope 无效 | +| `invalid_target` | 400 | 请求的 resource 目标无效 | | `server_error` | 500 | 服务器内部错误 | | `temporarily_unavailable` | 503 | 服务暂时不可用 | | `access_denied` | 403 | 授权请求被拒绝(用户无权或拒绝授权) | diff --git a/frontends/admin/src/services/messages/en.ts b/frontends/admin/src/services/messages/en.ts index 9b940d927..09d8dd676 100644 --- a/frontends/admin/src/services/messages/en.ts +++ b/frontends/admin/src/services/messages/en.ts @@ -76,6 +76,7 @@ export const en: Record = { unauthorized_client: 'The client is not allowed to use this grant type', unsupported_grant_type: 'Unsupported grant type', invalid_scope: 'The requested scope is invalid', + invalid_target: 'The requested resource target is invalid', server_error: 'Internal server error', temporarily_unavailable: 'The service is temporarily unavailable', access_denied: 'The authorization request was denied', diff --git a/frontends/admin/src/services/messages/zh-CN.ts b/frontends/admin/src/services/messages/zh-CN.ts index 4a51d3955..d85596de6 100644 --- a/frontends/admin/src/services/messages/zh-CN.ts +++ b/frontends/admin/src/services/messages/zh-CN.ts @@ -82,6 +82,7 @@ export const zhCN: Record = { unauthorized_client: '客户端无权使用该授权类型', unsupported_grant_type: '不支持的授权类型', invalid_scope: '请求的 scope 无效', + invalid_target: '请求的 resource 目标无效', server_error: '服务器内部错误', temporarily_unavailable: '服务暂时不可用', access_denied: '授权请求被拒绝', diff --git a/frontends/user/src/services/crossAppConsistency.property.test.ts b/frontends/user/src/services/crossAppConsistency.property.test.ts index 5a9b67066..9f635d24a 100644 --- a/frontends/user/src/services/crossAppConsistency.property.test.ts +++ b/frontends/user/src/services/crossAppConsistency.property.test.ts @@ -72,6 +72,7 @@ const FULLA_PROTOCOL_CODES = [ 'unauthorized_client', 'unsupported_grant_type', 'invalid_scope', + 'invalid_target', 'server_error', 'temporarily_unavailable', 'access_denied', diff --git a/frontends/user/src/services/messages/en.ts b/frontends/user/src/services/messages/en.ts index e2e6998a6..ec9079ea2 100644 --- a/frontends/user/src/services/messages/en.ts +++ b/frontends/user/src/services/messages/en.ts @@ -66,6 +66,7 @@ export const en: Record = { unauthorized_client: 'The client is not allowed to use this grant type', unsupported_grant_type: 'Unsupported grant type', invalid_scope: 'The requested scope is invalid', + invalid_target: 'The requested resource target is invalid', server_error: 'Internal server error', temporarily_unavailable: 'The service is temporarily unavailable', access_denied: 'The authorization request was denied', diff --git a/frontends/user/src/services/messages/zh-CN.ts b/frontends/user/src/services/messages/zh-CN.ts index 895c39dd4..a14a486e4 100644 --- a/frontends/user/src/services/messages/zh-CN.ts +++ b/frontends/user/src/services/messages/zh-CN.ts @@ -70,6 +70,7 @@ export const zhCN: Record = { unauthorized_client: '客户端无权使用该授权类型', unsupported_grant_type: '不支持的授权类型', invalid_scope: '请求的 scope 无效', + invalid_target: '请求的 resource 目标无效', server_error: '服务器内部错误', temporarily_unavailable: '服务暂时不可用', access_denied: '授权请求被拒绝', diff --git a/libs/common/src/error/ErrorCatalog.cc b/libs/common/src/error/ErrorCatalog.cc index 9060af1ff..0a9f1a12a 100644 --- a/libs/common/src/error/ErrorCatalog.cc +++ b/libs/common/src/error/ErrorCatalog.cc @@ -363,16 +363,18 @@ const std::array &rawEntries() return kEntries; } -// OAuth2 protocol error codes (RFC 6749 §5.2 base set + RFC 7009/8628 codes). -const std::array &rawOAuthEntries() +// OAuth2 protocol error codes (RFC 6749 §5.2 base set + RFC 7009/8628 codes +// + RFC 8707 §2.1 invalid_target for resource-indicator audience binding). +const std::array &rawOAuthEntries() { - static const std::array kEntries = {{ + static const std::array kEntries = {{ {"invalid_request", 400, "请求参数缺失或无效", ""}, {"invalid_client", 401, "客户端认证失败", ""}, {"invalid_grant", 400, "授权许可无效或已过期", ""}, {"unauthorized_client", 400, "客户端无权使用该授权类型", ""}, {"unsupported_grant_type", 400, "不支持的授权类型", ""}, {"invalid_scope", 400, "请求的 scope 无效", ""}, + {"invalid_target", 400, "请求的 resource 目标无效", ""}, {"server_error", 500, "服务器内部错误", ""}, {"temporarily_unavailable", 503, "服务暂时不可用", ""}, {"access_denied", 403, "授权请求被拒绝(用户无权或拒绝授权)", ""}, @@ -617,13 +619,14 @@ void ErrorCatalog::validateInvariants() ++oauthCounts[o.error]; } - static constexpr std::array kRequiredOAuthCodes = {{ + static constexpr std::array kRequiredOAuthCodes = {{ "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", "unsupported_grant_type", "invalid_scope", + "invalid_target", "server_error", "temporarily_unavailable", "access_denied", diff --git a/libs/drogon/include/fulla/drogon/plugin/OAuth2Plugin.h b/libs/drogon/include/fulla/drogon/plugin/OAuth2Plugin.h index c8cc1e569..d09637b7e 100644 --- a/libs/drogon/include/fulla/drogon/plugin/OAuth2Plugin.h +++ b/libs/drogon/include/fulla/drogon/plugin/OAuth2Plugin.h @@ -282,7 +282,8 @@ class OAuth2Plugin : public drogon::Plugin const std::string &clientSecret, const std::string &redirectUri, const std::string &codeVerifier, // P0-3: PKCE code verifier - std::function &&callback + std::function &&callback, + const std::string &resource = "" // RFC 8707 §2 audience override ); void exchangeCodeForAuthenticatedClient( @@ -290,17 +291,21 @@ class OAuth2Plugin : public drogon::Plugin const std::string &clientId, const std::string &redirectUri, const std::string &codeVerifier, - std::function &&callback + std::function &&callback, + const std::string &resource = "" // RFC 8707 §2 audience override ); /** * @brief Refresh Access Token (Async) * Returns JSON with {access_token, refresh_token, expires_in} or {error} + * `resource` (RFC 8707 §2.1) rebinds the rotated token's audience when + * non-empty. */ void refreshAccessToken( const std::string &refreshToken, const std::string &clientId, - std::function &&callback + std::function &&callback, + const std::string &resource = "" ); /** diff --git a/libs/drogon/include/fulla/drogon/validation/RuleSet.h b/libs/drogon/include/fulla/drogon/validation/RuleSet.h index e4fce8b62..3038503c9 100644 --- a/libs/drogon/include/fulla/drogon/validation/RuleSet.h +++ b/libs/drogon/include/fulla/drogon/validation/RuleSet.h @@ -41,6 +41,12 @@ class RuleSet static std::optional validateResponseType(const std::string &type); static std::optional validateGrantType(const std::string &type); static std::optional validateToken(const std::string &token); + /// RFC 8707 §2.1 resource indicator: must be an absolute URI (scheme + /// required), carry no fragment and no whitespace, and fit the + /// oauth2_access_tokens.audience column (255). Empty is valid == + /// "no audience binding requested" (callers gate on emptiness first). + /// Returns an error message or nullopt. + static std::optional validateResourceIndicator(const std::string &resource); static std::vector oauth2Authorize(const ::drogon::HttpRequestPtr &req); static std::vector oauth2Token(const ::drogon::HttpRequestPtr &req); diff --git a/libs/drogon/src/controllers/TokenEndpointController.cc b/libs/drogon/src/controllers/TokenEndpointController.cc index 2ecf9b8a2..ae251055b 100644 --- a/libs/drogon/src/controllers/TokenEndpointController.cc +++ b/libs/drogon/src/controllers/TokenEndpointController.cc @@ -226,6 +226,22 @@ void TokenEndpointController::initApiDocsImpl() fulla::drogon::observability::openapi::ParameterLocation::QUERY; codeVerifierParam.required = false; + // RFC 8707 §2.1: audience-bound resource indicator (optional, all + // grants). Non-empty values must be absolute URIs (no fragment, + // <=255 chars) and override the default aud = client id on the + // issued access token; malformed values get invalid_target. + fulla::drogon::observability::openapi::ParameterInfo resourceParam; + resourceParam.name = "resource"; + resourceParam.description = + "RFC 8707 resource indicator (optional, all grants): binds the " + "issued access token's audience (introspection aud) to this " + "absolute URI, overriding the default aud = client id. Malformed " + "values are rejected with invalid_target."; + resourceParam.type = fulla::drogon::observability::openapi::ParameterType::STRING; + resourceParam.location = + fulla::drogon::observability::openapi::ParameterLocation::QUERY; + resourceParam.required = false; + tokenEndpoint.parameters = {grantTypeParam, codeParam, @@ -233,7 +249,8 @@ void TokenEndpointController::initApiDocsImpl() clientIdParam, clientSecretParam, redirectUriParam, - codeVerifierParam}; + codeVerifierParam, + resourceParam}; tokenEndpoint.responses = {{200, "Token response with access_token and refresh_token"}, {400, "Invalid request"}, @@ -1177,6 +1194,7 @@ void TokenEndpointController::token( std::string grantType, code, redirectUri, clientId, clientSecret; std::string refreshToken; std::string codeVerifier; + std::string resource; // RFC 8707 §2 audience indicator (optional) std::string authHeader = req->getHeader("Authorization"); if (!authHeader.empty() && authHeader.substr(0, 6) == "Basic ") @@ -1215,6 +1233,7 @@ void TokenEndpointController::token( redirectUri = params["redirect_uri"]; refreshToken = params["refresh_token"]; codeVerifier = params["code_verifier"]; + resource = params["resource"]; } else { @@ -1227,6 +1246,31 @@ void TokenEndpointController::token( redirectUri = req->getParameter("redirect_uri"); refreshToken = req->getParameter("refresh_token"); codeVerifier = req->getParameter("code_verifier"); + resource = req->getParameter("resource"); + } + + // RFC 8707 §2: a non-empty resource indicator binds the issued access + // token's audience to the requested resource (overriding the P0-4 default + // aud = client id). Validated once here — before the F-017/F-018 gates — + // so all four grants share identical audience-binding semantics and a + // malformed indicator is a protocol invalid_target (RFC 8707 §2.1 via + // RFC 6749 §5.2), not invalid_request. + if (!resource.empty()) + { + auto resourceError = + fulla::drogon::validation::RuleSet::validateResourceIndicator(resource); + if (resourceError) + { + fulla::common::error::OAuth2ErrorHandler::sendErrorResponse( + std::move(callback), "invalid_target", *resourceError + ); + if (auto m = ::drogon::app().getPlugin<::OAuth2Plugin>()->getMetrics()) + m->incrementCounter( + "oauth2_requests_total", + fulla::common::ports::MetricLabels{{"endpoint", "token"}, {"status", "400"}} + ); + return; + } } // RFC 7523 section 2.2: allow omitting client_id when client_assertion is supplied. @@ -1264,6 +1308,7 @@ void TokenEndpointController::token( redirectUri, refreshToken, codeVerifier, + resource, authHeader](std::function rateAwareCallback) { auto dispatchCb = std::make_shared>( std::move(rateAwareCallback) @@ -1286,6 +1331,7 @@ void TokenEndpointController::token( redirectUri, refreshToken, codeVerifier, + resource, dispatchCb, authHeader, privateKeyJwtVerified]() mutable { @@ -1305,13 +1351,19 @@ void TokenEndpointController::token( if (*privateKeyJwtVerified) { plugin->exchangeCodeForAuthenticatedClient( - code, clientId, redirectUri, codeVerifier, std::move(onExchangeDone) + code, clientId, redirectUri, codeVerifier, std::move(onExchangeDone), resource ); } else { plugin->exchangeCodeForToken( - code, clientId, clientSecret, redirectUri, codeVerifier, std::move(onExchangeDone) + code, + clientId, + clientSecret, + redirectUri, + codeVerifier, + std::move(onExchangeDone), + resource ); } } @@ -1332,8 +1384,14 @@ void TokenEndpointController::token( plugin->getClient( clientId, - [plugin, clientId, clientSecret, refreshToken, authScheme, refreshCb, privateKeyJwtVerified]( - std::optional client + [plugin, + clientId, + clientSecret, + refreshToken, + resource, + authScheme, + refreshCb, + privateKeyJwtVerified](std::optional client ) { auto respondInvalidClient = [refreshCb, authScheme](const std::string &desc) { fulla::common::error::OAuth2ErrorHandler::sendErrorResponse( @@ -1351,15 +1409,18 @@ void TokenEndpointController::token( return; } - auto proceedRefresh = [plugin, clientId, refreshToken, refreshCb]() { + auto proceedRefresh = [plugin, clientId, refreshToken, resource, refreshCb]() { plugin->refreshAccessToken( - refreshToken, clientId, [refreshCb](const Json::Value &result) { + refreshToken, + clientId, + [refreshCb](const Json::Value &result) { (*refreshCb)(detail::buildTokenGrantResponse( result, detail::TokenGrantResponseKind::RefreshToken, ::drogon::app().getPlugin<::OAuth2Plugin>()->getMetrics() )); - } + }, + resource ); }; @@ -1473,6 +1534,8 @@ void TokenEndpointController::token( // server has no pre-defined default to fall back on) fulla::oauth2::model::Client aggregate(*client); std::string requestedScope = req->getParameter("scope"); + // RFC 8707 §2: audience indicator for the minted M2M token. + std::string ccResource = req->getParameter("resource"); std::string grantedScope; if (!requestedScope.empty()) { @@ -1527,7 +1590,7 @@ void TokenEndpointController::token( // caps introspection at org_id; org_name is dropped // from the CC surface (PR body records this). auto mintCcToken = - [plugin, clientId, grantedScope, sharedCb]( + [plugin, clientId, grantedScope, ccResource, sharedCb]( std::optional orgId) { // Generate access token (no refresh token for client_credentials) auto tokenStr = fulla::drogon::utils::generateSecureToken(); @@ -1553,8 +1616,9 @@ void TokenEndpointController::token( token.issuer = plugin->getIssuer(); token.orgId = orgId; // M3 org anchor (nullopt = personal) // P0-4 (#258): M2M audience = the client itself, same - // as the authorization_code path. - token.audience = clientId; + // as the authorization_code path. RFC 8707 §2: an + // explicit resource indicator overrides that default. + token.audience = ccResource.empty() ? clientId : ccResource; // Phase 4.3: route through plugin->saveAccessToken (NEW // ITokenRepository) instead of getStorage()->saveAccessToken. @@ -1634,6 +1698,8 @@ void TokenEndpointController::token( { clientId = req->getParameter("client_id"); } + // RFC 8707 §2: audience indicator for the minted device token pair. + std::string deviceResource = resource; if (deviceCode.empty() || clientId.empty()) { @@ -1689,7 +1755,7 @@ void TokenEndpointController::token( // PUBLIC -> current behavior (client_id bound to the device row) // The device-code lookup (Mapper::findBy + atomic consume) is the same // for both; wrapped in a local lambda so both paths converge on it. - auto runDeviceCodeLookup = [plugin, sharedCb, clientId, deviceCodeHash, dbClient]() { + auto runDeviceCodeLookup = [plugin, sharedCb, clientId, deviceCodeHash, deviceResource, dbClient]() { Mapper mapper(dbClient); mapper.findBy( Criteria( @@ -1697,7 +1763,7 @@ void TokenEndpointController::token( CompareOperator::EQ, deviceCodeHash ), - [plugin, sharedCb, clientId, deviceCodeHash, dbClient]( + [plugin, sharedCb, clientId, deviceCodeHash, deviceResource, dbClient]( const std::vector &results ) { if (results.empty()) @@ -1909,6 +1975,7 @@ void TokenEndpointController::token( userId, scope, now, + deviceResource, accessTokenTtl, refreshTokenTtl](const ::drogon::orm::Result &r) { if (r.empty()) @@ -1949,6 +2016,12 @@ void TokenEndpointController::token( // F-016: device-code tokens are constructed here // (outside TokenService), stamp the issuer too. accessToken.issuer = plugin->getIssuer(); + // P0-4 (#258) completion: the device path missed the + // default audience stamp the code/CC paths got; give + // it the same aud = client default, with RFC 8707 §2 + // overriding it when a resource indicator was sent. + accessToken.audience = + deviceResource.empty() ? clientId : deviceResource; fulla::oauth2::model::OAuth2RefreshToken refreshToken; refreshToken.token = diff --git a/libs/drogon/src/plugin/OAuth2Plugin.cc b/libs/drogon/src/plugin/OAuth2Plugin.cc index 46e8d62d9..77c8a39f1 100644 --- a/libs/drogon/src/plugin/OAuth2Plugin.cc +++ b/libs/drogon/src/plugin/OAuth2Plugin.cc @@ -1063,11 +1063,12 @@ void OAuth2Plugin::exchangeCodeForToken( const std::string &clientSecret, const std::string &redirectUri, const std::string &codeVerifier, - std::function &&callback + std::function &&callback, + const std::string &resource ) { tokenService_->exchangeCodeForToken( - code, clientId, clientSecret, redirectUri, codeVerifier, std::move(callback) + code, clientId, clientSecret, redirectUri, codeVerifier, std::move(callback), resource ); } @@ -1076,18 +1077,20 @@ void OAuth2Plugin::exchangeCodeForAuthenticatedClient( const std::string &clientId, const std::string &redirectUri, const std::string &codeVerifier, - std::function &&callback + std::function &&callback, + const std::string &resource ) { tokenService_->exchangeCodeForAuthenticatedClient( - code, clientId, redirectUri, codeVerifier, std::move(callback) + code, clientId, redirectUri, codeVerifier, std::move(callback), resource ); } void OAuth2Plugin::refreshAccessToken( const std::string &refreshToken, const std::string &clientId, - std::function &&callback + std::function &&callback, + const std::string &resource ) { // F-005: the standalone Redis backend never persisted refresh tokens @@ -1107,7 +1110,7 @@ void OAuth2Plugin::refreshAccessToken( callback(err); return; } - tokenService_->refreshAccessToken(refreshToken, clientId, std::move(callback)); + tokenService_->refreshAccessToken(refreshToken, clientId, std::move(callback), resource); } void OAuth2Plugin::validateAccessToken( diff --git a/libs/drogon/src/validation/RuleSet.cc b/libs/drogon/src/validation/RuleSet.cc index f9dca9c9f..cabe096b7 100644 --- a/libs/drogon/src/validation/RuleSet.cc +++ b/libs/drogon/src/validation/RuleSet.cc @@ -589,6 +589,54 @@ std::optional RuleSet::validateToken(const std::string &token) return std::nullopt; } +std::optional RuleSet::validateResourceIndicator(const std::string &resource) +{ + if (resource.empty()) + { + // Absent (or empty) == "no audience binding requested"; callers gate + // on emptiness before invoking this validator. + return std::nullopt; + } + + if (resource.length() > 255) + { + return "resource exceeds maximum length of 255 characters"; + } + + // RFC 8707 §2: the indicator MUST be an absolute URI (RFC 3986): its + // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) followed by ":". + // This accepts https://, urn:, mailto: style absolute URIs alike and + // rejects relative references (no scheme). A fragment is forbidden. + const auto colon = resource.find(':'); + if (colon == std::string::npos || colon == 0) + { + return "resource must be an absolute URI with a scheme"; + } + const auto scheme = resource.substr(0, colon); + if (!std::isalpha(static_cast(scheme[0]))) + { + return "resource must be an absolute URI with a scheme"; + } + for (const char c : scheme) + { + const auto uc = static_cast(c); + if (!std::isalpha(uc) && !std::isdigit(uc) && c != '+' && c != '-' && c != '.') + { + return "resource scheme contains invalid characters"; + } + } + if (resource.find('#') != std::string::npos) + { + return "resource must not contain a fragment"; + } + if (resource.find_first_of(" \t\r\n") != std::string::npos) + { + return "resource must not contain whitespace"; + } + + return std::nullopt; +} + // 便捷验证组合方法 std::vector RuleSet::oauth2Authorize(const ::drogon::HttpRequestPtr &req) diff --git a/libs/oauth2/include/fulla/oauth2/protocol/TokenService.h b/libs/oauth2/include/fulla/oauth2/protocol/TokenService.h index dba55ef2d..30422f18e 100644 --- a/libs/oauth2/include/fulla/oauth2/protocol/TokenService.h +++ b/libs/oauth2/include/fulla/oauth2/protocol/TokenService.h @@ -166,31 +166,40 @@ class TokenService : public std::enable_shared_from_this /// Exchange an authorization code for an access/refresh token pair. /// Original: oauth2::TokenService::exchangeCodeForToken. + /// RFC 8707 §2: a non-empty `resource` overrides the P0-4 default + /// audience (aud = issuing client) on the issued access token. void exchangeCodeForToken( const std::string &code, const std::string &clientId, const std::string &clientSecret, const std::string &redirectUri, const std::string &codeVerifier, - std::function &&callback + std::function &&callback, + const std::string &resource = "" ); /// Exchange an authorization code when the client has already been /// authenticated out-of-band (e.g. RFC 7523 private_key_jwt). + /// RFC 8707 §2: a non-empty `resource` overrides the P0-4 default + /// audience (aud = issuing client) on the issued access token. void exchangeCodeForAuthenticatedClient( const std::string &code, const std::string &clientId, const std::string &redirectUri, const std::string &codeVerifier, - std::function &&callback + std::function &&callback, + const std::string &resource = "" ); /// Refresh an access token (with reuse-detection cascade revocation). /// Original: oauth2::TokenService::refreshAccessToken. + /// RFC 8707 §2.1: a non-empty `resource` rebinds the rotated access + /// token's audience; absent keeps the P0-4 default (aud = client). void refreshAccessToken( const std::string &refreshToken, const std::string &clientId, - std::function &&callback + std::function &&callback, + const std::string &resource = "" ); /// Validate an access token (not expired, not revoked). Original: diff --git a/libs/oauth2/src/protocol/TokenService.cc b/libs/oauth2/src/protocol/TokenService.cc index 3b46a2bf8..144095e50 100644 --- a/libs/oauth2/src/protocol/TokenService.cc +++ b/libs/oauth2/src/protocol/TokenService.cc @@ -350,7 +350,8 @@ void TokenService::exchangeCodeForToken( const std::string &clientSecret, const std::string &redirectUri, const std::string &codeVerifier, - std::function &&callback + std::function &&callback, + const std::string &resource ) { if (!clients_ || !grants_ || !tokens_ || !crypto_) @@ -366,7 +367,7 @@ void TokenService::exchangeCodeForToken( clients_->validateClient( clientId, clientSecret, - [self, code, clientId, redirectUri, codeVerifier, callback = std::move(callback)]( + [self, code, clientId, redirectUri, codeVerifier, resource, callback = std::move(callback)]( bool isValid ) mutable { if (!isValid) @@ -376,7 +377,7 @@ void TokenService::exchangeCodeForToken( } self->exchangeCodeForAuthenticatedClient( - code, clientId, redirectUri, codeVerifier, std::move(callback) + code, clientId, redirectUri, codeVerifier, std::move(callback), resource ); } ); @@ -387,7 +388,8 @@ void TokenService::exchangeCodeForAuthenticatedClient( const std::string &clientId, const std::string &redirectUri, const std::string &codeVerifier, - std::function &&callback + std::function &&callback, + const std::string &resource ) { if (!clients_ || !grants_ || !tokens_ || !crypto_) @@ -401,7 +403,7 @@ void TokenService::exchangeCodeForAuthenticatedClient( self->grants_->consumeAuthCode( hashToken(*self->crypto_, code), redirectUri, - [self, callback = std::move(callback), clientId, codeVerifier]( + [self, callback = std::move(callback), clientId, codeVerifier, resource]( std::optional authCodeOpt ) { if (!authCodeOpt) @@ -453,12 +455,12 @@ void TokenService::exchangeCodeForAuthenticatedClient( authCode.userId, authCode.orgId, authCode.scope, - [self, callback, authCode, now]( + [self, callback, authCode, now, resource]( std::optional orgCtx ) { self->resolveRoles( authCode.userId, - [self, callback, authCode, now, orgCtx](std::vector roles) { + [self, callback, authCode, now, orgCtx, resource](std::vector roles) { Json::Value rolesJson(Json::arrayValue); for (const auto &r : roles) rolesJson.append(r); @@ -496,7 +498,9 @@ void TokenService::exchangeCodeForAuthenticatedClient( // P0-4 (#258): the audience column finally earns its // keep — aud = the client the token was issued to, so // introspection's aud stops being permanently empty. - token.audience = authCode.clientId; + // RFC 8707 §2: an explicit resource indicator at the + // token request overrides the client default. + token.audience = resource.empty() ? authCode.clientId : resource; fulla::oauth2::model::OAuth2RefreshToken refreshToken; refreshToken.token = hashToken(*self->crypto_, refreshTokenStr); @@ -680,7 +684,8 @@ void TokenService::exchangeCodeForAuthenticatedClient( void TokenService::refreshAccessToken( const std::string &refreshTokenStr, const std::string &clientId, - std::function &&callback + std::function &&callback, + const std::string &resource ) { if (!tokens_ || !crypto_) @@ -737,7 +742,7 @@ void TokenService::refreshAccessToken( callback(makeError("invalid_grant", "Invalid or revoked refresh token")); }; tokens_->inspectRefreshToken( - hashedRt, clientId, [self, callback, clientId, reject](RefreshTokenResult result) mutable { + hashedRt, clientId, [self, callback, clientId, reject, resource](RefreshTokenResult result) mutable { if (result.status != RefreshTokenStatus::Ready || !result.token) { reject(std::move(result)); @@ -769,7 +774,7 @@ void TokenService::refreshAccessToken( !storedRt->userId.empty() && storedRt->userId.find_first_not_of("0123456789") == std::string::npos; auto withSubject = std::make_shared>( - [self, callback, storedRt, now, expected, reject](std::string subject) mutable { + [self, callback, storedRt, now, expected, reject, resource](std::string subject) mutable { storedRt->userId = std::move(subject); // v1.4.0 M1 (design §2.1 item 4): refresh preserves the org // binding along the family and re-resolves org_ctx (O7: a @@ -780,7 +785,7 @@ void TokenService::refreshAccessToken( storedRt->userId, storedRt->orgId, storedRt->scope, - [self, callback, storedRt, now, expected, reject]( + [self, callback, storedRt, now, expected, reject, resource]( std::optional orgCtx ) { auto newTokenStr = generateSecureToken(*self->crypto_); @@ -804,8 +809,9 @@ void TokenService::refreshAccessToken( // v1.4.0 M1: the org binding survives rotation. token.orgId = storedRt->orgId; // P0-4 (#258): audience survives rotation with the same value - // (aud = issuing client). - token.audience = storedRt->clientId; + // (aud = issuing client). RFC 8707 §2.1: an explicit resource + // indicator on the refresh request rebinds the audience. + token.audience = resource.empty() ? storedRt->clientId : resource; fulla::oauth2::model::OAuth2RefreshToken newRt; newRt.token = hashToken(*self->crypto_, newRefreshTokenStr); diff --git a/libs/oauth2/test/TokenServiceTest.cc b/libs/oauth2/test/TokenServiceTest.cc index 55d2098a5..6736ff0c3 100644 --- a/libs/oauth2/test/TokenServiceTest.cc +++ b/libs/oauth2/test/TokenServiceTest.cc @@ -505,6 +505,81 @@ TEST(TokenServiceTest, ExchangeCode_HappyPath_ReturnsFrozenShape) EXPECT_EQ(validated->audience, "test-client"); } +TEST(TokenServiceTest, ExchangeCode_ResourceIndicator_BindsAudienceOverride) +{ + auto clients = makeSeededClients(); + auto grants = std::make_shared(); + auto tokens = std::make_shared(); + auto svc = makeService(clients, grants, tokens); + + const std::string redirectUri = "https://example.test/cb"; + const std::string resource = "https://mcp.example.test/mcp"; + std::string rawCode = issueAuthCode(*svc, "test-client", "alice", "profile", redirectUri); + ASSERT_FALSE(rawCode.empty()); + + Json::Value result; + bool called = false; + // RFC 8707 §2: the resource indicator rides the token request; the issued + // access token's audience must be the resource, not the client default. + svc->exchangeCodeForToken( + rawCode, "test-client", "secret", redirectUri, "", [&](const Json::Value &json) { + result = json; + called = true; + }, + resource + ); + + ASSERT_TRUE(called); + EXPECT_FALSE(result.isMember("error")); + + std::shared_ptr validated; + svc->validateAccessToken(result["access_token"].asString(), [&](auto at) { validated = at; }); + ASSERT_NE(validated, nullptr); + EXPECT_EQ(validated->audience, resource); + // The client-facing fields are unaffected by the audience override. + EXPECT_EQ(validated->clientId, "test-client"); + EXPECT_EQ(validated->userId, "alice"); +} + +TEST(TokenServiceTest, RefreshToken_ResourceIndicator_RebindsAudience) +{ + auto clients = makeSeededClients(); + auto grants = std::make_shared(); + auto tokens = std::make_shared(); + auto svc = makeService(clients, grants, tokens); + + const std::string redirectUri = "https://example.test/cb"; + std::string rawCode = issueAuthCode(*svc, "test-client", "alice", "profile", redirectUri); + ASSERT_FALSE(rawCode.empty()); + + Json::Value first; + svc->exchangeCodeForToken( + rawCode, "test-client", "secret", redirectUri, "", [&](const Json::Value &j) { first = j; } + ); + ASSERT_TRUE(first.isMember("refresh_token")); + + // RFC 8707 §2.1: a resource on the refresh request rebinds the rotated + // access token's audience. + const std::string resource = "https://mcp.example.test/mcp"; + Json::Value rotated; + bool called = false; + svc->refreshAccessToken( + first["refresh_token"].asString(), "test-client", [&](const Json::Value &j) { + rotated = j; + called = true; + }, + resource + ); + + ASSERT_TRUE(called); + EXPECT_FALSE(rotated.isMember("error")); + + std::shared_ptr validated; + svc->validateAccessToken(rotated["access_token"].asString(), [&](auto at) { validated = at; }); + ASSERT_NE(validated, nullptr); + EXPECT_EQ(validated->audience, resource); +} + TEST(TokenServiceTest, ExchangeCode_WrongSecret_ReturnsInvalidClient) { auto clients = makeSeededClients(); diff --git a/libs/storage-postgres/src/PostgresTokenRepository.cc b/libs/storage-postgres/src/PostgresTokenRepository.cc index 23956e15c..b40341cb9 100644 --- a/libs/storage-postgres/src/PostgresTokenRepository.cc +++ b/libs/storage-postgres/src/PostgresTokenRepository.cc @@ -66,6 +66,10 @@ void PostgresTokenRepository::saveAccessToken(const OAuth2AccessToken &token, Vo // F-016: persist the issuer stamped at issuance (previously never // written, so every row carried the schema's hardcoded default). newToken.setIssuer(token.issuer); + // RFC 8707: persist the audience stamped at issuance. The pair insert + // (insertPair) already carries it; keep the single-token path + // consistent so introspection's aud never silently differs by path. + newToken.setAudience(token.audience); // v1.4.0 M1 (design §2.1 item 4): the org binding inherited from // the code. V036 column; absent -> NULL. if (token.orgId.has_value()) diff --git a/tests/integration/error/OAuth2ProtocolEndpointRfcComplianceTest.cc b/tests/integration/error/OAuth2ProtocolEndpointRfcComplianceTest.cc index 09a36ccfb..677cf0759 100644 --- a/tests/integration/error/OAuth2ProtocolEndpointRfcComplianceTest.cc +++ b/tests/integration/error/OAuth2ProtocolEndpointRfcComplianceTest.cc @@ -347,3 +347,22 @@ DROGON_TEST(Integration_P1_OAuth2TokenEndpoint_DeviceCodeMissingParams_Rfc6749In assertLiveRfcError(TEST_CTX, resp, allowed, "invalid_request", k400BadRequest); } + +// --- B3: malformed RFC 8707 resource indicator -> invalid_target (400). +DROGON_TEST(Integration_P1_OAuth2TokenEndpoint_MalformedResourceIndicator_Rfc8707InvalidTarget) +{ + const std::unordered_set allowed = allowedProtocolCodes(); + + // A relative "resource" value fails the RFC 8707 §2 absolute-URI rule; the + // gate runs before any grant dispatch, so this never touches the database. + const HttpResponsePtr resp = + postForm("/oauth2/token", "grant_type=client_credentials&resource=not-a-uri"); + if (resp == nullptr) + { + LOG_WARN << "Skipping live /oauth2/token check: test server not reachable on " << kBaseUrl; + CHECK(true); + return; + } + + assertLiveRfcError(TEST_CTX, resp, allowed, "invalid_target", k400BadRequest); +} diff --git a/tests/unit/error/ErrorCatalogPropertyTest.cc b/tests/unit/error/ErrorCatalogPropertyTest.cc index 22368acb6..de65f99cc 100644 --- a/tests/unit/error/ErrorCatalogPropertyTest.cc +++ b/tests/unit/error/ErrorCatalogPropertyTest.cc @@ -139,17 +139,19 @@ bool checkApplicationEntryInvariants(const CatalogEntry &e) return true; } -// RFC 6749 §5.2 base set plus RFC 7009/8628 codes that must each be registered -// exactly once (Requirement 2.6). -const std::array &requiredOAuthCodes() +// RFC 6749 §5.2 base set plus RFC 7009/8628 codes and the RFC 8707 §2.1 +// resource-indicator code that must each be registered exactly once +// (Requirement 2.6). +const std::array &requiredOAuthCodes() { - static const std::array kCodes = {{ + static const std::array kCodes = {{ "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", "unsupported_grant_type", "invalid_scope", + "invalid_target", "server_error", "temporarily_unavailable", "access_denied", diff --git a/tests/unit/error/ErrorCatalogRegressionTest.cc b/tests/unit/error/ErrorCatalogRegressionTest.cc index 1f990e72e..abd55d7d6 100644 --- a/tests/unit/error/ErrorCatalogRegressionTest.cc +++ b/tests/unit/error/ErrorCatalogRegressionTest.cc @@ -144,7 +144,8 @@ DROGON_TEST(Unit_P0_ErrorCatalog_Regression_NumericCodesWithinCategorySegment) // --- Requirement 11.5 / 3.6: OAuth2 protocol code set present with no omissions. DROGON_TEST(Unit_P0_ErrorCatalog_Regression_OAuthProtocolCodeSetComplete) { - // RFC 6749 §5.2 base set plus RFC 7009/8628 codes that must all be registered. + // RFC 6749 §5.2 base set plus RFC 7009/8628 codes and the RFC 8707 §2.1 + // resource-indicator code that must all be registered. const std::vector kRequiredOAuthCodes = { "invalid_request", "invalid_client", @@ -152,6 +153,7 @@ DROGON_TEST(Unit_P0_ErrorCatalog_Regression_OAuthProtocolCodeSetComplete) "unauthorized_client", "unsupported_grant_type", "invalid_scope", + "invalid_target", "server_error", "temporarily_unavailable", "access_denied", diff --git a/tests/unit/initorder/CategoryA_InitOrderSnapshotTest.cc b/tests/unit/initorder/CategoryA_InitOrderSnapshotTest.cc index d3724144b..cb2ac6c98 100644 --- a/tests/unit/initorder/CategoryA_InitOrderSnapshotTest.cc +++ b/tests/unit/initorder/CategoryA_InitOrderSnapshotTest.cc @@ -108,9 +108,10 @@ DROGON_TEST(Unit_P1_InitOrder_1_1_OpenApiTokenEndpoint_Snapshot_Baseline) CHECK(token["tags"].size() == 2); // The token endpoint registers its query parameters. Updated for PKCE - // (RFC 7636): code_verifier added on the authorization_code grant. + // (RFC 7636): code_verifier added on the authorization_code grant, and + // for RFC 8707: the resource audience indicator. REQUIRE(token.isMember("parameters")); - CHECK(token["parameters"].size() == 7); + CHECK(token["parameters"].size() == 8); // Collect parameter names to assert the complete set (order-independent). std::set paramNames; @@ -121,7 +122,7 @@ DROGON_TEST(Unit_P1_InitOrder_1_1_OpenApiTokenEndpoint_Snapshot_Baseline) } const std::set expectedParams = {"grant_type", "code", "refresh_token", "client_id", "client_secret", - "redirect_uri", "code_verifier"}; + "redirect_uri", "code_verifier", "resource"}; CHECK(paramNames == expectedParams); // grant_type advertises its enum values (completeness of param metadata). diff --git a/tests/unit/validation/RuleSetValidateFieldTest.cc b/tests/unit/validation/RuleSetValidateFieldTest.cc index 455fbc039..3ad331dc0 100644 --- a/tests/unit/validation/RuleSetValidateFieldTest.cc +++ b/tests/unit/validation/RuleSetValidateFieldTest.cc @@ -112,3 +112,54 @@ DROGON_TEST(Unit_P1_Validation_RuleSet_ValidateField_AllConstraintsPass_ReturnsN auto err = RuleSet::validateField("alice", "username", r); CHECK(!err.has_value()); } + +// --- RFC 8707 §2.1 resource indicator (RuleSet::validateResourceIndicator). --- + +DROGON_TEST(Unit_P1_Validation_RuleSet_ResourceIndicator_AbsoluteUri_ReturnsNullopt) +{ + CHECK(!RuleSet::validateResourceIndicator("https://mcp.example.com/mcp").has_value()); + CHECK(!RuleSet::validateResourceIndicator("urn:ietf:params:oauth:resource:x").has_value()); +} + +DROGON_TEST(Unit_P1_Validation_RuleSet_ResourceIndicator_EmptyMeansAbsent_ReturnsNullopt) +{ + CHECK(!RuleSet::validateResourceIndicator("").has_value()); +} + +DROGON_TEST(Unit_P1_Validation_RuleSet_ResourceIndicator_RelativeUri_ReturnsError) +{ + auto err = RuleSet::validateResourceIndicator("not-a-uri"); + REQUIRE(err.has_value()); + CHECK(err->find("absolute URI") != std::string::npos); +} + +DROGON_TEST(Unit_P1_Validation_RuleSet_ResourceIndicator_Fragment_ReturnsError) +{ + auto err = RuleSet::validateResourceIndicator("https://mcp.example.com/mcp#frag"); + REQUIRE(err.has_value()); + CHECK(err->find("fragment") != std::string::npos); +} + +DROGON_TEST(Unit_P1_Validation_RuleSet_ResourceIndicator_Whitespace_ReturnsError) +{ + auto err = RuleSet::validateResourceIndicator("https://mcp.example.com/a b"); + REQUIRE(err.has_value()); + CHECK(err->find("whitespace") != std::string::npos); +} + +DROGON_TEST(Unit_P1_Validation_RuleSet_ResourceIndicator_TooLong_ReturnsError) +{ + // 256 chars past the scheme delimiter -> exceeds the audience column (255). + std::string longResource = "https://example.com/"; + longResource += std::string(256, 'a'); + auto err = RuleSet::validateResourceIndicator(longResource); + REQUIRE(err.has_value()); + CHECK(err->find("255") != std::string::npos); +} + +DROGON_TEST(Unit_P1_Validation_RuleSet_ResourceIndicator_BadSchemeChar_ReturnsError) +{ + auto err = RuleSet::validateResourceIndicator("ht tp://mcp.example.com"); + REQUIRE(err.has_value()); + CHECK(err->find("scheme") != std::string::npos); +} diff --git a/tools/api-diff/api-baseline.txt b/tools/api-diff/api-baseline.txt index aaa57e92a..ca02dba83 100644 --- a/tools/api-diff/api-baseline.txt +++ b/tools/api-diff/api-baseline.txt @@ -4833,19 +4833,22 @@ const std::string &clientId, const std::string &clientSecret, const std::string &redirectUri, const std::string &codeVerifier, -std::function &&callback +std::function &&callback, +const std::string &resource = "" ); void exchangeCodeForAuthenticatedClient( const std::string &code, const std::string &clientId, const std::string &redirectUri, const std::string &codeVerifier, -std::function &&callback +std::function &&callback, +const std::string &resource = "" ); void refreshAccessToken( const std::string &refreshToken, const std::string &clientId, -std::function &&callback +std::function &&callback, +const std::string &resource = "" ); void validateAccessToken( const std::string &token, @@ -6008,6 +6011,7 @@ static std::optional validateScope(const std::string &scope); static std::optional validateResponseType(const std::string &type); static std::optional validateGrantType(const std::string &type); static std::optional validateToken(const std::string &token); +static std::optional validateResourceIndicator(const std::string &resource); static std::vector oauth2Authorize(const ::drogon::HttpRequestPtr &req); static std::vector oauth2Token(const ::drogon::HttpRequestPtr &req); static std::vector login(const ::drogon::HttpRequestPtr &req); @@ -8960,19 +8964,22 @@ const std::string &clientId, const std::string &clientSecret, const std::string &redirectUri, const std::string &codeVerifier, -std::function &&callback +std::function &&callback, +const std::string &resource = "" ); void exchangeCodeForAuthenticatedClient( const std::string &code, const std::string &clientId, const std::string &redirectUri, const std::string &codeVerifier, -std::function &&callback +std::function &&callback, +const std::string &resource = "" ); void refreshAccessToken( const std::string &refreshToken, const std::string &clientId, -std::function &&callback +std::function &&callback, +const std::string &resource = "" ); void validateAccessToken( const std::string &token, diff --git a/website/static/llms-full.txt b/website/static/llms-full.txt index 1a8e51054..b0ba1fffb 100644 --- a/website/static/llms-full.txt +++ b/website/static/llms-full.txt @@ -2029,6 +2029,7 @@ OAuth2 protocol endpoints (OAuth2_Protocol_Endpoint) keep the RFC 6749 §5.2 err | `unauthorized_client` | 400 | 客户端无权使用该授权类型 | | `unsupported_grant_type` | 400 | 不支持的授权类型 | | `invalid_scope` | 400 | 请求的 scope 无效 | +| `invalid_target` | 400 | 请求的 resource 目标无效 | | `server_error` | 500 | 服务器内部错误 | | `temporarily_unavailable` | 503 | 服务暂时不可用 | | `access_denied` | 403 | 授权请求被拒绝(用户无权或拒绝授权) |