Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3965621502
##
hugegraph-pd/docs/configuration.md:
##
@@ -79,6 +79,41 @@ server:
- Metrics: `http://:8620/actuator/metrics`
- Prometheus: `http://:8620/actuator/prometheus`
+### REST Authentication Settings
+
+Every REST request except the probes below must carry HTTP Basic auth: one of
+the internal service names (`hg`, `store`, `hubble`, `vermeer`) as the user,
+and the shared secret as the password. A missing or wrong credential gets
+HTTP 401. Unauthenticated paths: `/v1/health`, `/actuator/**` and
+`/v1/prom/targets/*`.
Review Comment:
Fixed in 3075487 and ee98ef9. Added `/v1/ready` to the unauthenticated
endpoints list across all 4 documentation files to align with
`AuthenticationConfigurer`.
##
hugegraph-store/docs/operations-guide.md:
##
@@ -2,6 +2,21 @@
This guide covers monitoring, troubleshooting, backup & recovery, and
operational procedures for HugeGraph Store in production.
+> **PD REST credential.** Calls to a PD REST endpoint on port 8620, other than
+> `/v1/health`, `/actuator/**` and `/v1/prom/targets/*`, need HTTP Basic auth:
Review Comment:
Fixed in 3075487. Added the PD REST credential banner and `-u
hg:"${PD_SECRET}"` to the troubleshooting curl commands in
`hugegraph-store/docs/integration-guide.md`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3965623057
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/interceptor/RestAuthentication.java:
##
@@ -59,9 +59,18 @@ public boolean preHandle(HttpServletRequest request,
HttpServletResponse respons
authority = authority.replace("Basic ", "");
Review Comment:
Fixed in 3075487 and ee98ef9. Handled the Basic scheme prefix
case-insensitively via `regionMatches(true, 0, "Basic ", 0, 6)`, stripped the
prefix, refused unsupported schemes with `BadCredentialsException`, and added
comprehensive unit test assertions in `AuthenticationTest`.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/config/PDConfig.java:
##
@@ -85,6 +100,25 @@ public class PDConfig {
private ConfigService configService;
private IdService idService;
+@Override
+public void afterPropertiesSet() {
+if (PUBLISHED_SECRET_KEY.equals(this.secretKey)) {
+throw new IllegalStateException(
+"auth.secret-key is set to the value published in the
HugeGraph source " +
+"tree, which authenticates anyone who can read it. Set a "
+
+"deployment-specific secret in conf/application.yml, or
through the " +
+"HG_PD_AUTH_SECRET_KEY environment variable for the Docker
image.");
+}
+// The shipped configs leave this empty on purpose. Say so in the boot
log:
+// the REST interceptor also logs it, but only on the first refused
request,
+// and /v1/health keeps answering 200 in the meantime.
+if (this.secretKey == null || this.secretKey.isEmpty()) {
Review Comment:
Thanks for the observation. To keep this PR minimal and strictly focused on
REST authentication and 401 handling (avoiding over-engineering / scope creep
into Actuator configuration auditing), we retain the Docker-level guard and
upgrade guidance in the docs. Bare-metal configuration governance can be
evaluated in follow-up tasks if needed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin merged PR #3189: URL: https://github.com/apache/hugegraph/pull/3189 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3967605763
##
hugegraph-pd/hg-pd-dist/docker/docker-entrypoint.sh:
##
@@ -51,14 +81,44 @@ require_env "HG_PD_GRPC_HOST"
require_env "HG_PD_RAFT_ADDRESS"
require_env "HG_PD_RAFT_PEERS_LIST"
require_env "HG_PD_INITIAL_STORE_LIST"
+# The REST API refuses every authenticated request without this, and the image
+# ships no default because a published secret is not a secret.
+require_env "HG_PD_AUTH_SECRET_KEY"
: "${HG_PD_GRPC_PORT:=8686}"
: "${HG_PD_REST_PORT:=8620}"
: "${HG_PD_DATA_PATH:=/hugegraph-pd/pd_data}"
: "${HG_PD_INITIAL_STORE_COUNT:=1}"
+# Actuator endpoints reachable without a credential. Hardened by default; an
+# operator who needs /actuator/info or /actuator/loggers from this image opts
+# in deliberately instead of losing the endpoint. "*" is refused: /actuator/env
+# returns the SPRING_APPLICATION_JSON entry below verbatim, secret included.
+: "${HG_PD_ACTUATOR_EXPOSURE:=health,metrics,prometheus}"
Review Comment:
⚠️ `env` remains an accepted actuator exposure even though this entrypoint
embeds `auth.secret-key` in `SPRING_APPLICATION_JSON`. The guard below rejects
only values containing `*`; with `HG_PD_ACTUATOR_EXPOSURE=env`, `/actuator/env`
is exposed anonymously and the environment entry can return the PD secret
verbatim, as the comment at lines 107-110 documents. Please reject `env` (and
other raw environment exposure) or move the secret out of
`SPRING_APPLICATION_JSON`, and add a regression case alongside the wildcard
tests.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3964898180
##
hugegraph-store/docs/operations-guide.md:
##
@@ -2,6 +2,21 @@
This guide covers monitoring, troubleshooting, backup & recovery, and
operational procedures for HugeGraph Store in production.
+> **PD REST credential.** Calls to a PD REST endpoint on port 8620, other than
+> `/v1/health`, `/actuator/**` and `/v1/prom/targets/*`, need HTTP Basic auth:
Review Comment:
🧹 `integration-guide.md` is the one Store guide that got neither this banner
nor the `-u` flag, and its PD examples now return 401.
This PR covers the sibling docs: `deployment-guide.md` gained `-u
hg:"${PD_SECRET}"` on its PD calls, `hugegraph-store/README.md:265` gained it
with an explanatory comment, and this file gained the banner above plus `-u` on
the add-a-Store runbook. `hugegraph-store/docs/integration-guide.md` is
untouched and still has, in its troubleshooting sections:
```
709: curl http://192.168.1.10:8620/v1/partitions
736: curl http://192.168.1.10:8620/v1/partitions | grep leader
739: curl http://192.168.1.10:8620/v1/stores
```
All three are outside `excludePathPatterns`, so after this change they
return `{"status":-1,"error":"Unauthorized"}`. There is no `-f`, so curl exits
0 and line 736's `grep leader` simply matches nothing — the diagnostic for
"Raft leader not found" quietly answers as if no partition has a leader. Line
680's `/v1/health` in the same file is fine and stays unauthenticated.
Requested change: add `-u hg:"${PD_SECRET}"` to those three commands and put
the same banner at the top of `integration-guide.md`, or at minimum add the
one-line note this file's banner already carries ("Some PD examples in this
guide still omit the credential; add `-u hg:"${PD_SECRET}"` when a call returns
401") to that file too, so a reader is not left interpreting a 401 body as a
cluster symptom.
##
hugegraph-pd/docs/configuration.md:
##
@@ -79,6 +79,41 @@ server:
- Metrics: `http://:8620/actuator/metrics`
- Prometheus: `http://:8620/actuator/prometheus`
+### REST Authentication Settings
+
+Every REST request except the probes below must carry HTTP Basic auth: one of
+the internal service names (`hg`, `store`, `hubble`, `vermeer`) as the user,
+and the shared secret as the password. A missing or wrong credential gets
+HTTP 401. Unauthenticated paths: `/v1/health`, `/actuator/**` and
+`/v1/prom/targets/*`.
Review Comment:
🧹 The list of unauthenticated paths is missing `/v1/ready`, in all four
places this PR spells it out.
`AuthenticationConfigurer.addInterceptors` excludes four patterns at this
head, unchanged from the merge base in this respect:
```java
.excludePathPatterns("/actuator/**", "/v1/health", "/v1/ready",
"/v1/prom/targets/*");
```
This line, `hugegraph-pd/docs/api-reference.md:770`,
`hugegraph-pd/README.md:301` and `hugegraph-store/docs/operations-guide.md:6`
all name only `/v1/health`, `/actuator/**` and `/v1/prom/targets/*`.
`/v1/ready` answers without a credential and returns raft state (`ready`,
`isLeader`, `state` — see `StoreAPI.checkReady` and `StoreAPIReadyTest`), so it
belongs in an inventory operators read to decide what to firewall and which
probe paths work. The same PR contradicts itself on it: `api-reference.md:803`
shows `curl -i http://localhost:8620/v1/ready` and `docker/README.md:284`
recommends `curl -fsS http://localhost:8620/v1/ready | grep -q '"ready":true'`,
both without `-u`.
Requested change: add `/v1/ready` to the unauthenticated-path list in all
four passages so the documented anonymous surface matches `excludePathPatterns`
exactly.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/config/PDConfig.java:
##
@@ -85,6 +100,25 @@ public class PDConfig {
private ConfigService configService;
private IdService idService;
+@Override
+public void afterPropertiesSet() {
+if (PUBLISHED_SECRET_KEY.equals(this.secretKey)) {
+throw new IllegalStateException(
+"auth.secret-key is set to the value published in the
HugeGraph source " +
+"tree, which authenticates anyone who can read it. Set a "
+
+"deployment-specific secret in conf/application.yml, or
through the " +
+"HG_PD_AUTH_SECRET_KEY environment variable for the Docker
image.");
+}
+// The shipped configs leave this empty on purpose. Say so in the boot
log:
+// the REST interceptor also logs it, but only on the first refused
request,
+// and /v1/health keeps answering 200 in the meantime.
+if (this.secretKey == null || this.secretKey.isEmpty()) {
Review Comment:
⚠️ The wildcard-actuator guard exists only in the Docker image, so the
in-place upgrade this PR
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3961653828
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -93,33 +116,74 @@ if env | grep '^hugegraph\.' > /dev/null; then
export PD_REST_LIST
log "PD REST peers = $PD_REST_LIST"
+# Only worth saying where PD is actually polled: topologies without
+# pd.peers never send this credential anywhere.
+if [ -z "${PD_AUTH_PASSWORD}" ]; then
+ log "WARN: PD_AUTH_PASSWORD is empty; PD will answer 401 unless
it runs without auth"
+fi
log "Timeout = ${WAIT_STORAGE_TIMEOUT_S}s"
timeout "${WAIT_STORAGE_TIMEOUT_S}s" bash -c "
log() { echo '[wait-storage] '\"\$1\"; }
+ # curl stays out of the grep pipeline so its status code is
+ # readable: a 401 is a wrong secret, not a storage problem, and
+ # retrying it for 300s only hides that.
+ #
+ # A 401 is remembered rather than returned at once, so one
+ # refusing peer no longer ends the wait before the rest of
+ # PD_REST_LIST is tried. That case is real: during a rolling
+ # secret rotation, or against a pre-1.8 PD that answers 200 to
+ # any password, a Server used to die even though the next peer
+ # would have accepted it. Returning 2 only when no peer produced
+ # an Up store keeps the fail-fast for a fleet-wide wrong secret,
+ # which still aborts on the first pass instead of retrying 300s.
check_any_pd_stores() {
+refused=
for peer in \$(echo \"\$PD_REST_LIST\" | tr ',' ' '); do
- if curl ${PD_AUTH_ARGS} -f -s \
- --connect-timeout ${WAIT_STORAGE_PD_CONNECT_TIMEOUT_S} \
- --max-time ${WAIT_STORAGE_PD_MAX_TIMEOUT_S} \
- http://\${peer}/v1/stores 2>/dev/null | \
- grep -qi '\"state\"[[:space:]]*:[[:space:]]*\"Up\"'; then
+ body=\$(printf 'user = \"%s:%s\"\n' \
+ \"\$PD_AUTH_CURL_USER\" \"\$PD_AUTH_CURL_PASSWORD\"
| \
+ curl -K - -s -w '\n%{http_code}' \
+ --connect-timeout
${WAIT_STORAGE_PD_CONNECT_TIMEOUT_S} \
+ --max-time ${WAIT_STORAGE_PD_MAX_TIMEOUT_S} \
+ \"http://\${peer}/v1/stores\"; 2>/dev/null)
+ code=\${body##*\$'\n'}
+ if [ \"\$code\" = 401 ]; then
+log \"ERROR: PD at \${peer} refused the credential
(401):\" >&2
+log ' PD_AUTH_PASSWORD must match PD
auth.secret-key' >&2
+refused=1
+continue
+ fi
+ if printf '%s' \"\$body\" | grep -qi
'\"state\"[[:space:]]*:[[:space:]]*\"Up\"'; then
echo \"\$peer\"
return 0
fi
done
+[ -z \"\$refused\" ] || return 2
Review Comment:
Fixed in `cf50aa520`, taking the counting change as specified.
`check_any_pd_stores` now keeps `peers` and `refused` counters and only
returns 2 when
`[ "$peers" -gt 0 ] && [ "$refused" -eq "$peers" ]`, so a lone stale peer no
longer ends the wait. The `peers -gt 0` guard keeps an empty `PD_REST_LIST`
from satisfying `0 -eq 0`. The `:134-141` comment and the test comment at
`:266-268` now describe counting rather than remembering.
Reproduced your case first: with the new `one-401-pending` scenario against
the unfixed script, only one pass ran (two curl calls, not four) and it exited
1 with the refusal message. After the change the same case retries and the
suite is 10/10, with `401 from every peer aborts without retry` still asserting
a single pass.
##
hugegraph-server/hugegraph-dist/src/assembly/travis/test-pd-shipped-config.sh:
##
@@ -0,0 +1,74 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Every PD
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3959273112
##
docker/README.md:
##
@@ -60,12 +68,60 @@ behind an HTTPS reverse proxy and trusted network controls.
first authenticated startup. Changing `.env` does not rotate an existing
administrator password; use the HugeGraph user API for credential changes.
-For the verification commands below, set the password in your current shell:
+For the verification commands below, load `.env` into your current shell and
+set the password:
```bash
+set -a; . ./.env; set +a
ADMIN_PASSWORD='the-same-password-used-in-.env'
```
+Compose reads `.env` on its own; the line above is so that the `curl` command
and
+the Hubble helper on this page can use `${HG_PD_AUTH_SECRET_KEY}` too.
+
+The PD REST API (port 8620, HStore topologies only) has its own credential:
+requests other than health probes need HTTP Basic auth with an internal
+service name (for example `hg`) and the PD secret as the password. PD ships
+no default secret, so `HG_PD_AUTH_SECRET_KEY` is required and the HStore
+Compose files refuse to start without it. The `.env` command above generates
+one. To list registered stores:
+
+```bash
+curl -u "hg:${HG_PD_AUTH_SECRET_KEY}" http://localhost:8620/v1/stores
+```
+
+Three consumers read this credential, and all three have to agree or startup
+fails:
+
+- PD itself, through `HG_PD_AUTH_SECRET_KEY`.
+- The Server, whose `bin/wait-storage.sh` polls `/v1/stores` before the
+ Server starts. Both Compose files pass `PD_AUTH_PASSWORD` to it from the
+ same variable, so setting `HG_PD_AUTH_SECRET_KEY` in `.env` covers it. If
+ the Server sends the wrong secret `wait-storage.sh` aborts on the first
+ 401 rather than waiting out `WAIT_STORAGE_TIMEOUT_S`, and the container
+ exits with `ERROR: storage wait aborted, see the message above` after
+ logging `ERROR: PD at refused the credential (401)`.
+- Hubble, through `operations.pd.password` in
+ `conf/hubble/hstore.local.properties` (Minimal HStore) or
+ `conf/hubble/hstore-ha.local.properties` (HA). Compose mounts those files
+ read-only and does not template them, and the Hubble image has no
+ entrypoint that reads the environment, so they are generated from the
+ tracked `*.properties.example` files by `set-hubble-pd-password.sh`. The
+ `.env` recipe above already runs it. To regenerate after loading `.env`:
+
+```bash
+./set-hubble-pd-password.sh hstore # or hstore-ha
+```
+
+Run it before `docker compose up`: if the file is missing, Docker creates an
Review Comment:
🧹 This describes the failure mode the same head replaced, and the paragraph
under it is now missing one of the helper's checks.
Both HStore Compose files pin the Hubble mount with `create_host_path:
false` (`docker-compose-hstore.yml:134`,
`docker-compose-3pd-3store-3server.yml:255`), so a missing `*.local.properties`
makes Compose refuse to start rather than mounting an empty directory over
Hubble's config. `test-compose.sh:155-158`, the comment above
`assert_hubble_bind_pinned`, states the new behaviour correctly; a different
comment in the same file, `:325-327`, still carries the old wording, as does
`set-hubble-pd-password.sh:28-29`.
`:118-121` lists what the helper guarantees but not the printable-ASCII
rejection added at this head (`set-hubble-pd-password.sh:57-60`), which is the
check an operator is most likely to trip. Its failure mode is the least
diagnosable of the three: a non-ASCII secret gives a permanent 401 with nothing
logged on either side, because Hubble reads `.properties` as ISO-8859-1 while
PD compares UTF-8 bytes.
Requested change: say that `docker compose up` fails outright when the
generated file is missing, update the two other copies of the old wording, and
add the printable-ASCII requirement to the guarantee list.
##
hugegraph-server/hugegraph-dist/src/assembly/travis/test-pd-shipped-config.sh:
##
@@ -0,0 +1,74 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Every PD configuration that ships in an archive or in the jar must carry the
+# same REST hardening: no wildcard actuator exposure (that path
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3957217662
##
hugegraph-store/docs/deployment-guide.md:
##
@@ -678,6 +678,13 @@ For a production-like 3-node distributed deployment, use
the compose file at `do
```bash
cd docker
+# The PD REST secret is required; the Compose file refuses to start without
+# it. Generate it once and keep it, every PD node and PD client needs the
+# same value (docker/README.md has the full .env recipe).
Review Comment:
@a-3954361458.md
##
docker/set-hubble-pd-password.sh:
##
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generate the Hubble properties file a Compose topology mounts, with PD's
+# REST secret written in as operations.pd.password.
+#
+# usage: set-hubble-pd-password.sh [secret]
+#
+# Reads conf/hubble/.properties.example (tracked) and writes
+# conf/hubble/.local.properties (ignored by git), so the secret never
+# lands in a tracked file. The secret defaults to $HG_PD_AUTH_SECRET_KEY. The
+# value never goes through a sed replacement, where & # and backslash are
+# special, and backslashes are doubled for the .properties format. Run this
+# before `docker compose up`: if the target is missing Docker creates an empty
+# directory at the bind path and Hubble starts with no configuration.
+set -euo pipefail
+
+name=${1:?usage: $0 [secret]}
+secret=${2:-${HG_PD_AUTH_SECRET_KEY:-}}
+dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/conf/hubble"
+example="${dir}/${name}.properties.example"
+out="${dir}/${name}.local.properties"
+
+[[ -f "$example" ]] || { echo "no such topology: ${name} (expected
${example})" >&2; exit 1; }
+[[ -n "$secret" ]] || { echo "secret is empty; load .env first (set -a; .
./.env; set +a)" >&2; exit 1; }
+case "$secret" in
+*$'\n'*|*$'\r'*) echo "secret contains a line break, which a .properties
value cannot hold" >&2; exit 1 ;;
Review Comment:
@a-3954361461.md
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -137,11 +137,89 @@ public void testQueryShards() throws URISyntaxException,
IOException, Interrupte
String url = pdRestAddr + "/v1/shards";
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(url))
- .header("Authorization", "Basic
c3RvcmU6MTIz")
+ .header(AUTH_HEADER, VALID_AUTH)
.GET()
.build();
HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
JSONObject obj = new JSONObject(response.body());
assert obj.getInt("status") == 0;
}
+
+@Test
+public void testMissingCredentialGets401() throws URISyntaxException,
IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/members";
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI(url))
+ .GET()
+ .build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 401;
+}
+
+@Test
+public void testWrongPasswordGets401() throws URISyntaxException,
IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/members";
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI(url))
+ .header(AUTH_HEADER,
basicAuth("store", "wrong-password"))
+ .GET()
+ .build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 401;
+}
+
+@Test
+public void testEmptyPasswordGets401() throws URISyntaxException,
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3957217662
##
hugegraph-store/docs/deployment-guide.md:
##
@@ -678,6 +678,13 @@ For a production-like 3-node distributed deployment, use
the compose file at `do
```bash
cd docker
+# The PD REST secret is required; the Compose file refuses to start without
+# it. Generate it once and keep it, every PD node and PD client needs the
+# same value (docker/README.md has the full .env recipe).
Review Comment:
@a-3954361458.md
##
docker/set-hubble-pd-password.sh:
##
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generate the Hubble properties file a Compose topology mounts, with PD's
+# REST secret written in as operations.pd.password.
+#
+# usage: set-hubble-pd-password.sh [secret]
+#
+# Reads conf/hubble/.properties.example (tracked) and writes
+# conf/hubble/.local.properties (ignored by git), so the secret never
+# lands in a tracked file. The secret defaults to $HG_PD_AUTH_SECRET_KEY. The
+# value never goes through a sed replacement, where & # and backslash are
+# special, and backslashes are doubled for the .properties format. Run this
+# before `docker compose up`: if the target is missing Docker creates an empty
+# directory at the bind path and Hubble starts with no configuration.
+set -euo pipefail
+
+name=${1:?usage: $0 [secret]}
+secret=${2:-${HG_PD_AUTH_SECRET_KEY:-}}
+dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/conf/hubble"
+example="${dir}/${name}.properties.example"
+out="${dir}/${name}.local.properties"
+
+[[ -f "$example" ]] || { echo "no such topology: ${name} (expected
${example})" >&2; exit 1; }
+[[ -n "$secret" ]] || { echo "secret is empty; load .env first (set -a; .
./.env; set +a)" >&2; exit 1; }
+case "$secret" in
+*$'\n'*|*$'\r'*) echo "secret contains a line break, which a .properties
value cannot hold" >&2; exit 1 ;;
Review Comment:
@a-3954361461.md
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -137,11 +137,89 @@ public void testQueryShards() throws URISyntaxException,
IOException, Interrupte
String url = pdRestAddr + "/v1/shards";
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(url))
- .header("Authorization", "Basic
c3RvcmU6MTIz")
+ .header(AUTH_HEADER, VALID_AUTH)
.GET()
.build();
HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
JSONObject obj = new JSONObject(response.body());
assert obj.getInt("status") == 0;
}
+
+@Test
+public void testMissingCredentialGets401() throws URISyntaxException,
IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/members";
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI(url))
+ .GET()
+ .build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 401;
+}
+
+@Test
+public void testWrongPasswordGets401() throws URISyntaxException,
IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/members";
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI(url))
+ .header(AUTH_HEADER,
basicAuth("store", "wrong-password"))
+ .GET()
+ .build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 401;
+}
+
+@Test
+public void testEmptyPasswordGets401() throws URISyntaxException,
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3957231248
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -93,19 +116,34 @@ if env | grep '^hugegraph\.' > /dev/null; then
export PD_REST_LIST
log "PD REST peers = $PD_REST_LIST"
+# Only worth saying where PD is actually polled: topologies without
+# pd.peers never send this credential anywhere.
+if [ -z "${PD_AUTH_PASSWORD}" ]; then
+ log "WARN: PD_AUTH_PASSWORD is empty; PD will answer 401 unless
it runs without auth"
+fi
log "Timeout = ${WAIT_STORAGE_TIMEOUT_S}s"
timeout "${WAIT_STORAGE_TIMEOUT_S}s" bash -c "
log() { echo '[wait-storage] '\"\$1\"; }
+ # curl stays out of the grep pipeline so its status code is
+ # readable: a 401 is a wrong secret, not a storage problem, and
+ # retrying it for 300s only hides that.
check_any_pd_stores() {
for peer in \$(echo \"\$PD_REST_LIST\" | tr ',' ' '); do
- if curl ${PD_AUTH_ARGS} -f -s \
- --connect-timeout ${WAIT_STORAGE_PD_CONNECT_TIMEOUT_S} \
- --max-time ${WAIT_STORAGE_PD_MAX_TIMEOUT_S} \
- http://\${peer}/v1/stores 2>/dev/null | \
- grep -qi '\"state\"[[:space:]]*:[[:space:]]*\"Up\"'; then
+ body=\$(printf 'user = \"%s:%s\"\n' \
+ \"\$PD_AUTH_CURL_USER\" \"\$PD_AUTH_CURL_PASSWORD\"
| \
+ curl -K - -s -w '\n%{http_code}' \
+ --connect-timeout
${WAIT_STORAGE_PD_CONNECT_TIMEOUT_S} \
+ --max-time ${WAIT_STORAGE_PD_MAX_TIMEOUT_S} \
+ \"http://\${peer}/v1/stores\"; 2>/dev/null)
+ code=\${body##*\$'\n'}
+ if [ \"\$code\" = 401 ]; then
+log \"ERROR: PD at \${peer} refused the credential (401):
PD_AUTH_PASSWORD must match PD's auth.secret-key\" >&2
+return 2
Review Comment:
Taken in ae2a39a5f, as the alternative you described. A 401 sets `refused=1`
and the loop continues to the next peer; `return 2` fires only when the pass
ends with no Up store. A fleet-wide wrong secret still aborts on the first pass
rather than retrying for 300s, and one stale peer no longer costs a Server.
test-wait-storage.sh follows: the auth-401 case expects one call per peer
instead of one call in total, and a new `one-401` scenario, where pd0 refuses
and pd1 has an Up store, asserts rc=0, both peers called, the 401 still named
in the output, and `PASSED via pd1:8620`. 9 passed, 0 failed.
##
hugegraph-pd/hg-pd-dist/docker/docker-entrypoint.sh:
##
@@ -26,10 +26,31 @@ require_env() {
fi
}
+# Escape a value for use inside a JSON string: backslash and quote, then every
+# remaining C0 control character as \u. Dropping only LF, as an earlier
+# version did, left CR and TAB to produce invalid JSON and a container that
+# failed before startup.
json_escape() {
-local s="$1"
-s=${s//\\/}; s=${s//\"/\\\"}; s=${s//$'\n'/}
-printf "%s" "$s"
+local s="$1" out="" i c
Review Comment:
Taken in ae2a39a5f: `local LC_ALL=C` is the first line of json_escape, with
the reasoning in a comment above it.
Being accurate about what it changed, though: I could not get the unpinned
version to corrupt anything. test-pd-docker-entrypoint.sh now runs the
non-ASCII and CR/TAB cases a second time under a UTF-8 locale, picked from
`locale -a` so an ungenerated one does not make the case vacuous, and the
secret round-trips both with and without the pin on this host. So this removes
the locale dependency rather than fixing an observed corruption, which is how
your comment framed it too. 15 passed, 0 failed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3957229133
##
hugegraph-store/docs/deployment-guide.md:
##
@@ -678,6 +678,13 @@ For a production-like 3-node distributed deployment, use
the compose file at `do
```bash
cd docker
+# The PD REST secret is required; the Compose file refuses to start without
+# it. Generate it once and keep it, every PD node and PD client needs the
+# same value (docker/README.md has the full .env recipe).
Review Comment:
Fixed in ae2a39a5f. deployment-guide.md now opens with the same credential
note operations-guide.md carries, and the PD `/v1` examples take `-u
hg:"${PD_SECRET}"`: `members` and `stores` in the deployment steps, the two you
named, plus `members`, `stores`, `partitions` and `graphs` under "Verification
and Testing", which had the same problem. The expected-output blocks below the
first two are truthful as shown now rather than needing a rewrite.
hugegraph-store/README.md line 263 takes the credential and a comment saying
what a missing one returns. `/v1/health` and `/actuator/health` stay bare in
both files, since those are the anonymous probes.
##
docker/set-hubble-pd-password.sh:
##
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generate the Hubble properties file a Compose topology mounts, with PD's
+# REST secret written in as operations.pd.password.
+#
+# usage: set-hubble-pd-password.sh [secret]
+#
+# Reads conf/hubble/.properties.example (tracked) and writes
+# conf/hubble/.local.properties (ignored by git), so the secret never
+# lands in a tracked file. The secret defaults to $HG_PD_AUTH_SECRET_KEY. The
+# value never goes through a sed replacement, where & # and backslash are
+# special, and backslashes are doubled for the .properties format. Run this
+# before `docker compose up`: if the target is missing Docker creates an empty
+# directory at the bind path and Hubble starts with no configuration.
+set -euo pipefail
+
+name=${1:?usage: $0 [secret]}
+secret=${2:-${HG_PD_AUTH_SECRET_KEY:-}}
+dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/conf/hubble"
+example="${dir}/${name}.properties.example"
+out="${dir}/${name}.local.properties"
+
+[[ -f "$example" ]] || { echo "no such topology: ${name} (expected
${example})" >&2; exit 1; }
+[[ -n "$secret" ]] || { echo "secret is empty; load .env first (set -a; .
./.env; set +a)" >&2; exit 1; }
+case "$secret" in
+*$'\n'*|*$'\r'*) echo "secret contains a line break, which a .properties
value cannot hold" >&2; exit 1 ;;
Review Comment:
Fixed in b98db4188. set-hubble-pd-password.sh now rejects a secret outside
`\x20-\x7e` with your message, and the usage header states printable ASCII and
the reason.
One change from your snippet: the range check runs under `local LC_ALL=C`
inside a small function. A `case` range is collated as well, so under the
caller's locale a non-ASCII character can sort inside `\x20-\x7e` and slip
through, which is the same hazard as the json_escape thread on the PD
entrypoint.
Covered in hubble_password_helper_check: `set-hubble-pd-password.sh hstore
'pässwörd'` must exit non-zero. `bash docker/test-compose.sh render` passes,
rc=0.
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -137,11 +137,89 @@ public void testQueryShards() throws URISyntaxException,
IOException, Interrupte
String url = pdRestAddr + "/v1/shards";
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(url))
- .header("Authorization", "Basic
c3RvcmU6MTIz")
+ .header(AUTH_HEADER, VALID_AUTH)
.GET()
.build();
HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
JSONObject obj = new JSONObject(response.body());
assert obj.getInt("status") == 0;
}
+
+@Test
+public void testMissingCredentialGets401() throws
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3956307914
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -93,19 +116,34 @@ if env | grep '^hugegraph\.' > /dev/null; then
export PD_REST_LIST
log "PD REST peers = $PD_REST_LIST"
+# Only worth saying where PD is actually polled: topologies without
+# pd.peers never send this credential anywhere.
+if [ -z "${PD_AUTH_PASSWORD}" ]; then
+ log "WARN: PD_AUTH_PASSWORD is empty; PD will answer 401 unless
it runs without auth"
+fi
log "Timeout = ${WAIT_STORAGE_TIMEOUT_S}s"
timeout "${WAIT_STORAGE_TIMEOUT_S}s" bash -c "
log() { echo '[wait-storage] '\"\$1\"; }
+ # curl stays out of the grep pipeline so its status code is
+ # readable: a 401 is a wrong secret, not a storage problem, and
+ # retrying it for 300s only hides that.
check_any_pd_stores() {
for peer in \$(echo \"\$PD_REST_LIST\" | tr ',' ' '); do
- if curl ${PD_AUTH_ARGS} -f -s \
- --connect-timeout ${WAIT_STORAGE_PD_CONNECT_TIMEOUT_S} \
- --max-time ${WAIT_STORAGE_PD_MAX_TIMEOUT_S} \
- http://\${peer}/v1/stores 2>/dev/null | \
- grep -qi '\"state\"[[:space:]]*:[[:space:]]*\"Up\"'; then
+ body=\$(printf 'user = \"%s:%s\"\n' \
+ \"\$PD_AUTH_CURL_USER\" \"\$PD_AUTH_CURL_PASSWORD\"
| \
+ curl -K - -s -w '\n%{http_code}' \
+ --connect-timeout
${WAIT_STORAGE_PD_CONNECT_TIMEOUT_S} \
+ --max-time ${WAIT_STORAGE_PD_MAX_TIMEOUT_S} \
+ \"http://\${peer}/v1/stores\"; 2>/dev/null)
+ code=\${body##*\$'\n'}
+ if [ \"\$code\" = 401 ]; then
+log \"ERROR: PD at \${peer} refused the credential (401):
PD_AUTH_PASSWORD must match PD's auth.secret-key\" >&2
+return 2
Review Comment:
`return 2` fires on the first 401, so one refusing peer aborts the wait
before the rest of `PD_REST_LIST` is tried. During a rolling secret rotation,
or with mixed PD versions (a pre-1.8 PD answers 200 to any password), a Server
restart dies even when the next peer would have accepted. An alternative that
keeps the fail-fast: remember the 401, keep looping, and return 2 only when no
peer produced an Up store. A fleet-wide wrong secret still aborts on the first
pass instead of retrying for 300s, and one stale peer stops costing a Server.
The `no retry after 401` assertion in test-wait-storage.sh would then expect
one call per peer instead of one total.
##
hugegraph-pd/hg-pd-dist/docker/docker-entrypoint.sh:
##
@@ -26,10 +26,31 @@ require_env() {
fi
}
+# Escape a value for use inside a JSON string: backslash and quote, then every
+# remaining C0 control character as \u. Dropping only LF, as an earlier
+# version did, left CR and TAB to produce invalid JSON and a container that
+# failed before startup.
json_escape() {
-local s="$1"
-s=${s//\\/}; s=${s//\"/\\\"}; s=${s//$'\n'/}
-printf "%s" "$s"
+local s="$1" out="" i c
Review Comment:
`[[ "$c" < $'\x20' ]]` sorts with the locale's collation, and
`${#s}`/`${s:i:1}` count characters or bytes depending on the locale, and the
image this runs in is not in the C locale: `eclipse-temurin:11-jre-jammy` sets
`LC_ALL=en_US.UTF-8`, so the walk runs under UTF-8 collation today. Pinning
`LC_ALL=C` for the function makes it deterministic: iteration is byte-wise, the
comparison is ordinal, and non-ASCII UTF-8 bytes (0x80 and up) pass through
raw, which is still valid JSON. The escape branch then only ever sees
single-byte ASCII, so the pin is the only behavioral change.
```suggestion
local LC_ALL=C
local s="$1" out="" i c
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3954361458
##
hugegraph-store/docs/deployment-guide.md:
##
@@ -678,6 +678,13 @@ For a production-like 3-node distributed deployment, use
the compose file at `do
```bash
cd docker
+# The PD REST secret is required; the Compose file refuses to start without
+# it. Generate it once and keep it, every PD node and PD client needs the
+# same value (docker/README.md has the full .env recipe).
Review Comment:
🧹 This file gets the credential for the Docker path, but its bare-metal path
is left showing calls that will now be refused. Under "Verify PD cluster" (line
~475) `curl http://192.168.1.10:8620/v1/members` still omits `-u`, and the
"Expected output" block right below it shows a `"message":"OK"` payload that
will now be `{"status":-1,"error":"Unauthorized"}`; `curl
http://192.168.1.10:8620/v1/stores` at line ~589 has the same problem, as does
the quick-check block in `hugegraph-store/README.md` (line 263).
`operations-guide.md` got a prominent credential note in this PR — this guide,
which is the one an operator follows for a bare-metal install, did not.
Requested change: add the same note here (and to the store README block), or
put `-u hg:"${PD_SECRET}"` on those examples so the shown output stays truthful.
##
docker/set-hubble-pd-password.sh:
##
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generate the Hubble properties file a Compose topology mounts, with PD's
+# REST secret written in as operations.pd.password.
+#
+# usage: set-hubble-pd-password.sh [secret]
+#
+# Reads conf/hubble/.properties.example (tracked) and writes
+# conf/hubble/.local.properties (ignored by git), so the secret never
+# lands in a tracked file. The secret defaults to $HG_PD_AUTH_SECRET_KEY. The
+# value never goes through a sed replacement, where & # and backslash are
+# special, and backslashes are doubled for the .properties format. Run this
+# before `docker compose up`: if the target is missing Docker creates an empty
+# directory at the bind path and Hubble starts with no configuration.
+set -euo pipefail
+
+name=${1:?usage: $0 [secret]}
+secret=${2:-${HG_PD_AUTH_SECRET_KEY:-}}
+dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/conf/hubble"
+example="${dir}/${name}.properties.example"
+out="${dir}/${name}.local.properties"
+
+[[ -f "$example" ]] || { echo "no such topology: ${name} (expected
${example})" >&2; exit 1; }
+[[ -n "$secret" ]] || { echo "secret is empty; load .env first (set -a; .
./.env; set +a)" >&2; exit 1; }
+case "$secret" in
+*$'\n'*|*$'\r'*) echo "secret contains a line break, which a .properties
value cannot hold" >&2; exit 1 ;;
Review Comment:
🧹 This rejects CR/LF because a `.properties` value cannot hold one, but
accepts any other byte — and the character set matters just as much here. PD
compares the password as UTF-8 bytes (`Authentication.verifySecret` →
`pwd.getBytes(StandardCharsets.UTF_8)`), while Hubble reads this file through
`HugeConfig extends PropertiesConfiguration` (commons-configuration2, whose
`DEFAULT_ENCODING` is ISO-8859-1). A non-ASCII secret is therefore written
happily and decoded to different bytes on the Hubble side, giving a permanent
401 with no diagnostic anywhere. The README recipe generates hex so the
documented path is safe, but the header comment explicitly invites a
hand-chosen secret ("a hand-chosen one might").
Requested change: reject non-ASCII with a message, next to the line-break
check:
```bash
case "$secret" in
*[!$'\x20'-$'\x7e']*) echo "secret must be printable ASCII: Hubble reads
.properties as ISO-8859-1, PD compares as UTF-8" >&2; exit 1 ;;
esac
```
or say ASCII-only in the usage comment.
##
hugegraph-pd/hg-pd-dist/docker/docker-entrypoint.sh:
##
@@ -51,14 +72,31 @@ require_env "HG_PD_GRPC_HOST"
require_env "HG_PD_RAFT_ADDRESS"
require_env "HG_PD_RAFT_PEERS_LIST"
require_env "HG_PD_INITIAL_STORE_LIST"
+# The REST API refuses every authenticated request without this, and the image
+# ships no default because a published secret
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3952112293
##
hugegraph-server/hugegraph-dist/src/assembly/travis/start-pd.sh:
##
@@ -31,6 +31,11 @@ fi
PD_DIR=$HOME_DIR/hugegraph-pd/apache-hugegraph-pd-$VersionInBash
+# conf/application.yml ships auth.secret-key empty on purpose, so PD would
+# refuse every authenticated REST request. Supply a test-only secret; it must
+# match the value the PD test suites send.
+export
SPRING_APPLICATION_JSON='{"auth":{"secret-key":"pd-ci-test-secret-not-for-production"}}'
Review Comment:
Fixed in `10f590a02`. The export is gone; the secret and the launch now sit
inside a subshell:
```bash
(
export SPRING_APPLICATION_JSON='{"auth":{"secret-key":"..."}}'
. bin/start-hugegraph-pd.sh
)
```
So `install-hstore.sh` sourcing this script and then `start-store.sh` in the
same shell no longer leaves PD's ports and raft properties set for Store's
Spring context. The comment above it now records why the scoping matters, so it
does not get flattened back into an export later.
##
hugegraph-server/hugegraph-dist/src/assembly/travis/test-pd-shipped-config.sh:
##
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Every PD configuration that ships in the archive or the jar must carry the
+# same REST hardening: no wildcard actuator exposure (that path is anonymous),
+# an auth.secret-key that is present and empty, and no copy of the secret that
+# earlier revisions published. A fix applied to one variant and not the others
+# is what this catches.
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../../.." && pwd)"
+PUBLISHED_SECRET='FXQXbJtbCLxODc6tGci732pkH1cyf8Qg'
+FAIL=0
+
+check() {
+local file="$1" rel="${1#"${ROOT}/"}" before="$FAIL"
+[[ -f "$file" ]] || { echo " FAIL ${rel}: missing"; FAIL=1; return; }
+
+# The actuator exposure specifically: a config that grows an unrelated
+# include: above this block must not satisfy the check by accident.
+local exposure
+exposure=$(awk '/^[[:space:]]*exposure:/ {found = 1; next}
+found && /^[[:space:]]*include:/
{sub(/^[[:space:]]*include:[[:space:]]*/, ""); print; exit}' "$file")
+if [[ "$exposure" == *'*'* ]]; then
+echo " FAIL ${rel}: actuator exposure is a wildcard (${exposure})";
FAIL=1
+fi
+if ! grep -qE '^[[:space:]]*secret-key:[[:space:]]*$' "$file"; then
+echo " FAIL ${rel}: auth.secret-key must be present and empty"; FAIL=1
+fi
+if grep -q "${PUBLISHED_SECRET}" "$file"; then
+echo " FAIL ${rel}: contains the published secret"; FAIL=1
+fi
+# Only when nothing above raised FAIL, or the file contradicts its own
report
+if [[ "$FAIL" == "$before" ]]; then
+echo " ok ${rel}"
+fi
+}
+
+echo "PD shipped configuration hardening"
+for f in
"${ROOT}"/hugegraph-pd/hg-pd-dist/src/assembly/static/conf/application.yml* \
Review Comment:
Fixed in `e420f9ab2`.
`hugegraph-cluster-test/hugegraph-clustertest-dist/src/assembly/static/conf/pd-application.yml.template`
now carries the same allowlist and empty-secret contract as the other shipped
configs, and `test-pd-shipped-config.sh` covers it, so the script's claim to
check every shipped PD configuration is now true rather than aspirational.
##
hugegraph-pd/README.md:
##
@@ -280,6 +290,30 @@ docker/docker-compose-3pd-3store-3server.yml
- Ensure low latency (<5ms) between PD nodes for Raft consensus
- Open required ports: `8620` (REST), `8686` (gRPC), `8610` (Raft)
+### Security
+
+- Keep all three ports on a trusted network. The REST API on `8620` includes
+ management endpoints that mutate the cluster (peer changes, store removal,
+ data movement), and the gRPC and Raft ports carry no authentication.
+- REST requests need HTTP Basic auth: one of the internal service names
+ (`hg`, `store`, `hubble`, `vermeer`) with the `auth.secret-key` value as
+ the password. Health probes (`/v1/health`, `/actuator/**`,
+ `/v1/prom/targets/*`) stay unauthenticated.
+- `auth.secret-key` has no shipped default,
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3952113182
##
docker/docker-compose-hstore.yml:
##
@@ -117,7 +120,7 @@ services:
- "${HUBBLE_PUBLISH_HOST:-127.0.0.1}:8088:8088"
volumes:
- hubble-data:/hubble/data
- -
./conf/hubble/hstore.properties:/hubble/conf/hugegraph-hubble.properties:ro
+ -
./conf/hubble/hstore.local.properties:/hubble/conf/hugegraph-hubble.properties:ro
Review Comment:
Fixed in `25bcb539b`. Both Hubble mounts, here and in
`docker-compose-3pd-3store-3server.yml`, use the long syntax with
`create_host_path: false`, so Compose refuses to start instead of inventing an
empty directory at the path. The comment records that the file comes from
`set-hubble-pd-password.sh` and is gitignored. `test-compose.sh` covers the
missing-file case.
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -39,7 +39,33 @@ log() {
echo "[wait-storage] $1"
}
-PD_AUTH_ARGS="-u ${PD_AUTH_USER:-store}:${PD_AUTH_PASSWORD:-admin}"
+# PD REST credential. PD checks the password against its auth.secret-key and
+# ships no default, so this has to be provided by the deployment.
+# The value is deliberately kept out of the inner script's source text and out
+# of curl's argv: the inner shell reads it from the environment and hands it to
+# curl on stdin as a config file.
+PD_AUTH_USER="${PD_AUTH_USER:-store}"
+PD_AUTH_PASSWORD="${PD_AUTH_PASSWORD:-}"
+if [ -z "${PD_AUTH_PASSWORD}" ]; then
+ log "WARN: PD_AUTH_PASSWORD is empty; PD will answer 401 unless it runs
without auth"
Review Comment:
Fixed in `63a54e972`. The warning moved into the branch that actually polls
PD, so the standalone RocksDB topology no longer logs a PD credential warning
two lines before saying it is skipping the storage wait.
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -114,12 +150,21 @@ if env | grep '^hugegraph\.' > /dev/null; then
}
until PD_REST=\$(check_any_pd_stores); do
+if [ \$? -eq 2 ]; then exit 2; fi
Review Comment:
Fixed in `63a54e972`. The status is captured as the opening statement and
the branch reads the copy:
```bash
rc=$?
if [ "$rc" -eq 2 ]; then exit 2; fi
```
with a comment saying it has to stay first, since anything inserted in front
would overwrite `$?` and turn the 401 abort back into a 300 second retry.
`test-wait-storage.sh` still passes, including the 401-aborts-without-retry
case.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3947215076
##
hugegraph-pd/hg-pd-dist/docker/docker-entrypoint.sh:
##
@@ -51,14 +72,22 @@ require_env "HG_PD_GRPC_HOST"
require_env "HG_PD_RAFT_ADDRESS"
require_env "HG_PD_RAFT_PEERS_LIST"
require_env "HG_PD_INITIAL_STORE_LIST"
+# The REST API refuses every authenticated request without this, and the image
+# ships no default because a published secret is not a secret.
+require_env "HG_PD_AUTH_SECRET_KEY"
: "${HG_PD_GRPC_PORT:=8686}"
: "${HG_PD_REST_PORT:=8620}"
: "${HG_PD_DATA_PATH:=/hugegraph-pd/pd_data}"
: "${HG_PD_INITIAL_STORE_COUNT:=1}"
+# Secret for REST Basic authentication (auth.secret-key). Required above and
+# never logged.
+AUTH_JSON="\"auth\": { \"secret-key\": \"$(json_escape
"${HG_PD_AUTH_SECRET_KEY}")\" },"
Review Comment:
⚠️ Putting the secret in `SPRING_APPLICATION_JSON` makes it recoverable from
`/actuator/env` whenever that endpoint is exposed, because Spring Boot's env
sanitizer keys off the property *name*.
`hg-pd-service/pom.xml:92` pins Spring Boot 2.5.14, whose default
`Sanitizer` key list is `password`, `secret`, `key`, `token`,
`.*credentials.*`, `vcap_services`, `sun.java.command`, each compiled as
`.*$` case-insensitively. `auth.secret-key` matches (`...key$`) and is
redacted, but the `systemEnvironment` entry `SPRING_APPLICATION_JSON` matches
none of them and is returned verbatim - secret included. The image's own
`conf/application.yml` now narrows the exposure, so the shipped path is fine;
an operator who bind-mounts a pre-1.8 `conf/application.yml` (the case
`hugegraph-pd/README.md` explicitly anticipates) gets `include: "*"` back and
hands out the secret anonymously on the port this PR is hardening.
Requested change: emit the exposure allowlist in the same JSON document, so
it outranks any mounted config file and the image is safe regardless of what is
mounted:
```bash
MANAGEMENT_JSON="\"management\": { \"endpoints\": { \"web\": { \"exposure\":
{ \"include\": \"health,metrics,prometheus\" } } } },"
```
and add it next to `${AUTH_JSON}` in the heredoc.
##
hugegraph-pd/README.md:
##
@@ -280,6 +290,30 @@ docker/docker-compose-3pd-3store-3server.yml
- Ensure low latency (<5ms) between PD nodes for Raft consensus
- Open required ports: `8620` (REST), `8686` (gRPC), `8610` (Raft)
+### Security
+
+- Keep all three ports on a trusted network. The REST API on `8620` includes
+ management endpoints that mutate the cluster (peer changes, store removal,
+ data movement), and the gRPC and Raft ports carry no authentication.
+- REST requests need HTTP Basic auth: one of the internal service names
+ (`hg`, `store`, `hubble`, `vermeer`) with the `auth.secret-key` value as
+ the password. Health probes (`/v1/health`, `/actuator/**`,
+ `/v1/prom/targets/*`) stay unauthenticated.
+- `auth.secret-key` has no shipped default, because a secret in the source
+ tree is published to everyone. Generate one per deployment (`openssl rand
+ -hex 24`) and set it in the config file, or through
+ `HG_PD_AUTH_SECRET_KEY`, which the Docker image requires. Give every REST
+ client the same value: the Server's `bin/wait-storage.sh` reads
+ `PD_AUTH_PASSWORD` (and `PD_AUTH_USER`, default `store`), and Hubble reads
+ `operations.pd.password`. A client left on a stale secret gets 401, and
+ `wait-storage.sh` aborts the Server's startup on the first one rather than
+ waiting out `WAIT_STORAGE_TIMEOUT_S`.
+- An existing `conf/application.yml` carried over from an earlier release has
Review Comment:
⚠️ This upgrade bullet covers `auth.secret-key` but not the actuator
allowlist, which leaves the upgraded deployment with exactly the anonymous
surface this PR identifies as the real boundary.
A `conf/application.yml` carried over from an earlier release does not only
lack the `auth` block - it also still has
`management.endpoints.web.exposure.include: "*"`. `AuthenticationConfigurer`
and `docs/configuration.md` both state (correctly) that the interceptor is
never attached to actuator's handler mapping, so the allowlist is the only
thing bounding what is reachable without a credential on 8620. Following this
bullet as written produces a PD that authenticates `/v1/**` while
`/actuator/env`, `/actuator/configprops` and `/actuator/beans` stay open.
Requested change: name the second setting in this bullet too, e.g. "Add
`auth.secret-key` **and** replace `management.endpoints.web.exposure.include:
"*"` with `health,metrics,prometheus` before upgrading."
##
docker/docker-compose-hstore.yml:
##
@@ -117,7 +120,7 @@ services:
- "${HUBBLE_PUBLISH_HOST:-127.0.0.1}:8088:8088"
volumes:
- hubble-data:/hubble/data
- -
./conf/hubble/hstore.properties:/hubble/conf/hugegraph-hubble.properties:ro
+ -
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3945718233
##
hugegraph-server/hugegraph-dist/src/assembly/travis/start-pd.sh:
##
@@ -31,6 +31,11 @@ fi
PD_DIR=$HOME_DIR/hugegraph-pd/apache-hugegraph-pd-$VersionInBash
+# conf/application.yml ships auth.secret-key empty on purpose, so PD would
+# refuse every authenticated REST request. Supply a test-only secret; it must
+# match the value the PD test suites send.
+export
SPRING_APPLICATION_JSON='{"auth":{"secret-key":"pd-ci-test-secret-not-for-production"}}'
Review Comment:
⚠️ This export leaks into the next service when the existing HStore
installer sources both startup scripts. `install-hstore.sh:22-23` runs `.
start-pd.sh` and then `. start-store.sh` in the same shell, so this exported
`SPRING_APPLICATION_JSON` remains set for Store. It contains PD's
`grpc.port=8686`, `server.port=8620`, and PD raft/data properties, while Store
expects `grpc.port=8500` and `server.port=8520` in
`hugegraph-store/hg-store-node/src/main/resources/application.yml`; Spring Boot
consumes `SPRING_APPLICATION_JSON` for both apps. Please scope this JSON to the
PD process or unset/restore it before `start-pd.sh` returns.
##
hugegraph-server/hugegraph-dist/src/assembly/travis/test-pd-shipped-config.sh:
##
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Every PD configuration that ships in the archive or the jar must carry the
+# same REST hardening: no wildcard actuator exposure (that path is anonymous),
+# an auth.secret-key that is present and empty, and no copy of the secret that
+# earlier revisions published. A fix applied to one variant and not the others
+# is what this catches.
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../../.." && pwd)"
+PUBLISHED_SECRET='FXQXbJtbCLxODc6tGci732pkH1cyf8Qg'
+FAIL=0
+
+check() {
+local file="$1" rel="${1#"${ROOT}/"}" before="$FAIL"
+[[ -f "$file" ]] || { echo " FAIL ${rel}: missing"; FAIL=1; return; }
+
+# The actuator exposure specifically: a config that grows an unrelated
+# include: above this block must not satisfy the check by accident.
+local exposure
+exposure=$(awk '/^[[:space:]]*exposure:/ {found = 1; next}
+found && /^[[:space:]]*include:/
{sub(/^[[:space:]]*include:[[:space:]]*/, ""); print; exit}' "$file")
+if [[ "$exposure" == *'*'* ]]; then
+echo " FAIL ${rel}: actuator exposure is a wildcard (${exposure})";
FAIL=1
+fi
+if ! grep -qE '^[[:space:]]*secret-key:[[:space:]]*$' "$file"; then
+echo " FAIL ${rel}: auth.secret-key must be present and empty"; FAIL=1
+fi
+if grep -q "${PUBLISHED_SECRET}" "$file"; then
+echo " FAIL ${rel}: contains the published secret"; FAIL=1
+fi
+# Only when nothing above raised FAIL, or the file contradicts its own
report
+if [[ "$FAIL" == "$before" ]]; then
+echo " ok ${rel}"
+fi
+}
+
+echo "PD shipped configuration hardening"
+for f in
"${ROOT}"/hugegraph-pd/hg-pd-dist/src/assembly/static/conf/application.yml* \
Review Comment:
⚠️ This regression check does not cover the PD template used by the
cluster-test distribution.
`hugegraph-cluster-test/hugegraph-clustertest-dist/src/assembly/static/conf/pd-application.yml.template`
is copied to each PD node by `PDNodeWrapper`, but it still has
`management.endpoints.web.exposure.include: "*"` and no `auth.secret-key`. With
this PR's `PDConfig`, REST credentials fail closed while actuator endpoints
such as `/actuator/env` remain anonymously exposed. Please update that shipped
template to the same allowlist/empty secret contract and include it in this
check.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#issuecomment-5560593174
@imbajin Ready for a review pass when you have time, though please read the
second section first: I got something wrong in this PR and the last three
commits correct it.
**Correction, and the reason for `fdec006b1` and `ffd88d31c`.** This PR
moves the interceptor exclusion from `/actuator/*` to `/actuator/**`, and it
shipped an explanation saying the single star would have caused the auth
interceptor to refuse nested probe paths such as `/actuator/metrics/{name}`.
That explanation is wrong. The interceptor never runs on any actuator path,
with either pattern.
`RestAuthentication` is registered through
`WebMvcConfigurer.addInterceptors`, so it lands in the MVC
`InterceptorRegistry`. Actuator is served by `WebMvcEndpointHandlerMapping`,
and `AbstractHandlerMapping.detectMappedInterceptors` collects
`MappedInterceptor` **beans** only, via `beansOfTypeIncludingAncestors`. The
registry does build a `MappedInterceptor` here, since both include and exclude
patterns are supplied, but it is never published as a bean, so the actuator
mapping does not pick it up. `WebMvcConfigurationSupport.getInterceptors`
pushes the registry's interceptors onto the MVC handler mappings alone.
Checked empirically as well as by reading the sources at the versions
`hg-pd-service` resolves, Spring Boot 2.5.14 and spring-webmvc 5.3.20, on Jetty
to match PD. Four cases, with the interceptor logging every request it saw:
| exclusion | `/actuator/health` | `/actuator/metrics/jvm.memory.used` |
`/v1/foo` |
|---|---|---|---|
| `/actuator/*` | 200 | 200 | 401 |
| a pattern matching nothing | 200 | 200 | 401 |
| no registry interceptor at all | 200 | 200 | 200 |
| same interceptor as a `MappedInterceptor` bean on `/**` | 401 | 401 | 401 |
In the first two the interceptor logged only `/v1/foo`. The third is the
control showing the interceptor is what refuses `/v1/foo`. The fourth is the
positive control: published as a bean, the identical interceptor does reach
actuator paths. So bean detection is the mechanism, not the exclusion pattern.
What actually keeps those paths anonymous is that actuator has its own
handler mapping, and what bounds them is the exposure allowlist, which this PR
narrows from `include: "*"` to `health,metrics,prometheus` in every shipped
config. That is the real security improvement here, and it stands.
`testUnexposedActuatorEndpointIsClosed` is the assertion that guards it.
`/actuator/**` stays in the exclusion list: it states the intent correctly
for nested probe paths and costs nothing. `fdec006b1` and `ffd88d31c` correct
the explanation in `AuthenticationConfigurer`, `RestApiTest`,
`docs/configuration.md`, and the comment above
`management.endpoints.web.exposure.include` in `hg-pd-service/application.yml`,
`hg-pd-dist/conf/application.yml` and its `.template`. Comments and prose only,
no assertion or code path changed. The message on `a890122` still carries the
old wrong reasoning; I left it rather than rewrite public history.
**What else I checked on the branch.** PD booted from the shipped
`hg-pd-dist` config and probed without credentials: every authenticated `/v1`
path answers 401 with the constant body `{"status":-1,"error":"Unauthorized"}`
and a `WWW-Authenticate: Basic realm="hugegraph-pd"` challenge. `/v1/health`
and `/v1/prom/targets/*` stay anonymous by design.
On the previously published placeholder secret PD exits 1 as intended. With
no `auth` block at all PD starts, logs the error once, keeps raft and gRPC
serving, and fails closed on REST. The live secret appears nowhere in `pd.log`,
`logs/` or `pd_data/`, and the refusal log is debug level with method, URI and
reason only. `test-pd-shipped-config.sh` passes against the edited configs.
One wording note on the credential path: `Authentication.authenticate` wraps
everything in a `RuntimeException`, so callers see `BadCredentialsException` or
`AccessDeniedException` as the cause, which is why `RestAuthentication` unwraps
with `e.getCause() != null ? e.getCause() : e`.
**Merge-order conflict with #3185, worth deciding before either lands.**
Both PRs rewrite the same line, `AuthenticationConfigurer.addInterceptors`.
This one makes it `excludePathPatterns("/actuator/**", "/v1/health",
"/v1/prom/targets/*")`. #3185 makes it `excludePathPatterns("/actuator/*",
"/v1/health", "/v1/ready", "/v1/prom/targets/*")`. Whichever lands second
conflicts, and the two changes disagree about two independent things at once.
The correct union is:
```java
excludePathPatterns("/actuator/**", "/v1/health", "/v1/ready",
"/v1/prom/targets/*")
```
Dropping `/v1/ready` puts that endpoint back behind authentication and
defeats #3185. `/v1/ready` is the half that actually matters, since it is on
the MVC
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3943249865
##
docker/README.md:
##
@@ -60,12 +66,59 @@ behind an HTTPS reverse proxy and trusted network controls.
first authenticated startup. Changing `.env` does not rotate an existing
administrator password; use the HugeGraph user API for credential changes.
-For the verification commands below, set the password in your current shell:
+For the verification commands below, load `.env` into your current shell and
+set the password:
```bash
+set -a; . ./.env; set +a
ADMIN_PASSWORD='the-same-password-used-in-.env'
```
+Compose reads `.env` on its own; the line above is so that the `curl` command
and
+the Hubble helper on this page can use `${HG_PD_AUTH_SECRET_KEY}` too.
+
+The PD REST API (port 8620, HStore topologies only) has its own credential:
+requests other than health probes need HTTP Basic auth with an internal
+service name (for example `hg`) and the PD secret as the password. PD ships
+no default secret, so `HG_PD_AUTH_SECRET_KEY` is required and the HStore
+Compose files refuse to start without it. The `.env` command above generates
+one. To list registered stores:
+
+```bash
+curl -u "hg:${HG_PD_AUTH_SECRET_KEY}" http://localhost:8620/v1/stores
+```
+
+Three consumers read this credential, and all three have to agree or startup
+fails:
+
+- PD itself, through `HG_PD_AUTH_SECRET_KEY`.
+- The Server, whose `bin/wait-storage.sh` polls `/v1/stores` before the
+ Server starts. Both Compose files pass `PD_AUTH_PASSWORD` to it from the
+ same variable, so setting `HG_PD_AUTH_SECRET_KEY` in `.env` covers it. If
+ the Server sends the wrong secret it retries until
+ `WAIT_STORAGE_TIMEOUT_S` (300s) expires and the container exits with
+ `ERROR: Timeout waiting for storage backend`.
Review Comment:
Fixed in 94a4a0f, taking the suggestion. The bullet now describes the abort
and names both strings the script actually prints, `ERROR: PD at refused
the credential (401)` and `ERROR: storage wait aborted, see the message above`;
I grepped the script for each to be sure the docs do not promise a string that
cannot appear again.
##
hugegraph-pd/README.md:
##
@@ -280,6 +290,30 @@ docker/docker-compose-3pd-3store-3server.yml
- Ensure low latency (<5ms) between PD nodes for Raft consensus
- Open required ports: `8620` (REST), `8686` (gRPC), `8610` (Raft)
+### Security
+
+- Keep all three ports on a trusted network. The REST API on `8620` includes
+ management endpoints that mutate the cluster (peer changes, store removal,
+ data movement), and the gRPC and Raft ports carry no authentication.
+- REST requests need HTTP Basic auth: one of the internal service names
+ (`hg`, `store`, `hubble`, `vermeer`) with the `auth.secret-key` value as
+ the password. Health probes (`/v1/health`, `/actuator/*`,
+ `/v1/prom/targets/*`) stay unauthenticated.
+- `auth.secret-key` has no shipped default, because a secret in the source
+ tree is published to everyone. Generate one per deployment (`openssl rand
+ -hex 24`) and set it in the config file, or through
+ `HG_PD_AUTH_SECRET_KEY`, which the Docker image requires. Give every REST
+ client the same value: the Server's `bin/wait-storage.sh` reads
+ `PD_AUTH_PASSWORD` (and `PD_AUTH_USER`, default `store`), and Hubble reads
+ `operations.pd.password`. A client left on a stale secret gets 401, and for
+ `wait-storage.sh` that means Server startup aborts after
+ `WAIT_STORAGE_TIMEOUT_S`.
Review Comment:
Fixed in 94a4a0f, taking the suggestion. Same correction as
`docker/README.md`: startup aborts on the first 401 rather than waiting out
`WAIT_STORAGE_TIMEOUT_S`.
##
.gitignore:
##
@@ -44,6 +44,8 @@ build/
.env.test.local
.env.production.local
docker/.env
+# generated by docker/set-hubble-pd-password.sh, carries the PD REST secret
+docker/conf/hubble/*.local.properties
Review Comment:
Fixed in 94a4a0f, taking `docker/conf/hubble/*.local.properties*`. Confirmed
your reproduction first (the base name ignored,
`hstore.local.properties.aB3xY9` not), and after the change both forms are
ignored while `hstore.properties.example`, `hstore-ha.properties.example` and
`standalone.properties` stay tracked. Good catch on the crash window; the trap
only covers a clean exit.
##
hugegraph-server/hugegraph-dist/src/assembly/travis/test-pd-shipped-config.sh:
##
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3940228462
##
docker/README.md:
##
@@ -60,12 +66,59 @@ behind an HTTPS reverse proxy and trusted network controls.
first authenticated startup. Changing `.env` does not rotate an existing
administrator password; use the HugeGraph user API for credential changes.
-For the verification commands below, set the password in your current shell:
+For the verification commands below, load `.env` into your current shell and
+set the password:
```bash
+set -a; . ./.env; set +a
ADMIN_PASSWORD='the-same-password-used-in-.env'
```
+Compose reads `.env` on its own; the line above is so that the `curl` command
and
+the Hubble helper on this page can use `${HG_PD_AUTH_SECRET_KEY}` too.
+
+The PD REST API (port 8620, HStore topologies only) has its own credential:
+requests other than health probes need HTTP Basic auth with an internal
+service name (for example `hg`) and the PD secret as the password. PD ships
+no default secret, so `HG_PD_AUTH_SECRET_KEY` is required and the HStore
+Compose files refuse to start without it. The `.env` command above generates
+one. To list registered stores:
+
+```bash
+curl -u "hg:${HG_PD_AUTH_SECRET_KEY}" http://localhost:8620/v1/stores
+```
+
+Three consumers read this credential, and all three have to agree or startup
+fails:
+
+- PD itself, through `HG_PD_AUTH_SECRET_KEY`.
+- The Server, whose `bin/wait-storage.sh` polls `/v1/stores` before the
+ Server starts. Both Compose files pass `PD_AUTH_PASSWORD` to it from the
+ same variable, so setting `HG_PD_AUTH_SECRET_KEY` in `.env` covers it. If
+ the Server sends the wrong secret it retries until
+ `WAIT_STORAGE_TIMEOUT_S` (300s) expires and the container exits with
+ `ERROR: Timeout waiting for storage backend`.
Review Comment:
🧹 This bullet documents the failure mode this same head replaced. A wrong
secret no longer waits out `WAIT_STORAGE_TIMEOUT_S`.
`wait-storage.sh:140-142` returns 2 on a 401 and `:152-153` turns that into
`exit 2`, which is not 124, so the outer handler prints `ERROR: storage wait
aborted, see the message above` (`:164`) rather than the timeout message
(`:162`). `travis/test-wait-storage.sh:255` asserts exactly that: `[[
"${CASE_OUTPUT}" != *"Timeout waiting"* ]] || fail "401 was reported as a
timeout"`.
An operator on a stale secret is told to wait 300s and to look for a string
that cannot appear.
```suggestion
the Server sends the wrong secret `wait-storage.sh` aborts on the first
401 rather than waiting out `WAIT_STORAGE_TIMEOUT_S`, and the container
exits with `ERROR: storage wait aborted, see the message above` after
logging `ERROR: PD at refused the credential (401)`.
```
##
hugegraph-pd/README.md:
##
@@ -280,6 +290,30 @@ docker/docker-compose-3pd-3store-3server.yml
- Ensure low latency (<5ms) between PD nodes for Raft consensus
- Open required ports: `8620` (REST), `8686` (gRPC), `8610` (Raft)
+### Security
+
+- Keep all three ports on a trusted network. The REST API on `8620` includes
+ management endpoints that mutate the cluster (peer changes, store removal,
+ data movement), and the gRPC and Raft ports carry no authentication.
+- REST requests need HTTP Basic auth: one of the internal service names
+ (`hg`, `store`, `hubble`, `vermeer`) with the `auth.secret-key` value as
+ the password. Health probes (`/v1/health`, `/actuator/*`,
+ `/v1/prom/targets/*`) stay unauthenticated.
+- `auth.secret-key` has no shipped default, because a secret in the source
+ tree is published to everyone. Generate one per deployment (`openssl rand
+ -hex 24`) and set it in the config file, or through
+ `HG_PD_AUTH_SECRET_KEY`, which the Docker image requires. Give every REST
+ client the same value: the Server's `bin/wait-storage.sh` reads
+ `PD_AUTH_PASSWORD` (and `PD_AUTH_USER`, default `store`), and Hubble reads
+ `operations.pd.password`. A client left on a stale secret gets 401, and for
+ `wait-storage.sh` that means Server startup aborts after
+ `WAIT_STORAGE_TIMEOUT_S`.
Review Comment:
🧹 The same stale claim as `docker/README.md:98-100`: a 401 no longer costs
`WAIT_STORAGE_TIMEOUT_S`.
`wait-storage.sh:140-142` returns 2 on the first 401 and `:152-153` exits
immediately, so startup aborts on the first attempt, not after the timeout.
```suggestion
`operations.pd.password`. A client left on a stale secret gets 401, and
`wait-storage.sh` aborts the Server's startup on the first one rather than
waiting out `WAIT_STORAGE_TIMEOUT_S`.
```
##
.gitignore:
##
@@ -44,6 +44,8 @@ build/
.env.test.local
.env.production.local
docker/.env
+# generated by docker/set-hubble-pd-password.sh, carries the PD REST secret
+docker/conf/hubble/*.local.properties
Review Comment:
🧹 This pattern, which I asked for on the `hstore.properties.example`
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#issuecomment-5550447338
Tested end to end on Kubernetes through the Helm chart on 2026-09-05.
**Build under test.** Tag
[`helm-dev-20260905`](https://github.com/hugegraph/hugegraph/releases/tag/helm-dev-20260905),
commit `6ec19838`: apache master `36811483` plus this PR at `e964b680`, #3185
and #3187. PD, Store and Server images built from that tree with `docker buildx
bake -f docker/bake.hcl pd store server-hstore` (linux/amd64),
`org.opencontainers.image.revision=6ec1983889f58a52995b27a4e1ea89bd00932396`
read back from every pod. kind, Kubernetes 1.37.0, 3 PD + 3 Store + 3 Server +
Hubble, auth on. The chart side is apache/hugegraph#3132 at `0a50f6fe`: a kept
release Secret holding `auth.secret-key`, handed to PD as
`HG_PD_AUTH_SECRET_KEY`, to the Server storage wait as `PD_AUTH_PASSWORD`, and
written into Hubble's properties as `operations.pd.password`.
- Rollout: a running cluster on images from the same tree minus this PR was
upgraded to these images in 175 s. All three PDs started with the secret; every
Server's `wait-storage.sh` logged `Store registration check PASSED` and
`Storage backend is VIABLE` with no 401; 0 `Blocked connection` and 0 `Could
not resolve allowlist entry` lines; data written before the roll readable after
it; `helm test` passed.
- Credential matrix, 57 requests against `/v1/members`, `/v1/stores` and
`/v1/allInfo` through the PD client Service: no header, empty password, wrong
password, and `admin` or `nobody` with any password all answered `401
{"status":-1,"error":"Unauthorized"}` with `WWW-Authenticate: Basic
realm="hugegraph-pd"`; `hg`, `store`, `hubble` and `vermeer` with the release
secret answered 200 with the real payload. `/v1/health`, `/v1/ready`,
`/actuator/health` and `/actuator/prometheus` stayed open without a credential.
- Control: the same 57 requests against the pre-#3189 images reproduced the
old behaviour, 200 for every outcome and any password accepted for the four
names.
- Hubble, not restarted across the roll, listed 3 PD, 3 STORE and 3 SERVER,
all UP, with the `operations.pd.password` it had from install, so its PD calls
carry the credential on this image.
Merge notes for whoever lands the second of #3185 and this PR:
`AuthenticationConfigurer` needs both changes in one exclusion list,
`"/actuator/**", "/v1/health", "/v1/ready", "/v1/prom/targets/*"`; and
`docker/test-compose.sh` keeps #3187's timeout asserts followed by
`hubble_password_helper_check`, with `HG_PD_AUTH_SECRET_KEY="${PD_SECRET}"`
added to `render_with_timeout`. That is how the tag resolves them.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3939639187
##
docker/conf/hubble/hstore.properties.example:
##
@@ -20,6 +20,11 @@ pd.enabled=true
server.direct_url=http://server:8080
pd.peers=pd:8686
pd.server=pd:8620
+# PD REST credential. The password must equal PD's auth.secret-key, which has
+# no default: set it to the same value as HG_PD_AUTH_SECRET_KEY in .env. While
+# it is empty, Hubble's PD-backed views get HTTP 401 from PD.
+operations.pd.username=hubble
+operations.pd.password=
Review Comment:
Fixed in e964b68, following your layout. The tracked files are now
`conf/hubble/hstore.properties.example` and `hstore-ha.properties.example`;
both Compose files mount `.local.properties`;
`docker/conf/hubble/*.local.properties` is in `.gitignore` next to
`docker/.env`. `set-hubble-pd-password.sh [secret]` generates the local
file from the example (no sed, backslashes doubled, mode 644 for the read-only
mount, refuses empty or line-break secrets). The `.env` recipe and the
deployment guide run it before `up`, and `test-compose.sh` generates both
before every render and smoke, then restores a developer's own local files.
Render passes with the CI secret and with `a&b#c\d`.
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -101,10 +119,12 @@ if env | grep '^hugegraph\.' > /dev/null; then
check_any_pd_stores() {
for peer in \$(echo \"\$PD_REST_LIST\" | tr ',' ' '); do
- if curl ${PD_AUTH_ARGS} -f -s \
+ if printf 'user = \"%s:%s\"\n' \
+ \"\$PD_AUTH_CURL_USER\" \"\$PD_AUTH_CURL_PASSWORD\" | \
+ curl -K - -f -s \
Review Comment:
Fixed in e964b68, taking the shape you sketched. curl now runs alone with
`-w '\n%{http_code}'`, the code is split off the body, and a 401 logs `PD at
refused the credential (401): PD_AUTH_PASSWORD must match PD's
auth.secret-key` and aborts via a distinct return code, so the `until` loop
exits instead of retrying; the outer handler now separates a real timeout (124)
from an abort. The mock curl honours `-w`, and a new `auth-401` case asserts
non-zero exit, the message, exactly one call, and no timeout wording; 7/7 pass.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/config/PDConfig.java:
##
@@ -85,6 +98,17 @@ public class PDConfig {
private ConfigService configService;
private IdService idService;
+@Override
+public void afterPropertiesSet() {
+if (PUBLISHED_SECRET_KEY.equals(this.secretKey)) {
Review Comment:
Fixed in e964b68, taking the log option rather than the hard gate.
`PDConfig.afterPropertiesSet` now emits the same "auth.secret-key is not
configured" ERROR when the key is empty, so it is in the boot log before any
request. Verified on the packaged dist with the shipped config: the line
appears at `[main]` during startup (it lands in `hugegraph-pd-stdout.log`,
where the boot phase logs before the file appender takes over). Kept it a log
rather than a throw so a tarball upgrade still starts for gRPC clients while
the operator adds the key.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/interceptor/RestAuthentication.java:
##
@@ -59,6 +59,10 @@ public boolean preHandle(HttpServletRequest request,
HttpServletResponse respons
authority = authority.replace("Basic ", "");
return authenticate(authority, token, tokenCall, DEFAULT_HANDLE);
} catch (Exception e) {
+response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+// RFC 7235 requires a challenge on a 401; without it clients that
+// authenticate reactively never retry with credentials
+response.setHeader("WWW-Authenticate", "Basic
realm=\"hugegraph-pd\"");
response.setContentType("application/json");
response.getWriter().println(new API().toJSON(e));
Review Comment:
Fixed in e964b68. The 401 body is now the constant
`{"status":-1,"error":"Unauthorized"}` for every refusal, and the reason
(missing header, unknown service name, wrong password) goes to `log.debug` with
the method and path. Verified on the dist: wrong password, unknown name and no
header all return the identical body with the challenge header. Debug rather
than warn since the path is reachable unauthenticated and I did not want a
log-flood lever; the one-shot boot and first-use ERRORs still cover the
misconfiguration case.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3939615797
##
hugegraph-pd/hg-pd-service/src/test/java/org/apache/hugegraph/pd/service/interceptor/AuthenticationTest.java:
##
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hugegraph.pd.service.interceptor;
+
+import java.lang.reflect.Field;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+
+import org.apache.hugegraph.pd.config.PDConfig;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * In-process cover for the REST credential check. The suites that exercise it
+ * over HTTP talk to a PD in another JVM, so nothing here is covered by them.
+ */
+public class AuthenticationTest {
+
+private static final String SECRET = "unit-test-secret";
+
+private static Authentication authWithSecret(String secret) throws
Exception {
Review Comment:
Fixed in 94b1566, and the cascade was mine. Your diagnosis is exactly right:
the repackage puts `hg-pd-service` classes under `BOOT-INF/classes`, so
`hg-pd-test` can never compile against it in an `install` build, which is why
no existing test there imports service classes. `AuthenticationTest` now lives
in `hg-pd-service/src/test/java` with junit at test scope, and
`PDCoreSuiteTest` no longer references it. Verified with the same `mvn install
-Dmaven.test.skip=true` path the commons job runs (clean) and `mvn test -pl
hugegraph-pd/hg-pd-service -am` (8/8).
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -39,7 +39,25 @@ log() {
echo "[wait-storage] $1"
}
-PD_AUTH_ARGS="-u ${PD_AUTH_USER:-store}:${PD_AUTH_PASSWORD:-admin}"
+# PD REST credential. PD checks the password against its auth.secret-key and
+# ships no default, so this has to be provided by the deployment.
+# The value is deliberately kept out of the inner script's source text and out
+# of curl's argv: the inner shell reads it from the environment and hands it to
+# curl on stdin as a config file.
+PD_AUTH_USER="${PD_AUTH_USER:-store}"
+PD_AUTH_PASSWORD="${PD_AUTH_PASSWORD:-}"
+if [ -z "${PD_AUTH_PASSWORD}" ]; then
+ log "WARN: PD_AUTH_PASSWORD is empty; PD will answer 401 unless it runs
without auth"
+fi
+# curl -K takes a quoted string, so escape backslash first and then quote
Review Comment:
Fixed in 94b1566. `escape_curlrc` now maps LF, CR, TAB and VT to the `\n \r
\t \v` escapes curl's quoted config strings accept, after backslash and quote.
`test-wait-storage.sh` gained a case whose secret contains CR, LF, a backslash
and a quote, asserting every config line the mock reads is the single escaped
`user = "..."` form; 6/6 pass.
##
hugegraph-pd/hg-pd-dist/src/assembly/static/conf/application.yml:
##
@@ -27,7 +27,9 @@ management:
endpoints:
web:
exposure:
-include: "*"
+# Allowlist, not "*": /actuator/* is excluded from the REST auth
+# interceptor, so anything exposed here is anonymous on this port.
+include: "health,metrics,prometheus"
Review Comment:
Fixed in 94b1566. `application.yml.template` now carries the same allowlist
and an empty `auth.secret-key` block. The regression check you asked for is
`travis/test-pd-shipped-config.sh`, wired into the `pd` job: for every
`hg-pd-dist/.../conf/application.yml*` and the `hg-pd-service` resources config
it fails on a wildcard exposure, a missing or non-empty `secret-key`, or the
published secret string.
##
docker/docker-compose-3pd-3store-3server.yml:
##
@@ -107,6 +109,7 @@ services:
HG_PD_INITIAL_STORE_LIST: store0:8500,store1:8500,store2:8500
Review Comment:
Fixed in 94b1566. `hugegraph-pd/README.md` lists `HG_PD_AUTH_SECRET_KEY` on
each of the three PD container blocks with a line saying it must be the same
value everywhere, and `hugegraph-store/docs/deployment-guide.md` generates and
exports it before the `docker compose up` line and adds it to the per-node PD
environment table. Both point at the `.env` recipe in `docker/README.md` for
the persistent form.
##
docker/README.md:
##
@@ -60,12 +61,56 @@
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3934249764
##
docker/conf/hubble/hstore.properties:
##
@@ -20,6 +20,11 @@ pd.enabled=true
server.direct_url=http://server:8080
pd.peers=pd:8686
pd.server=pd:8620
+# PD REST credential. The password must equal PD's auth.secret-key, which has
+# no default: set it to the same value as HG_PD_AUTH_SECRET_KEY in .env. While
+# it is empty, Hubble's PD-backed views get HTTP 401 from PD.
+operations.pd.username=hubble
+operations.pd.password=
Review Comment:
⚠️ Hubble has no path from `.env` to this value, so its PD-backed views
answer 401 in both shipped HStore stacks. The fix spans `docker/README.md`, the
two compose files and `.gitignore`, not just this line.
`docker-compose-hstore.yml:120` mounts this file verbatim
(`./conf/hubble/hstore.properties:/hubble/conf/hugegraph-hubble.properties:ro`),
and `docker-compose-3pd-3store-3server.yml:239` does the same for
`hstore-ha.properties`. Compose does not interpolate properties files, and the
`hugegraph/hubble` image has no entrypoint that rewrites config from the
environment: hugegraph-toolchain ships only `hugegraph-hubble/Dockerfile`,
whose `ENTRYPOINT` is `./bin/start-hubble.sh -f`, and `operations.pd.password`
is read through `HubbleOptions` into a `HugeConfig` from the file, not through
Spring relaxed binding. The Server gets the secret via `PD_AUTH_PASSWORD:
${HG_PD_AUTH_SECRET_KEY:?...}`; Hubble gets nothing.
The remedy `docker/README.md` documents is `sed -i.bak` over this file,
which is tracked in git. That has an operator write a production secret into a
tracked file in their clone, one `git add -A` away from being committed.
`hstore-ha.properties:27` is identical.
Requested change: imbajin already asked for a safe config-generation path on
`docker/README.md:107`. When you build it, have it generate an untracked file
rather than edit this one in place: ship
`conf/hubble/hstore.properties.example`, generate
`conf/hubble/hstore.local.properties` from it in the same step that writes
`.env`, point the compose mount there, and add
`docker/conf/hubble/*.local.properties` to `.gitignore` next to the existing
`docker/.env` entry. The generation step has to run before `docker compose up`,
otherwise Docker creates an empty directory at the bind path and Hubble starts
with no config at all.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/config/PDConfig.java:
##
@@ -85,6 +98,17 @@ public class PDConfig {
private ConfigService configService;
private IdService idService;
+@Override
+public void afterPropertiesSet() {
+if (PUBLISHED_SECRET_KEY.equals(this.secretKey)) {
Review Comment:
🧹 Follow-on to the resolved `Authentication.java:112` thread, not a
reopening of it: the one-shot ERROR you added in `verifySecret` fires on the
first authenticated request, so it can arrive long after the misconfiguration,
or never.
This check rejects only `PUBLISHED_SECRET_KEY`. The empty case is the one
both shipped `application.yml` files now produce, and it starts silently.
Meanwhile the shipped PD healthchecks are `curl -fsS
http://localhost:8620/v1/health`, which `AuthenticationConfigurer` excludes, so
a PD with no secret reports healthy while refusing every real REST call. An
operator sees it only as a client-side 401 or as the 300s `wait-storage.sh`
timeout.
Requested change: log it here too. `afterPropertiesSet` is already the
startup hook, so adding `@Slf4j` to `PDConfig` and an `else if
(StringUtils.isEmpty(this.secretKey))` branch that emits the same
"auth.secret-key is not configured" message puts the condition in the boot log
rather than only on first use. Throwing instead, for symmetry with the
entrypoint's `require_env "HG_PD_AUTH_SECRET_KEY"`, would also work if you are
willing to make it a hard upgrade gate.
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -101,10 +119,12 @@ if env | grep '^hugegraph\.' > /dev/null; then
check_any_pd_stores() {
for peer in \$(echo \"\$PD_REST_LIST\" | tr ',' ' '); do
- if curl ${PD_AUTH_ARGS} -f -s \
+ if printf 'user = \"%s:%s\"\n' \
+ \"\$PD_AUTH_CURL_USER\" \"\$PD_AUTH_CURL_PASSWORD\" | \
+ curl -K - -f -s \
Review Comment:
⚠️ A 401 from PD is indistinguishable here from "PD unreachable" and from
"no store is Up", so a missing or stale secret surfaces as a storage-backend
failure.
curl's exit status never reaches the `if`: lines 122-128 are `printf ... |
curl ... | grep -qi '"state"...'`, and neither this script, `util.sh`, nor the
inner `bash -c` sets `pipefail`, so the `if` tests grep alone. On a 401 the
body is `{"status":-1,"error":"..."}`, grep finds no `"state": "Up"`, and the
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3933761830
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/service/interceptor/AuthenticationTest.java:
##
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hugegraph.pd.service.interceptor;
+
+import java.lang.reflect.Field;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+
+import org.apache.hugegraph.pd.config.PDConfig;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * In-process cover for the REST credential check. The suites that exercise it
+ * over HTTP talk to a PD in another JVM, so nothing here is covered by them.
+ */
+public class AuthenticationTest {
+
+private static final String SECRET = "unit-test-secret";
+
+private static Authentication authWithSecret(String secret) throws
Exception {
Review Comment:
‼️ The new `AuthenticationTest` cannot be compiled in `hg-pd-test`. On exact
head `ace8913a079810503810584cdc552bb710fe601a`, the `pd`, `hstore`, and
`store` jobs, `build-commons (11)`, the macOS jobs, and the Docker build matrix
fail in `maven-compiler-plugin` with `cannot find symbol: class Authentication`
at this file's lines 36 and 51. Although `hg-pd-test` declares `hg-pd-service`,
that module's Spring Boot repackage replaces the main artifact with a fat jar
whose classes are under `BOOT-INF/classes`, so javac cannot resolve this new
test under `hg-pd-test/src/main/java`; the checks fail before the
authentication tests execute. Please move the test into `hg-pd-service`'s test
source set or provide/use an un-repackaged service artifact, then rerun the
failed checks.
##
hugegraph-pd/hg-pd-service/src/main/resources/application.yml:
##
@@ -27,7 +27,9 @@ management:
endpoints:
web:
exposure:
-include: "*"
+# Allowlist, not "*": /actuator/* is excluded from the REST auth
+# interceptor, so anything exposed here is anonymous on this port.
+include: "health,metrics,prometheus"
Review Comment:
⚠️ The documented unauthenticated actuator allowlist does not cover nested
endpoint paths. `AuthenticationConfigurer` still excludes only `/actuator/*`;
Spring's path matcher does not match `/actuator/metrics/{name}` or
`/actuator/health/{group}`, so these exposed `metrics`/`health` sub-endpoints
are intercepted and return 401. Please change the exclusion to `/actuator/**`
if all exposed actuator paths are intended to remain probe-accessible, or
narrow both the allowlist and docs to exact root paths and add tests.
##
hugegraph-pd/hg-pd-dist/src/assembly/static/conf/application.yml:
##
@@ -27,7 +27,9 @@ management:
endpoints:
web:
exposure:
-include: "*"
+# Allowlist, not "*": /actuator/* is excluded from the REST auth
+# interceptor, so anything exposed here is anonymous on this port.
+include: "health,metrics,prometheus"
Review Comment:
⚠️ This allowlist is not applied to the other configuration shipped in the
same archive. `server-assembly.xml` copies `conf/*`, but
`application.yml.template` remains `management.endpoints.web.exposure.include:
"*"`. Since `AuthenticationConfigurer` excludes `/actuator/*`, an operator who
uses the packaged template can expose `/actuator/env` and `/actuator/beans`
without Basic auth even though this changed config claims to close that path.
Please update the template too and add a regression check for every shipped
config variant.
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -39,7 +39,25 @@ log() {
echo "[wait-storage] $1"
}
-PD_AUTH_ARGS="-u ${PD_AUTH_USER:-store}:${PD_AUTH_PASSWORD:-admin}"
+# PD REST credential. PD checks the password against its auth.secret-key and
+# ships no default, so this has to be provided by the deployment.
+# The value is deliberately kept out of the inner script's source text and out
+# of curl's argv: the inner shell reads it from the environment and hands it to
+# curl on stdin as a config file.
+PD_AUTH_USER="${PD_AUTH_USER:-store}"
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3930914959
##
docker/test-compose.sh:
##
@@ -21,6 +21,7 @@ set -Eeuo pipefail
DOCKER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PASSWORD="ci-compose-password"
SECRET="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+PD_SECRET="ci-compose-pd-secret"
Review Comment:
Fixed in 3b39132, and the break was mine: I required the variable in the
Compose files without giving it to every caller of `docker compose`.
`compose_active` now passes `HG_PD_AUTH_SECRET_KEY="${PD_SECRET}"` alongside
the other three, so the smoke path interpolates the same way render does. Kept
the two functions separate rather than routing smoke through `compose_auth`,
since `compose_active` carries the project and file selection that smoke needs.
##
hugegraph-pd/hg-pd-dist/docker/docker-entrypoint.sh:
##
@@ -57,8 +57,16 @@ require_env "HG_PD_INITIAL_STORE_LIST"
: "${HG_PD_DATA_PATH:=/hugegraph-pd/pd_data}"
: "${HG_PD_INITIAL_STORE_COUNT:=1}"
+# Optional secret for REST Basic authentication (auth.secret-key). When unset,
+# the value from conf/application.yml applies. Never logged.
+AUTH_JSON=""
+if [[ -n "${HG_PD_AUTH_SECRET_KEY:-}" ]]; then
+AUTH_JSON="\"auth\": { \"secret-key\": \"$(json_escape
"${HG_PD_AUTH_SECRET_KEY}")\" },"
Review Comment:
Fixed in 3b39132. `json_escape` now escapes every C0 control character as
`\u` rather than only backslash, quote and LF, so CR and TAB no longer
produce invalid JSON.
Added `travis/test-pd-docker-entrypoint.sh`, wired into the `pd` CI job, as
you asked. It drives the real entrypoint with a stub launcher and asserts the
generated `SPRING_APPLICATION_JSON` parses and round-trips the secret for eight
values: plain, CR, TAB, double quote, backslash, backslash-and-quote, non-ASCII
and spaces. It also covers the missing-secret refusal and that the secret never
reaches the log. Verified it catches the old behaviour: the previous escaper
produced `Invalid control character` on the CR case.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/service/interceptor/Authentication.java:
##
@@ -77,19 +90,39 @@ protected T authenticate(String authority, String
token, Function
}
String name = info.substring(0, delim);
-// TODO: password validation is skipped — only service name is
checked against
-// innerModules. Full credential validation should be added as
part of the auth refactor.
-//String pwd = info.substring(delim + 1);
-if (innerModules.contains(name)) {
-return call.get();
-} else {
+String pwd = info.substring(delim + 1);
Review Comment:
Fixed in 3b39132, taking the suggestion. Line 89 is now `new String(decode,
StandardCharsets.UTF_8)`.
Confirmed both directions in isolation before and after: the old decode
rejects `hg:sécrèt-2026` under `-Dfile.encoding=US-ASCII` and accepts it under
UTF-8, the new one accepts it under both. Also end to end on the packaged dist
with the secret in `conf/application.yml` and PD started with `LANG=C LC_ALL=C
-Dfile.encoding=US-ASCII`: the non-ASCII secret now gets 200 and a wrong one
still gets 401.
One nearby case this does not cover, since it is a different path: passing a
non-ASCII secret through `SPRING_APPLICATION_JSON` still depends on how the JVM
decodes the environment (`sun.jnu.encoding`), so it can be mangled before
Spring parses it. The Docker recipe generates a hex secret, so it does not bite
there.
##
docker/README.md:
##
@@ -66,6 +67,37 @@ For the verification commands below, set the password in
your current shell:
ADMIN_PASSWORD='the-same-password-used-in-.env'
```
+The PD REST API (port 8620, HStore topologies only) has its own credential:
+requests other than health probes need HTTP Basic auth with an internal
+service name (for example `hg`) and the PD secret as the password. PD ships
+no default secret, so `HG_PD_AUTH_SECRET_KEY` is required and the HStore
+Compose files refuse to start without it. The `.env` command above generates
+one. To list registered stores:
+
+```bash
+curl -u "hg:${HG_PD_AUTH_SECRET_KEY}" http://localhost:8620/v1/stores
+```
+
+Three consumers read this credential, and all three have to agree or startup
+fails:
+
+- PD itself, through `HG_PD_AUTH_SECRET_KEY`.
+- The Server, whose `bin/wait-storage.sh` polls `/v1/stores` before the
+ Server starts. Both Compose files pass `PD_AUTH_PASSWORD` to it from the
+ same variable, so setting `HG_PD_AUTH_SECRET_KEY` in `.env` covers it. If
+ the Server sends the wrong secret it retries until
+ `WAIT_STORAGE_TIMEOUT_S` (300s) expires and the container exits with
+ `ERROR: Timeout waiting for storage backend`.
+- Hubble, through `operations.pd.password` in the file under
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3930889066
##
docker/README.md:
##
@@ -66,6 +67,37 @@ For the verification commands below, set the password in
your current shell:
ADMIN_PASSWORD='the-same-password-used-in-.env'
```
+The PD REST API (port 8620, HStore topologies only) has its own credential:
+requests other than health probes need HTTP Basic auth with an internal
+service name (for example `hg`) and the PD secret as the password. PD ships
+no default secret, so `HG_PD_AUTH_SECRET_KEY` is required and the HStore
+Compose files refuse to start without it. The `.env` command above generates
+one. To list registered stores:
+
+```bash
+curl -u "hg:${HG_PD_AUTH_SECRET_KEY}" http://localhost:8620/v1/stores
+```
+
+Three consumers read this credential, and all three have to agree or startup
+fails:
+
+- PD itself, through `HG_PD_AUTH_SECRET_KEY`.
+- The Server, whose `bin/wait-storage.sh` polls `/v1/stores` before the
+ Server starts. Both Compose files pass `PD_AUTH_PASSWORD` to it from the
+ same variable, so setting `HG_PD_AUTH_SECRET_KEY` in `.env` covers it. If
+ the Server sends the wrong secret it retries until
+ `WAIT_STORAGE_TIMEOUT_S` (300s) expires and the container exits with
+ `ERROR: Timeout waiting for storage backend`.
+- Hubble, through `operations.pd.password` in the file under `conf/hubble/`.
+ That file is mounted read-only and is not templated, so write the same value
+ into it by hand. Until you do, Hubble's PD-backed views get 401 from PD;
+ everything else in Hubble works.
+
+```bash
+sed -i.bak
"s#^operations.pd.password=.*#operations.pd.password=${HG_PD_AUTH_SECRET_KEY}#"
\
Review Comment:
⚠️ This command reports success and changes nothing: `HG_PD_AUTH_SECRET_KEY`
is never in the operator's shell at this point.
The `.env` recipe at lines 32-45 runs inside `( ... )`, so the generated
value reaches the file and nothing else. Line 64 does the equivalent step for
the admin password ("set the password in your current shell"); there is no
counterpart for the PD secret. Following the page top to bottom:
- Line 78 expands to `curl -u hg: http://localhost:8620/v1/stores`, i.e. the
empty password, and returns the 401 this section exists to prevent.
- This `sed` expands to
`s#^operations.pd.password=.*#operations.pd.password=#`, rewriting the shipped
empty value to itself and exiting 0. Hubble keeps getting 401 with a
`hstore.properties.bak` sitting next to the file as evidence that something ran.
It also covers only `conf/hubble/hstore.properties`.
`docker-compose-3pd-3store-3server.yml:244` mounts
`conf/hubble/hstore-ha.properties`, which got the same empty
`operations.pd.password` in this PR, so an HA operator who runs this command is
still left with a broken Hubble.
Requested change: load `.env` first, refuse to write an empty value, and
name both files.
```bash
set -a; . ./.env; set +a
if [ -n "${HG_PD_AUTH_SECRET_KEY:-}" ]; then
sed -i.bak
"s#^operations.pd.password=.*#operations.pd.password=${HG_PD_AUTH_SECRET_KEY}#"
\
conf/hubble/hstore.properties # hstore-ha.properties for the HA
topology
else
echo 'HG_PD_AUTH_SECRET_KEY is empty; check .env' >&2
fi
```
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/service/interceptor/Authentication.java:
##
@@ -77,19 +90,39 @@ protected T authenticate(String authority, String
token, Function
}
String name = info.substring(0, delim);
-// TODO: password validation is skipped — only service name is
checked against
-// innerModules. Full credential validation should be added as
part of the auth refactor.
-//String pwd = info.substring(delim + 1);
-if (innerModules.contains(name)) {
-return call.get();
-} else {
+String pwd = info.substring(delim + 1);
Review Comment:
⚠️ The password is decoded with the JVM default charset but compared as
UTF-8, so a non-ASCII secret authenticates or not depending on the host locale.
Line 86 is `String info = new String(decode);`, no charset, so it uses
`Charset.defaultCharset()`. Until this line the only thing read out of that
string was `name`, and the four service names are ASCII, so the charset never
mattered. It does now: line 122 compares `pwd.getBytes(UTF_8)` against
`secret.getBytes(UTF_8)`, and the secret side comes from the YAML config, which
Spring reads as UTF-8. The two agree only when the default charset is UTF-8.
PD targets JDK 11, where the default charset still follows the locale (JEP
400 lands in 18), and `bin/start-hugegraph-pd.sh:171-196` sets no
`-Dfile.encoding`. The tarball path this PR documents is where that bites: a PD
started from systemd or a shell with `LANG` unset gets US-ASCII and rejects the
secret that worked
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3930703534
##
docker/test-compose.sh:
##
@@ -21,6 +21,7 @@ set -Eeuo pipefail
DOCKER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PASSWORD="ci-compose-password"
SECRET="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+PD_SECRET="ci-compose-pd-secret"
Review Comment:
‼️ Please also pass `HG_PD_AUTH_SECRET_KEY="${PD_SECRET}"` through
`compose_active` (or route the smoke path through `compose_auth`). The new
secret is currently supplied only by `compose_auth` for render; `smoke` calls
`compose_active` at lines 347-349, so the hstore smoke cannot interpolate
`docker-compose-hstore.yml` and fails before testing the stack. This is
reproduced on the exact head by the latest `build-server (rocksdb, 11)` run
above, which reports `HG_PD_AUTH_SECRET_KEY` missing.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3928071839
##
hugegraph-pd/hg-pd-dist/docker/docker-entrypoint.sh:
##
@@ -57,8 +57,16 @@ require_env "HG_PD_INITIAL_STORE_LIST"
: "${HG_PD_DATA_PATH:=/hugegraph-pd/pd_data}"
: "${HG_PD_INITIAL_STORE_COUNT:=1}"
+# Optional secret for REST Basic authentication (auth.secret-key). When unset,
+# the value from conf/application.yml applies. Never logged.
+AUTH_JSON=""
+if [[ -n "${HG_PD_AUTH_SECRET_KEY:-}" ]]; then
+AUTH_JSON="\"auth\": { \"secret-key\": \"$(json_escape
"${HG_PD_AUTH_SECRET_KEY}")\" },"
Review Comment:
⚠️ The optional secret is inserted through `json_escape`, but that helper
only escapes backslashes and quotes and removes LF; it leaves other JSON
control characters such as CR and tab unescaped. Reproduction: on this exact
head, setting HG_PD_AUTH_SECRET_KEY to a value containing `a\rb` produces an
invalid SPRING_APPLICATION_JSON, so the PD container fails before startup.
Please escape all JSON control characters or avoid hand-building this JSON, and
add a test for the override.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3928159161
##
hugegraph-pd/hg-pd-dist/src/assembly/static/conf/application.yml:
##
@@ -44,6 +44,15 @@ server:
# REST service port number
port: 8620
+auth:
+ # Shared secret checked against the password of the Basic credential on every
+ # authenticated REST request. Clients must send one of the internal service
+ # names (hg, store, hubble, vermeer) with this value as the password.
+ # CHANGE THIS IN PRODUCTION and keep it in sync with every client that calls
+ # the PD REST API (e.g. Hubble's operations.pd.password). Do not expose the
+ # REST port (8620) outside a trusted network.
+ secret-key: FXQXbJtbCLxODc6tGci732pkH1cyf8Qg
Review Comment:
You are right, and this is fixed in 5c339c1. Both halves of what you asked
for:
Required, not defaulted. Both `application.yml` files now ship
`auth.secret-key` empty. The Docker image requires `HG_PD_AUTH_SECRET_KEY`, and
both HStore Compose files fail to render without it rather than falling back to
a shared value; the `.env` recipe generates one next to the JWT secret. The
Hubble properties ship the password empty with the manual step documented.
Fails startup on the published default. PD refuses to boot if
`auth.secret-key` equals the value earlier revisions carried, so a deployment
that copied it does not silently keep a well-known credential.
Verified on the packaged dist: startup refused with the published value,
shipped config starts but answers 401 to every credential while naming the key
in an error, and a deployment-provided secret restores normal access.
Unrelated but worth flagging: `hugegraph-struct/.../AuthOptions.java:51`
uses the same published string as the default for the Server's
`auth.token_secret`. Out of scope here; happy to file it separately.
##
hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:
##
@@ -39,7 +39,9 @@ log() {
echo "[wait-storage] $1"
}
-PD_AUTH_ARGS="-u ${PD_AUTH_USER:-store}:${PD_AUTH_PASSWORD:-admin}"
+# PD validates the password against its auth.secret-key; the default below
+# matches PD's shipped default. Override both when the PD secret is changed.
+PD_AUTH_ARGS="-u
${PD_AUTH_USER:-store}:${PD_AUTH_PASSWORD:-FXQXbJtbCLxODc6tGci732pkH1cyf8Qg}"
Review Comment:
Fixed in 5c339c1 after all, rather than deferring it. The inner shell now
reads the credential from the environment and passes it to curl on stdin as a
config file, so it is neither part of the `bash -c` source text nor visible in
argv. Values are escaped for the `-K` quoted-string form, backslash first.
`PD_AUTH_PASSWORD` no longer carries a default, since PD ships no secret.
`test-wait-storage.sh` now asserts the credential is absent from argv and
present in the config the mock reads from stdin; 5/5 still pass.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3924727033
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/interceptor/RestAuthentication.java:
##
@@ -59,6 +59,7 @@ public boolean preHandle(HttpServletRequest request,
HttpServletResponse respons
authority = authority.replace("Basic ", "");
return authenticate(authority, token, tokenCall, DEFAULT_HANDLE);
} catch (Exception e) {
+response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
Review Comment:
Fixed in 1e3b616, taking the suggestion as written. Verified on the wire:
`HTTP/1.1 401 Unauthorized` now carries `WWW-Authenticate: Basic
realm="hugegraph-pd"`. You are right that the existing coverage could not catch
it, since `curl -u` and the new `RestApiTest` cases both send Basic
preemptively.
##
hugegraph-pd/README.md:
##
@@ -100,6 +100,7 @@ Key configuration file: `conf/application.yml`
| `raft.address` | `127.0.0.1:8610` | Raft service address for this PD node |
| `raft.peers-list` | `127.0.0.1:8610` | Comma-separated list of all PD nodes
in the Raft cluster |
| `pd.data-path` | `./pd_data` | Directory for storing PD metadata and Raft
logs |
+| `auth.secret-key` | (public default) | Password required by the REST API
with an internal service name (`hg`, `store`, `hubble`, `vermeer`) via HTTP
Basic auth. Change it in production and configure every REST client (e.g.
Hubble's `operations.pd.password`) with the same value |
Review Comment:
Fixed in 1e3b616. `docs/configuration.md` gained a REST Authentication
section with the `auth.secret-key` row, the unauthenticated paths and the
client-side names, and `docs/api-reference.md` gained a note at the top of the
REST API section saying the examples below omit `-u` and which paths do not
need it. Took the `operations-guide.md` `balanceLeaders` procedure now as you
suggested: it and the two calls in the same runbook step carry `-u
hg:"${PD_SECRET}"`, with a note at the top of the file defining it. The wider
sweep across the other Store docs is the follow-up.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/service/interceptor/Authentication.java:
##
@@ -77,19 +84,33 @@ protected T authenticate(String authority, String
token, Function
}
String name = info.substring(0, delim);
-// TODO: password validation is skipped — only service name is
checked against
-// innerModules. Full credential validation should be added as
part of the auth refactor.
-//String pwd = info.substring(delim + 1);
-if (innerModules.contains(name)) {
-return call.get();
-} else {
+String pwd = info.substring(delim + 1);
+if (!innerModules.contains(name)) {
throw new AccessDeniedException("invalid service name");
}
+if (!verifySecret(pwd)) {
+throw new BadCredentialsException("invalid credential");
+}
Review Comment:
Fixed in 1e3b616, taking the second option. The check stays in the base
class, so the gRPC path is not left permanently name-only, and the
`GRpcServerConfig` TODO now records that registering the interceptor first
requires giving the secret to the three clients, naming
`ServiceConstant.AUTHORITY`, `DefaultPdProvider.authority` and `hg-pd-cli` with
their current `""` / `"default"` values. Verified the interceptor is still
unregistered at this head, so nothing changes for gRPC today.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3924725808
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/service/interceptor/Authentication.java:
##
@@ -77,19 +84,33 @@ protected T authenticate(String authority, String
token, Function
}
String name = info.substring(0, delim);
-// TODO: password validation is skipped — only service name is
checked against
-// innerModules. Full credential validation should be added as
part of the auth refactor.
-//String pwd = info.substring(delim + 1);
-if (innerModules.contains(name)) {
-return call.get();
-} else {
+String pwd = info.substring(delim + 1);
+if (!innerModules.contains(name)) {
throw new AccessDeniedException("invalid service name");
}
+if (!verifySecret(pwd)) {
+throw new BadCredentialsException("invalid credential");
+}
+return call.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
+/**
+ * Compare the password of the Basic credential with the shared secret
+ * configured via `auth.secret-key`. A missing or empty secret refuses
every
+ * request instead of falling back to name-only authentication.
Review Comment:
Fixed in 1e3b616. Confirmed your resolution independently against
spring-core 5.3.20: `resolved=[ 'FXQXbJtbCLxODc6tGci732pkH1cyf8Qg']`, 35 chars.
`PDConfig.java:72` is now `@Value("${auth.secret-key:}")`, so an absent key
yields `""` and this contract holds, plus a one-shot ERROR naming the parameter
and the fix. Verified on the packaged dist with the `auth` block stripped from
`conf/application.yml`: the shipped secret gets 401, the old quoted-literal
string gets 401, and the log line appears. The upgrade note is in the PD README
security section. `pd.initial-store-list` at line 57 left alone for a separate
pass, as you suggested.
##
hugegraph-pd/README.md:
##
@@ -280,6 +281,19 @@ docker/docker-compose-3pd-3store-3server.yml
- Ensure low latency (<5ms) between PD nodes for Raft consensus
- Open required ports: `8620` (REST), `8686` (gRPC), `8610` (Raft)
+### Security
+
+- Keep all three ports on a trusted network. The REST API on `8620` includes
+ management endpoints that mutate the cluster (peer changes, store removal,
+ data movement), and the gRPC and Raft ports carry no authentication.
+- REST requests need HTTP Basic auth: one of the internal service names
+ (`hg`, `store`, `hubble`, `vermeer`) with the `auth.secret-key` value as
+ the password. Health probes (`/v1/health`, `/actuator/*`,
+ `/v1/prom/targets/*`) stay unauthenticated.
Review Comment:
Fixed in 1e3b616. Narrowed to `health,metrics,prometheus` in both
`application.yml` files and updated the matching row and example in
`docs/configuration.md`, which documented `"*"`. Verified on the running dist:
`/actuator/health`, `/metrics` and `/prometheus` still 200, while
`/actuator/env`, `/beans` and `/configprops` no longer serve data. They return
401 rather than 404, because the unmapped dispatch re-enters the interceptor,
which seems the better of the two.
##
docker/README.md:
##
@@ -66,6 +66,22 @@ For the verification commands below, set the password in
your current shell:
ADMIN_PASSWORD='the-same-password-used-in-.env'
```
+The PD REST API (port 8620, HStore topologies only) has its own credential:
+requests other than health probes need HTTP Basic auth with an internal
+service name (for example `hg`) and the PD secret as the password. PD ships
+with a default secret in `conf/application.yml` (`auth.secret-key`), and the
+Hubble files under `conf/hubble/` carry the matching `operations.pd.password`.
+With the shipped default, list registered stores like this:
+
+```bash
+curl -u hg:FXQXbJtbCLxODc6tGci732pkH1cyf8Qg http://localhost:8620/v1/stores
+```
+
+The default secret is public (it is in the source tree), so it only keeps
+casual traffic out. On any shared network, change it: set
+`HG_PD_AUTH_SECRET_KEY` on the PD services and put the same value in the
+Hubble properties files, or do not publish port 8620 at all.
Review Comment:
Fixed in 1e3b616, with one correction to the suggestion.
`HG_PD_AUTH_SECRET_KEY` cannot go in the `x-pd-common` anchor: each pd service
defines its own `environment:` block, and a service-level key replaces the
merged mapping wholesale instead of deep-merging, so it would be silently
dropped. It is set per service instead, on pd0/pd1/pd2 and the single `pd` in
the hstore file, with `PD_AUTH_PASSWORD` on the server anchor and the hstore
server. `docker compose config` with `HG_PD_AUTH_SECRET_KEY=rotated-secret-xyz`
renders that value at every consumer. The paragraph now names all three
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
imbajin commented on code in PR #3189: URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3924059642 ## hugegraph-pd/hg-pd-dist/src/assembly/static/conf/application.yml: ## @@ -44,6 +44,15 @@ server: # REST service port number port: 8620 +auth: + # Shared secret checked against the password of the Basic credential on every + # authenticated REST request. Clients must send one of the internal service + # names (hg, store, hubble, vermeer) with this value as the password. + # CHANGE THIS IN PRODUCTION and keep it in sync with every client that calls + # the PD REST API (e.g. Hubble's operations.pd.password). Do not expose the + # REST port (8620) outside a trusted network. + secret-key: FXQXbJtbCLxODc6tGci732pkH1cyf8Qg Review Comment: ⚠️ The shipped PD image enables REST authentication with a fixed repository-published secret. The default HStore Compose files publish PD port 8620 to the host, so anyone who can reach that port can read this source/default and authenticate as an internal service against management endpoints. The README warning does not enforce a change. Please require a deployment-provided or generated secret, or fail startup when the public default is still in use. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
bitflicker64 commented on code in PR #3189:
URL: https://github.com/apache/hugegraph/pull/3189#discussion_r3923380792
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/service/interceptor/Authentication.java:
##
@@ -77,19 +84,33 @@ protected T authenticate(String authority, String
token, Function
}
String name = info.substring(0, delim);
-// TODO: password validation is skipped — only service name is
checked against
-// innerModules. Full credential validation should be added as
part of the auth refactor.
-//String pwd = info.substring(delim + 1);
-if (innerModules.contains(name)) {
-return call.get();
-} else {
+String pwd = info.substring(delim + 1);
+if (!innerModules.contains(name)) {
throw new AccessDeniedException("invalid service name");
}
+if (!verifySecret(pwd)) {
+throw new BadCredentialsException("invalid credential");
+}
+return call.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
+/**
+ * Compare the password of the Basic credential with the shared secret
+ * configured via `auth.secret-key`. A missing or empty secret refuses
every
+ * request instead of falling back to name-only authentication.
Review Comment:
‼️ This contract does not hold. A PD whose config omits `auth.secret-key`
does not refuse every request, it authenticates against a string no client will
send.
`PDConfig.java:72` declares the field as `@Value("${auth.secret-key:
'FXQXbJtbCLxODc6tGci732pkH1cyf8Qg'}")`. Spring's `PropertyPlaceholderHelper`
takes everything after the first `:` as a literal default, with no trimming and
no quote stripping. Against spring-core 5.3.20, the line
`spring-boot-starter-web:2.5.14` resolves:
```
resolved=[ 'FXQXbJtbCLxODc6tGci732pkH1cyf8Qg']
equalsDocumented=false
```
So `getSecretKey()` returns `" 'FXQXbJtbCLxODc6tGci732pkH1cyf8Qg'"`,
`StringUtils.isEmpty` is false, the branch below never runs, and `verifySecret`
rejects the value this PR ships in both `application.yml` files,
`wait-storage.sh` and the Hubble properties.
`start-hugegraph-pd.sh:178` passes
`-Dspring.config.location=${CONF}/application.yml`, which replaces the default
config locations rather than adding to them, so only that one file is read. An
in-place upgrade keeping the operator's existing `conf/application.yml` has no
`auth` block, and the failure is not a warning: every client gets 401,
`wait-storage.sh:118-124` retries until `WAIT_STORAGE_TIMEOUT_S=300` expires,
then exits 1.
Requested change: in `PDConfig.java:72` use `@Value("${auth.secret-key:}")`
so an absent key yields `""` and the fail-closed path this javadoc describes
actually runs, and log an ERROR naming `auth.secret-key` when it is empty. That
makes the failure diagnosable rather than preventing it, so the upgrade still
needs a release note telling operators to add the key to an existing
`conf/application.yml` first. `PDConfig.java:57` has the same quoted-default
shape for `pd.initial-store-list`, worth a separate pass.
##
hugegraph-pd/README.md:
##
@@ -280,6 +281,19 @@ docker/docker-compose-3pd-3store-3server.yml
- Ensure low latency (<5ms) between PD nodes for Raft consensus
- Open required ports: `8620` (REST), `8686` (gRPC), `8610` (Raft)
+### Security
+
+- Keep all three ports on a trusted network. The REST API on `8620` includes
+ management endpoints that mutate the cluster (peer changes, store removal,
+ data movement), and the gRPC and Raft ports carry no authentication.
+- REST requests need HTTP Basic auth: one of the internal service names
+ (`hg`, `store`, `hubble`, `vermeer`) with the `auth.secret-key` value as
+ the password. Health probes (`/v1/health`, `/actuator/*`,
+ `/v1/prom/targets/*`) stay unauthenticated.
Review Comment:
⚠️ `/actuator/*` covers more than the probes this line describes, on the
port the PR is hardening.
Both shipped configs set `management.endpoints.web.exposure.include: "*"` on
port 8620 (`hg-pd-dist/src/assembly/static/conf/application.yml:30`,
`hg-pd-service/src/main/resources/application.yml:30`), and
`AuthenticationConfigurer.java:35` excludes `/actuator/*` from the interceptor.
Spring Boot 2.5's full actuator set includes endpoints that dump process and
configuration state, and every one of them whose path is a single segment is
anonymous on 8620. The three the docs actually reference are `health`,
`metrics` and `prometheus` (`hugegraph-pd/README.md:198`,
`hugegraph-pd/docs/configuration.md:705,718,731`).
Pre-existing configuration, so not a regression, but this PR is where the
port gets a credential worth protecting, and
`hugegraph-pd/docs/configuration.md:262` already
Re: [PR] fix(pd): validate REST credentials and return 401 on refusal [hugegraph]
codecov[bot] commented on PR #3189: URL: https://github.com/apache/hugegraph/pull/3189#issuecomment-5521241352 ## [Codecov](https://app.codecov.io/gh/apache/hugegraph/pull/3189?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report :white_check_mark: All modified and coverable lines are covered by tests. :white_check_mark: Project coverage is 93.25%. Comparing base ([`98477f0`](https://app.codecov.io/gh/apache/hugegraph/commit/98477f0f56a3ad49593ec7632f2f0ee13e72f0dd?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`f796637`](https://app.codecov.io/gh/apache/hugegraph/commit/f796637919317786326375ee9373feeb42b8f57e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)). Additional details and impacted files ```diff @@ Coverage Diff @@ ## master#3189 +/- ## = + Coverage 37.78% 93.25% +55.47% + Complexity 6556 65 -6491 = Files 8009 -791 Lines 68929 267-68662 Branches 9157 22 -9135 = - Hits 26046 249-25797 + Misses398248-39816 + Partials 3059 10 -3049 ``` [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/hugegraph/pull/3189?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache). :rocket: New features to boost your workflow: - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
