Skip to content

Make enabled_protocols authoritative for http and h2 - #3767

Open
wwbmmm wants to merge 7 commits into
apache:masterfrom
wwbmmm:oncall/req-20261121-025731-2
Open

wwbmmm wants to merge 7 commits into
apache:masterfrom
wwbmmm:oncall/req-20261121-025731-2

Conversation

@wwbmmm

@wwbmmm wwbmmm commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Problem Summary:

ServerOptions.enabled_protocols is documented as the list of protocols to serve, but Server::BuildAcceptor() always exempted http/h2 (and rdma_handshake) from the whitelist. A server configured with enabled_protocols = "baidu_std" still served the complete HTTP/1 and HTTP/2 stacks, including builtin services on the main port, without any error or warning.

What is changed and the side effects?

Changed:

  • The whitelist is now authoritative: when enabled_protocols is non-empty, only the listed protocols are served. rdma_handshake remains always served because it only handles the transport level handshake and dispatches no request; this is documented explicitly.
  • If builtin services (has_builtin_services, true by default) or restful services are registered while the whitelist contains neither http nor h2, Server::Start() fails with an actionable error instead of leaving their HTTP surface in an undefined state.
  • Updated the ServerOptions.enabled_protocols comment and docs/en/server.md, docs/cn/server.md.
  • Tests: test/brpc_server_unittest.cpp covers a whitelist without http rejecting HTTP, a whitelist with http/h2 still serving builtin services, and the misconfiguration failures. test/rdma_test_helper.h disables builtin services since it whitelists only baidu_std.

Side effects:

  • Performance effects: none, the change only affects acceptor construction.
  • Breaking backward compatibility: yes. Deployments that relied on the undocumented http/h2 exemption must add http (or h2) to enabled_protocols, or set has_builtin_services = false; Server::Start() now fails with a message explaining both options instead of silently serving HTTP.

Tests run:

  • build/test/brpc_server_unittest (all 54 tests), executed from test/ so that cert-relative tests find their files.

🤖 This PR was automatically created by brpc-oncall

ServerOptions.enabled_protocols is documented as the only protocols to
serve, but BuildAcceptor always exempted http/h2 (and rdma_handshake) from
the whitelist. An operator setting enabled_protocols="baidu_std" still
served the whole HTTP/1 and HTTP/2 stacks, including builtin services on
the main port, without any error or warning.

Only rdma_handshake stays exempt since it handles the transport level
handshake and dispatches no request. A whitelist without http or h2 while
builtin or restful services are enabled now fails Server::Start() with an
actionable message instead of silently serving or dropping them.

Update the option comment and docs/en, docs/cn accordingly.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Two moderate active findings remain in src/brpc/server.cpp: the HTTP-only check treats empty RESTful maps as present and its diagnostic does not account for mappings that still cause startup failure.

2 open issues
What changed in this PR

This PR makes ServerOptions.enabled_protocols authoritative for HTTP/1 and HTTP/2 while preserving the transport-level rdma_handshake exception, and adds validation for HTTP-dependent services.

Changes:

  • Restricts acceptor construction to explicitly whitelisted protocols.
  • Validates builtin and RESTful service configurations that require http or h2.
  • Updates server documentation, unit tests, and RDMA test configuration.
File Description
test/​rdma_test_helper.h Disables builtin services for RDMA tests that use a baidu_std-only protocol whitelist.
test/​brpc_server_unittest.cpp Adds tests covering HTTP exclusion, service availability, and invalid protocol whitelist configurations.
src/​brpc/​server.h Documents the authoritative protocol whitelist behavior and HTTP service requirements.
src/​brpc/​server.cpp Enforces protocol filtering and validates configurations for HTTP-dependent services.
docs/​en/​server.md Documents the updated protocol whitelist semantics and configuration examples in English.
docs/​cn/​server.md Documents the updated protocol whitelist semantics and configuration examples in Chinese.

Review effort: Lite

Comment thread src/brpc/server.cpp Resolved
Comment thread src/brpc/server.cpp Resolved
RemoveService() keeps the restful maps allocated after their last mapping
is removed, so checking the map pointers made a server without any restful
endpoint fail to start when enabled_protocols omitted http/h2. Check the
number of mappings instead, and make the error message name every cause
that still has to be fixed.

Add a test that removes a restful service and starts with a whitelist
without http.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Two moderate active issues remain: a configured HTTP master service can be silently unreachable under the affected options, and the documented retry path fails because builtin registrations persist after startup failure.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Missing HTTP protocol validation for http_master_service

src/​brpc/​server.cpp:770

http_master_service is another HTTP-only surface: http_rpc_protocol.cpp dispatches every HTTP request to it, but it is not represented in either ServiceMap or RestfulMap. With has_builtin_services=false, enabled_protocols="baidu_std", and an http_master_service configured, this condition is false, so Start() succeeds while no HTTP handler is installed and the configured master service is silently unreachable. Include this option in the HTTP-required validation and diagnostic (or explicitly reject this combination elsewhere).

Medium severity Failed startup leaves builtin services registered, breaking retries

src/​brpc/​server.cpp:787

This recovery advice does not work when the caller retries Start() on the same Server: StartInternal() has already added the builtin services before BuildAcceptor() reaches this check, and the failed-start cleanup does not remove them. Changing the options to has_builtin_services=false on a retry then hits the existing consistency check for _builtin_service_count > 0 and fails again. Validate this configuration before adding builtin services, or otherwise remove/reset those registrations on this failure path (and cover the retry case).

2 resolved since last review

Review effort: Lite

http_master_service is served through http/h2 but is represented in
neither ServiceMap nor RestfulMap, so a whitelist without http/h2 made it
silently unreachable. Include it in the validation and diagnostic.

Also run the validation before AddBuiltinServices(): a Start() rejected
after builtin services were registered left them behind, so retrying the
same Server with has_builtin_services=false failed the consistency check.
Add tests for both cases.
@wwbmmm
wwbmmm requested a lite review from Copilot November 22, 2026 13:58
@wwbmmm

wwbmmm commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

[replied by brpc-oncall robot] Addressed both new findings:

  • ServerOptions.http_master_service is now part of the HTTP-only validation and the diagnostic message, so a whitelist without http/h2 fails Start() instead of silently making the configured master service unreachable. Covered by enabled_protocols_must_include_http_for_http_master_service.
  • The validation now runs in StartInternal() before AddBuiltinServices(), so a rejected Start() leaves no builtin registrations behind and retrying the same Server with has_builtin_services=false works. Covered by can_retry_start_after_protocols_rejection.

The diagnostic still lists every cause that applies and its matching remedy (builtin services, restful mappings, http_master_service). brpc_server_unittest passes all 57 tests.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

An active diagnostic issue remains because invalid protocol names can be masked by the HTTP-only feature check, making configuration errors harder to diagnose.

1 open issue

Review effort: Lite

Comment thread src/brpc/server.cpp Resolved
The http/h2 requirement of builtin services ran before unknown protocol
names were rejected, so a typo in enabled_protocols was masked by the
HTTP-only diagnostic and the operator had to fix the config twice.
Validate the names first: ValidateEnabledProtocols() now rejects unknown
names and is called before AddBuiltinServices(), and BuildAcceptor() only
filters protocols by the whitelist. Extend the invalid protocol test to
check that no builtin service was added by the failed Start().

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because the protocol whitelist can become stale across server restarts, allowing handlers that no longer match the configured options.

No open issues 🎉

1 resolved since last review

Review effort: Lite

Acceptors cache the protocol handlers built from ServerOptions, and they
were only created once per Server. Restarting a stopped Server with a
different enabled_protocols kept serving the old whitelist, which defeats
the authoritative whitelist and can leave http enabled after it is
removed from the options. Delete the acceptors in StartInternal() so that
they are rebuilt from the options of the current Start(), and add a test
that restarts a server with a different whitelist.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because the rejection path can adopt and later delete caller-owned or invalid option pointers, violating the retry-safety invariant and creating a critical hidden lifecycle issue.

No open issues 🎉

Review effort: Lite

@wwbmmm

wwbmmm commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

[replied by brpc-oncall robot] Confirmed and fixed: _am/_internal_am were created once per Server and reused after Stop()/Join(), so restarting with a different enabled_protocols (or different socket_mode/max_connections) kept serving the handlers of the previous options. StartInternal() now deletes both acceptors before creating the listening sockets so they are rebuilt from the options of the current Start().

Added restart_rebuilds_acceptor_for_enabled_protocols: start with enabled_protocols="baidu_std", stop, restart with "hulu_pbrpc", and verify baidu_std/http are no longer accepted. brpc_server_unittest passes all 58 tests.

copy_and_fill_server_options() transfers ownership of the pointers in the
user-provided ServerOptions to the server. The enabled_protocols
validation ran after that, so a rejected configuration adopted pointers
such as http_master_service which the caller may still believe it owns.
Validate the user's options before the adopt, keeping the rejection path
free of ownership changes, and let the test delete the pointer it owns.
@wwbmmm
wwbmmm requested a lite review from Copilot November 23, 2026 05:39
@wwbmmm

wwbmmm commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

[replied by brpc-oncall robot] Confirmed and fixed. copy_and_fill_server_options() transfers ownership of the pointers in the caller's ServerOptions into _options, and the enabled_protocols validation ran after it, so a rejected configuration adopted pointers (e.g. http_master_service) that the caller may still own.

ValidateEnabledProtocols() now takes the user-provided ServerOptions and runs right after the existing pre-adoption validations, before copy_and_fill_server_options(). A rejected Start() therefore leaves ownership untouched; the http_master_service test releases the pointer itself.

Note: while stress-running brpc_server_unittest I hit a rare pre-existing hang during Server::Join() (ordinary_services_are_not_served_on_internal_port, ~1/20 full runs). I reproduced the same rate on the base commit 51e26d5 without this PR, so it is unrelated to this change. brpc_server_unittest passes all 58 tests.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are identified for the protocol-filtering, validation, restart, and documentation changes.

No open issues 🎉

Review effort: Lite

@wwbmmm
wwbmmm requested a review from chenBright November 24, 2026 04:15
Comment thread src/brpc/server.cpp Outdated
delete _am;
_am = nullptr;
delete _internal_am;
_internal_am = nullptr;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

GetStat() can pass the null check before a second Start() deletes _am, then read the counters from the freed listener. Join() only waits for the server's own statistics thread. Please protect the entire period during which external readers use the listener, or have GetStat() read counters owned by Server.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] Removed the deletion. Acceptors are created once by the first Start() and are no longer destroyed when a stopped Server is restarted, so GetStat()/SetMaxConnections() can never observe a freed listener. A restart with a different enabled_protocols now fails with an error instead of reusing the stale handlers (test: restart_rejects_changed_enabled_protocols).

Comment thread src/brpc/server.cpp Outdated
delete _am;
_am = nullptr;
delete _internal_am;
_internal_am = nullptr;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

When idle_timeout_sec is enabled, CloseIdleConnections may already have started before Socket::Create() fails. The listener is still READY, so both StopAccept() and Join() return immediately during destruction. Please clean up the cleanup thread on this failure path; otherwise, after a retry executes the delete here, the thread will still use the old this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] With the restart-time deletion removed, the acceptor is destroyed only by the Server destructor. On that path StartAccept() has no soft failure after CloseIdleConnections starts: the invalid-fd and force-ssl checks happen before it and a Socket::Create() failure is LOG(FATAL) (abort), so the cleanup thread cannot outlive the acceptor. No change is needed here; if you prefer, I can still make Acceptor stop the thread on any early return.

Comment thread src/brpc/server.cpp Outdated
delete _am;
_am = nullptr;
delete _internal_am;
_internal_am = nullptr;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A short-lived connection can enter recycling before it is added to _socket_map. When AddressFailedAsWell() returns failure, the socket version may have just become invalid while BeforeRecycle() is still pending. In that case, Join() cannot see the connection, and a restart may delete the listener before the callback accesses it. Please register the socket before I/O, or have the socket hold the listener until the callback completes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] This window is pre-existing in Acceptor (it applies to the destructor path as well) and the withdrawn change was what made it reachable on restart: acceptors are no longer deleted at restart, so a restart can no longer free the listener while a pending BeforeRecycle() uses it. I did not restructure socket registration in the accept loop in this PR; that is an independent fix.

Comment thread src/brpc/server.cpp Outdated
delete _am;
_am = nullptr;
delete _internal_am;
_internal_am = nullptr;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deleting the old listener here relies on Join() having waited for the listening socket to be recycled. _listened_fd == 0 is valid, but it does not enter the wait loop in Acceptor::Join(). Please check completion against the actual sentinel, -1, to prevent an event thread that still holds the socket from calling back into a freed object.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] Fixed: Acceptor::Join() now waits while _listened_fd >= 0, so fd 0 is handled like any other listened fd and -1 remains the only recycled sentinel.

Comment thread src/brpc/server.cpp
// rdma_handshake is always served since it only handles the
// transport level handshake and dispatches no request.
RPC_VLOG << "Skip protocol=" << protocols[i].name;
continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

enabled_protocols="h2" with alpns="http,h2" passes startup validation. A client that supports both protocols will negotiate the server-preferred http/1.1, then be disconnected on its first request. Please ensure ALPN selects only protocols with installed parsers, or report the configuration conflict at startup.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] Fixed: InitALPNOptions() rejects any alpn whose protocol is not in enabled_protocols (errno=EINVAL), so a TLS client can no longer negotiate a protocol without an installed handler. Test: enabled_protocols_must_include_alpn_protocols.

Comment thread src/brpc/server.cpp
// configuration does not transfer their ownership to this server.
if (ValidateEnabledProtocols(real_opt) != 0) {
return -1;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

bthread_init_fn runs after this point, when AddService() still accepts REST mappings. A single callback can cause a baidu_std-only server to report both successful registration and startup, while the new route remains inaccessible. Please retain the early ownership check and ensure that service table changes after validation also comply with the HTTP dependency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] Fixed: the early check on the user-provided options is kept (it still runs before copy_and_fill_server_options() adopts the pointers), and ValidateEnabledProtocols() is called again after bthread_init_fn returns, before builtin services and listeners. Test: restful_service_added_in_init_fn_requires_http.

Comment thread src/brpc/server.h
// dispatching no request; naming it here is allowed and changes nothing.
// Builtin and restful services as well as http_master_service are served
// through http/h2, so if any of them is enabled, http or h2 must be listed
// as well, otherwise Server::Start() fails.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It would be helpful to also document ownership after failure here. If protocol validation rejects the configuration, the caller needs to free the newly supplied http_master_service, as the new test does. If failure occurs later during port binding, the object is already owned by Server. The field comment currently says only that the server destructor frees it, so the caller cannot choose the correct cleanup based solely on Start() == -1.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] Documented at the top of ServerOptions: a Start() rejected by the validation adopts nothing and the caller still owns the pointers; once Start() gets past the validation, the Server owns them and frees them in its destructor.

Comment thread src/brpc/server.cpp
std::vector<std::string> fixes;
if (options.has_builtin_services) {
features.push_back("ServerOptions.has_builtin_services is true");
fixes.push_back("set ServerOptions.has_builtin_services=false");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If this Server has previously started successfully with built-in services, setting has_builtin_services=false as suggested here will cause the next attempt to be rejected by the _builtin_service_count > 0 consistency check. Please provide an actionable fix based on the existing registration state.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] The message now checks the registration state: when _builtin_service_count > 0 it reports that builtin services are already registered and suggests creating a new Server with has_builtin_services=false instead of an option change that cannot work. Test: registered_builtin_services_hint_to_use_new_server.

Comment thread src/brpc/server.cpp
// configuration does not transfer their ownership to this server.
if (ValidateEnabledProtocols(real_opt) != 0) {
return -1;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The public contract for Start() includes setting errno on failure. This configuration rejection path currently only returns -1, so callers may read an error code left by a previous operation. Please return a consistent EINVAL for protocol configuration errors.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] Protocol configuration rejections (unknown names, missing http/h2, ALPN conflict, changed whitelist on restart) now set errno = EINVAL, and the new tests assert it.

Comment thread test/brpc_server_unittest.cpp Outdated
ASSERT_EQ(-1, server.Start(ep, &opt));
// Unknown names are rejected before builtin services are added, so this
// error is not masked by the http/h2 requirement of builtin services.
ASSERT_EQ(0u, server._builtin_service_count);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Even if the unknown-name check is skipped entirely, hehe baidu_std will fail before registering built-in services because it lacks http/h2. Consider using http hehe to test the unknown name separately, and checking the actual diagnostic for the original input with both errors, so the test covers the error priority described in the comment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[replied by brpc-oncall robot] invalid_protocol_in_enabled_protocols now covers both hehe baidu_std and http hehe, captures logs with logging::StringSink and asserts the unknown-name diagnostic (plus errno=EINVAL and that no builtin service was added), so the priority is actually verified rather than inferred.

Stop deleting the acceptors when a stopped Server is restarted: acceptors
are only created once, so restarting with a different enabled_protocols
now fails with an actionable error instead of reusing stale handlers or
destroying a listener that GetStat() and other readers may still use.

Also:
- reject ALPN protocols that are not in enabled_protocols at startup,
  otherwise TLS clients negotiate a protocol without a handler;
- clear _global_restful_map in ClearServices() so a cleared Server is not
  treated as still having restful services;
- validate again after bthread_init_fn, which may add restful services;
- report already registered builtin services instead of suggesting an
  option change that cannot work, and set errno=EINVAL on rejections;
- document the ownership of ServerOptions pointers after a failed start;
- wait for a non-negative listened fd in Acceptor::Join() since fd 0 is
  valid.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Approval is blocked because active moderate findings identify assertion paths that can leave a global logging sink pointing to a destroyed stack-local object, risking dangling-pointer use in later tests.

1 open issue

Review effort: Lite

Comment on lines +486 to +487
ASSERT_EQ(-1, server.Start(ep, &opt));
logging::SetLogSink(old_sink);
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.

3 participants