feat(cubeapi): add webhook event notifications
Summary
This PR adds configurable CubeAPI webhook notifications for sandbox lifecycle events.
Supported lifecycle events:
sandbox.createdsandbox.deletedsandbox.pausedsandbox.resumed
Main capabilities:
- Configure one or more webhook endpoints through
CUBE_API_WEBHOOK_ENDPOINTS - Configure event subscriptions independently for each endpoint
- Deliver JSON payloads through asynchronous HTTP POST
- Keep webhook delivery outside sandbox lifecycle request paths
- Use a bounded queue and bounded delivery concurrency
- Support optional HMAC-SHA256 signing
- Retry eligible delivery failures with bounded exponential backoff
- Log delivery failures without exposing endpoint secrets or signatures
- Provide a runnable standard-library Python receiver and bilingual validation guides
Design Notes
Webhook delivery is implemented as a CubeAPI logging backend.
API handlers emit structured LogEvent values. The existing logger fan-out preserves FileLogger behavior and optionally adds HttpLogger when webhook endpoints are configured.
Webhook delivery is best-effort and asynchronous. Endpoint failures, timeouts, retries, or queue pressure do not change sandbox lifecycle API responses.
Lifecycle payloads include:
idtimestampleveleventsandbox_idtemplate_id, when available
The payload is intentionally not a complete Sandbox object. Sensitive fields such as tokens, secrets, credentials, environment variables, and selected runtime or network details are removed before serialization and are not delivered.
Key Behavioral Guarantees
- Webhook support remains disabled when no endpoints are configured.
- Delivery does not determine the result of sandbox lifecycle API requests.
- Queues and delivery concurrency are bounded.
- Retry backoff does not hold an HTTP concurrency permit.
- Redirects are disabled.
- Non-public targets are rejected by default unless explicitly allowed.
- Domain endpoints are asynchronously resolved and validated at startup.
- Validated addresses are pinned into the HTTP client.
- Sensitive payload fields are removed recursively before serialization.
- Endpoint secrets and signatures are not written to logs.
- Invalid webhook configuration fails during startup instead of being silently ignored.
Reviewer Guide
Suggested review order:
-
CubeAPI/src/config/mod.rs- Webhook configuration, defaults, environment parsing, and validation
-
CubeAPI/src/main.rs- Optional asynchronous
HttpLoggerinitialization and logger fan-out
- Optional asynchronous
-
CubeAPI/src/logging/http.rs- Endpoint validation and DNS resolution
- SSRF protection and address pinning
- Queue and background dispatcher
- Concurrency control, retries, and graceful shutdown
- Payload sanitization and HMAC signing
-
Tests in
CubeAPI/src/logging/http.rs- Configuration validation
- URL and DNS validation
- Payload redaction
- Queue and retry behavior
- Actual delivered request headers and signature
-
CubeAPI/examples/webhook-receiver/- Runnable receiver
- Signature verification
- English and Simplified Chinese local lifecycle validation guides
-
CubeAPI/README.md- Configuration and webhook request format
Acceptance Criteria Coverage
| Requirement | Implementation / evidence |
|---|---|
| Configure one or more endpoints | CUBE_API_WEBHOOK_ENDPOINTS endpoint array |
| Subscribe by event type | Per-endpoint events configuration and filtering tests |
| Four lifecycle events | Created, paused, resumed, and deleted lifecycle validation |
| JSON HTTP POST payload | Delivery implementation and captured-request tests |
| Async non-blocking delivery | Bounded queue/background dispatcher and unreachable-receiver validation |
| Optional HMAC-SHA256 | Receiver verification example and wire-signature test |
| Retry and error logging | Retry tests and runtime unreachable-receiver logs |
| Runnable example and documentation | CubeAPI/examples/webhook-receiver/ with English and Simplified Chinese validation guides |
| Core tests and formatting | Webhook test suite, full test suite, format check, and build |
Validation
Verification note: the runtime screenshots and complete logs were captured from commit
e7728667e7f2c9f07695761977cbde79a53212f9. Subsequent commits17a4abfand7bc06cbonly update documentation and do not change CubeAPI or webhook runtime behavior.
Validated on Linux:
cargo fmt --check
cargo test logging::http::tests -- --nocapture
cargo test
cargo build
python3 -m py_compile examples/webhook-receiver/receiver.py
Results
logging::http::tests: 42 passed, 0 failed
cargo test: 114 passed, 0 failed
cargo build: passed
cargo fmt --check: passed
receiver.py py_compile: passed
Lifecycle validation
The example receiver successfully received:
sandbox.created
sandbox.paused
sandbox.resumed
sandbox.deleted
The receiver was started with WEBHOOK_SECRET=test-secret, validating the documented signed-delivery path.
Non-blocking failure-path validation
The webhook endpoint was configured to an intentionally unreachable receiver:
http://127.0.0.1:18081/webhook
The receiver was not running, but all sandbox lifecycle API operations still succeeded:
create sandbox: success
pause sandbox: success
resume sandbox: success
delete sandbox: success
CubeAPI logs recorded delivery failures, retries, and retry exhaustion for each lifecycle event.
This confirms that receiver unavailability does not prevent sandbox lifecycle API requests from succeeding.
Out of Scope
This PR does not add:
- A REST API for webhook administration
- A persistent outbox or disk spool
- A dead-letter queue
- Batch delivery
- Exactly-once delivery
Possible Follow-up Work
Future work can build on this delivery foundation without expanding the scope of this PR:
- Additional sandbox lifecycle and failure-path events, after their API semantics and payload contracts are defined and validated
- Delivery observability, including success/failure counters, latency metrics, and dropped-event metrics
- Optional circuit breaking, persistent outbox, or dead-letter handling for deployments that require stronger delivery guarantees
Refs #642
Test
Thanks, I pushed an update for the webhook review items.
This covers the startup/config validation path, stricter endpoint URL validation, safe endpoint debug output, and stronger payload redaction. In particular, malformed CUBE_API_WEBHOOK_ENDPOINTS now fails startup, embedded URL credentials are rejected, non-public URL targets are blocked by default unless explicitly opted in, and camelCase/PascalCase sensitive fields are now redacted consistently with the existing snake_case rules.
I also updated the local receiver docs and added tests for the validation, redaction, and debug-output cases.
Verified on the server with fmt, the webhook logger tests, the full test suite, and build.
Thanks for the detailed review.
I addressed the latest webhook-related comments in this round. The changes mainly cover:
- startup DNS resolution and validation for domain-name webhook endpoints, with resolved addresses pinned into the shared reqwest client;
- a practical upper bound for
max_retries; - fixed the backoff jitter test so it actually varies the attempt value;
- a sanitization depth limit for deeply nested JSON payloads;
- explicit reqwest connection settings for connect timeout and idle pool behavior;
- simplified
sign_payloadto returnStringdirectly; - derived secret-material redaction for fields like
db_password_hash/client_secret_b64; - removal of the extra cloned sanitized field map during webhook payload serialization.
I also updated the README for the new DNS validation and pinned-address behavior.
Validation on the server:
cargo fmt --checkcargo test logging::http::tests -- --nocapturecargo testcargo build
All tests passed locally on the validation server; existing build warnings are unrelated to this webhook change.
Thanks for the detailed follow-up review.
I addressed the latest webhook review comments with focused changes:
- Replaced blocking startup hostname resolution with
tokio::net::lookup_hostand made webhook logger initialization async. - Changed the serialized delivery body storage from
Vec<u8>to ref-countedBytes, so retry attempts no longer clone the full payload. - Lowered the validated maximum webhook retry count from 20 to 6 to reduce the worst-case retry window from misconfiguration.
- Added an explicit webhook
User-Agentheader (CubeAPI-Webhook/1.0) so outgoing requests do not rely on the HTTP client default. - Replaced the mock server's oneshot/yield-based readiness signal with a bounded HTTP readiness probe against a dedicated
GET /__readyroute.
The existing webhook behavior is otherwise preserved: request body bytes, JSON payload shape, signing input, signature format, retry/backoff flow, timeout behavior, DNS pinning behavior, endpoint validation, redaction, and sanitization behavior are unchanged.
I also reviewed the suggested top-level sanitizer pre-check, but did not implement it because it would be unsafe for nested secrets. The sanitizer intentionally removes sensitive fields recursively and enforces the nesting-depth limit, so a top-level-only bypass could allow nested sensitive fields to be delivered.
Validation completed:
cargo fmt --checkcargo test logging::http::tests -- --nocapturecargo testcargo build- Manual CubeSandbox lifecycle smoke test with the example webhook receiver:
sandbox.created,sandbox.paused,sandbox.resumed, andsandbox.deletedwere all delivered successfully.
Update after the latest webhook follow-up commits:
I addressed the lower-risk webhook review follow-ups in the latest commits:
- Documented why
pool_max_idle_per_hostis intentionally smaller thanmax_concurrency.max_concurrencybounds active in-flight requests, while the idle pool cap only limits post-burst retained idle connections. - Rejected zero
initial_backoff_msandmax_backoff_msvalues during webhook config validation. - Downgraded expected delivery task cancellations during flush-timeout shutdown from
errortowarn, while keeping panics and other task failures aterror. - Documented that the semaphore permit is intentionally acquired per HTTP attempt and released before retry backoff sleeps.
- Documented that endpoint
enableddefaults totrue, and added the explicit webhookUser-Agentto the README request format. - Added an end-to-end header correctness test that captures the actual delivered request and validates
Content-Type,User-Agent,X-Cube-Webhook-*headers, delivery id consistency, timestamp parsing, and the HMAC signature over the raw wire body.
Validation completed on Linux:
cargo fmt --checkcargo test logging::http::tests -- --nocapturecargo testcargo build
I intentionally left the maximum webhook payload body size as a separate follow-up because it introduces a new runtime behavior decision, such as whether to reject, truncate, or drop oversized webhook deliveries.
Refs #642 (this is a multi-participation issue, please use Refs instead of Closes)
Update after the latest documentation commit and validation:
The latest commit mainly improves the webhook receiver example documentation. It clarifies:
- The lifecycle check requires a working local CubeSandbox deployment.
- For PR/source-tree validation against an existing deployment, the running CubeAPI process must be built from this source tree.
- If an older systemd-managed CubeAPI service is already running, it should be temporarily stopped before running the current branch CubeAPI binary.
- The receiver is only the webhook notification target; it does not run sandbox lifecycle operations.
- The expected receiver output should include:
sandbox.createdsandbox.pausedsandbox.resumedsandbox.deleted
- Troubleshooting notes now cover local loopback receivers, missing callbacks, signature failures, and container-localhost behavior.
Validation completed on Linux:
cargo fmt --checkcargo test logging::http::tests -- --nocapturecargo testcargo build
Manual lifecycle validation completed with the example receiver:
sandbox.createdsandbox.pausedsandbox.resumedsandbox.deleted
I also manually validated the non-blocking failure path. I configured the webhook endpoint to an intentionally unreachable receiver:
http://127.0.0.1:18081/webhook
The receiver was not running. The sandbox lifecycle API calls still succeeded:
- create sandbox: success
- pause sandbox: success
- resume sandbox: success
- delete sandbox: success
CubeAPI logs showed webhook delivery failures, retries, and retry exhaustion for the lifecycle events.
Conclusion: the existing webhook delivery behavior is asynchronous and non-blocking; receiver unavailability does not prevent sandbox lifecycle API requests from succeeding.
Hello, thank you for your contribution! Since we have a large number of participants in this event, to speed up the PR review process, could you please attach some screenshots and logs (both are needed) showing the verification process and results for this PR? Thank you for your participation!
Thank you for the review. I have attached both screenshots and the complete text logs showing the verification process and results for this PR.
Verification environment
- Repository:
hyy321/CubeSandbox - Branch:
feat/cubeapi-webhooks - Commit:
e7728667e7f2c9f07695761977cbde79a53212f9 - Working tree: clean
- CubeSandbox node: healthy
- Test template:
tpl-2d326315c7e64985b0bba2a9
1. Source, environment, and build verification
The screenshot below shows:
- the repository source
- the PR branch
- the exact commit used for verification
- a clean working tree
- a successful CubeAPI build
- a READY sandbox template
- a healthy CubeSandbox node and CubeAPI service
2. Signed lifecycle API operations
The example receiver was started with HMAC verification enabled:
WEBHOOK_SECRET=test-secret python3 -u receiver.py
CubeAPI was configured to send the following lifecycle events:
sandbox.createdsandbox.pausedsandbox.resumedsandbox.deleted
The following sandbox lifecycle operations all completed successfully:
- Create
- Pause
- Resume
- Delete
The validation process completed with exit code 0.
3. Signed receiver events
The receiver successfully verified and received all four signed lifecycle events:
sandbox.createdsandbox.pausedsandbox.resumedsandbox.deleted
The received output also includes the corresponding:
- sandbox ID
- delivery ID
- timestamp
- template ID where applicable
4. Unreachable receiver validation
The webhook endpoint was intentionally configured as:
http://127.0.0.1:18081/webhook
No process was listening on port 18081.
Despite the unreachable webhook receiver, all sandbox lifecycle operations still completed successfully:
- Create
- Pause
- Resume
- Delete
This confirms that webhook delivery failures do not block the main sandbox lifecycle paths.
CubeAPI retried each failed webhook delivery three times and then recorded retry exhaustion.
Results:
- Retrying log count:
12 - Retries exhausted log count:
4 sandbox.created: retries exhaustedsandbox.paused: retries exhaustedsandbox.resumed: retries exhaustedsandbox.deleted: retries exhausted
Each exhausted delivery recorded:
error_kind="connect"
attempts=4
5. Automated validation
The following checks all passed:
cargo fmt --checkcargo test --locked logging::http::tests -- --nocapture- 42 passed
- 0 failed
cargo test --locked- 114 passed
- 0 failed
cargo build --lockedpython3 -m py_compile examples/webhook-receiver/receiver.py
Overall automated validation result: PASS
Automated validation exit code: 0
6. Complete logs
The attached pr702-verification-full-logs.txt contains the complete logs for:
- source, branch, commit, and environment verification
- CubeSandbox node and CubeAPI health verification
- CubeAPI build
- built binary information
- READY template verification
- signed webhook receiver output
- signed lifecycle API operations
- unreachable receiver precondition verification
- non-blocking lifecycle operations with an unreachable receiver
- webhook retry and retry-exhaustion output
- format checks
- webhook-specific tests
- the full test suite
- the locked build
- the Python receiver syntax check
- restoration and health verification of the original CubeAPI service
The original CubeAPI system service was restored after verification and passed its health check.
Follow-up: I have pushed a documentation-only update to CubeAPI/examples/webhook-receiver/README.md. The runtime implementation has not changed. The screenshots and logs above correspond to commit e7728667e7f2c9f07695761977cbde79a53212f9.
Follow-up documentation update:
- Added a Simplified Chinese guide for the webhook receiver example.
- Added bidirectional links between the English and Chinese receiver guides.
- Updated
CubeAPI/README.mdto link to both language versions. - Clarified why the local validation workflow uses three terminals.
This update only changes documentation files. No runtime code or webhook behavior was changed, so the previous validation results remain applicable.
nice job
Follow-up update: payload protection and lifecycle accuracy
During follow-up validation of PR #702, I identified two edge cases where additional protection was necessary:
-
Serialized payload-size enforcement
The payload-size limit needs to be applied to the final serialized request body because this is the actual byte sequence allocated, signed, and transmitted to the receiver.
Without this check, an unexpectedly large event could still consume request-construction, signing, network, and retry resources, and could exceed size limits enforced by receivers or HTTP infrastructure.
-
Accurate
sandbox.resumedsemanticsA successful connect operation does not necessarily mean that a sandbox changed from paused to running.
Emitting
sandbox.resumedfor every successful connect could therefore produce duplicate or semantically inaccurate lifecycle events when the sandbox was already running.
I updated PR #702 with two focused improvements addressing these cases:
- Added a serialized Webhook payload-size limit before signing, request construction, delivery, and retry.
- Changed the connect and resume flows so that
sandbox.resumedis emitted only after an actual resume transition.
These changes do not alter the Webhook endpoint configuration, request format, signing format, event schema, or receiver interface. They strengthen resource protection and improve lifecycle-event accuracy.
Candidate
- Upstream baseline used for this candidate:
8bcbbbf71929b3329a799afead61a86cbc11089c - Original Webhook integration point:
8e21332f - Validated and pushed commit:
6afafa68da173967a5939501d9f4716f973dbf26
The upstream branch advanced after the original integration, but the intervening upstream commits did not modify the files touched by these follow-up changes. I kept the already validated candidate unchanged so that the pushed commit remains identical to the runtime-tested version.
Automated validation
cargo fmt --all -- --check: PASS- Lifecycle targeted tests:
5 passed, 0 failed cargo check --all-targets: PASScargo test --all-targets:144 passed, 0 failedcargo clippy --all-targets: PASS with non-blocking warnings
Security validation scope
The full test suite and existing implementation-level checks cover the following Webhook security and validation areas:
- URL scheme and embedded-credential validation
- Non-public destination and DNS-resolution validation
- Payload redaction and serialized-size enforcement
- Exact-byte HMAC-SHA256 signing and delivered-request verification
- Redirect, retry, timeout, and failure-logging behavior
- Checks that endpoint secrets and signatures are not exposed through diagnostic output
The runtime validation in this update is intentionally focused on the two follow-up changes described above: serialized payload-size protection and accurate sandbox.resumed emission.
The remaining security properties were covered by the full automated test suite and code-level validation; they were not all independently repeated as separate runtime experiments in this update. The runnable receiver example additionally demonstrates HMAC-SHA256 signature verification.
Payload-size runtime validation
The following checks were run directly on commit 6afafa68:
- Safety check and CubeAPI build: PASS
- Webhook receiver startup: PASS
- Oversized serialized payload: dropped with
payload_too_large - Receiver count for the oversized event:
0 - Normal Webhook payload delivery: PASS
- Normal payload JSON validation: PASS
- Runtime exit code:
0
Lifecycle runtime validation
The following scenarios were run directly on commit 6afafa68:
- Paused sandbox → connect: emitted one
sandbox.resumedevent - Running sandbox → connect: emitted no duplicate event
- Explicit resume: emitted the second
sandbox.resumedevent - RFC3339 timestamp compatibility: PASS
- Runtime exit code:
0 - Candidate worktree remained clean
- Official CubeAPI service was restored successfully
- Port
3000was listening after validation
The original four-event Webhook behavior was covered by the previous PR #702 verification. This follow-up validation focuses specifically on the two edge cases described above and verifies the corresponding fixes directly against the pushed commit.
The attached validation report contains the complete environment information, automated-test results, runtime results, and acceptance-criteria mapping.
Follow-up: endpoint-isolation hardening
During an additional review of the existing shared webhook scheduler, I identified two reproducible endpoint-isolation gaps and pushed two narrowly scoped fixes:
3c33542gives each endpoint an independent outstanding-delivery budget, preventing a blocked endpoint from consuming healthy endpoints' backlog capacity.c5ad8e6limits each endpoint to one pending attempt admission ahead of the global concurrency semaphore, preventing a hot endpoint from occupying multiple global waiter positions.
The changes are limited to CubeAPI/src/logging/http.rs. They do not add new user-facing features or change configuration, payloads, signing, lifecycle APIs, or retry semantics.
These two commits were validated as a fast-forward from the existing public PR tip 6afafa68 to c5ad8e6, using the same official CubeSandbox v0.5.1 deployment as the previous runtime validation.
Validation on candidate c5ad8e6:
- full suite: 156 passed, 0 failed
- targeted HTTP logger suite: 63 passed, 0 failed
- Stage 1 isolated runtime reproduction: passed
- Stage 2 isolated runtime reproduction: passed
- previously covered payload, signing, and retry behavior was rechecked on the final candidate
- candidate worktree remained clean, and all isolated test ports were released
Stage 1: endpoint backlog isolation
Stage 2: bounded global waiter positions
These changes harden endpoint failure isolation in the existing shared scheduler; they do not introduce or claim FIFO delivery ordering.
A concise validation summary for the final candidate is attached below:
Thanks for the review. I reviewed all eight comments individually; after deduplication, they covered four distinct findings.
The production webhook proxy-routing issue was addressed in commit
eaa6c177. The webhook delivery client now explicitly applies
ClientBuilder::no_proxy(), preserving the validated and DNS-pinned
destination routing. A deterministic local regression test was added, and its
negative control failed as expected when .no_proxy() was removed.
The remaining findings did not require code changes:
- The
PayloadTooLargeearly return is intentional under the current logger-wide event-level limit. - A simple timeout around
lookup_hostwould not reliably cancel the platform blocking resolver or provide a strict process-level startup bound, so DNS deadline handling should be designed separately. thread_rng()is not reseeded per retry, and no RNG state is held across an await point.
Linux validation against baseline c5ad8e6 completed successfully:
cargo fmt --all -- --checkcargo check --all-targetscargo test logging::http: 64 passedcargo test: 157 passedcargo clippy --all-targets: exit 0
The follow-up remains narrowly scoped to the concrete proxy-routing issue.
Apologies for not noticing the merge conflicts earlier and for the delay in updating the branch. I should have checked the PR status more closely after the recent upstream changes.
The conflicts with the latest upstream/master have now been resolved in commit c040cef1.
I merged the latest master at 00ecd7fb without rewriting the existing PR history, and resolved the conflicts in:
CubeAPI/Cargo.tomlCubeAPI/Cargo.lockCubeAPI/src/config/mod.rs
The resolution preserves the latest upstream CubeAPI architecture changes while retaining the webhook configuration and delivery dependencies. I also updated the affected test setup from the removed database_url field to the current cube_api_key field, and regenerated Cargo.lock from the merged Cargo.toml on Linux.
Validation against 00ecd7fb completed successfully:
cargo fmt --all -- --checkcargo check --all-targets --lockedcargo test logging::http: 64 passedcargo test config::tests: 5 passedcargo test handlers::sandboxes::tests: 5 passedcargo test: 169 passedcargo clippy --all-targets: exit 0git diff --check -- CubeAPI: exit 0
The final diff relative to the latest master remains limited to 13 files under CubeAPI, with no changes outside that directory.
The branch was updated using a normal push, with no force-push.
Thank you for your patience.
Hello, I've reviewed your PR changes. I think the architecture design is not very reasonable, and adding a webhook feature with 4,300 lines of code seems quite problematic:
- This feature does not require so many code changes.
- There may be some issues in the overall process design.
- There are also responsibility allocation issues in the implementation—almost all the code has been added into one large file.
Although it might work, I don't think this is a good design. Moreover, for a component like the Cube API that needs to support multi-replica deployment, such a design could affect its horizontal scalability.
Hello, thank you for your contribution. After careful consideration, I believe this PR does not yet meet the requirements for merging. However, for the Rhino Bird project, it has already fulfilled the criteria—I’ve logged it accordingly. Therefore, I’ll temporarily close this PR for now. We warmly welcome your continued involvement in CubeSandbox’s community development—let’s build more interesting features together! 🚀