How to Run a CI/CD Pipeline That Tests Against a Live Local Environment
Run database integration tests inside GitHub Actions using service containers, and test webhook handlers against your local code using a Localtonet HTTP tunnel. No staging server needed.
In this article 11 sections
Choose the correct trust boundary before connecting a pipeline to a live test service
Integration tests can either build their dependencies inside a CI runner or call an environment maintained outside the runner. These two architectures differ in networking, readiness, security, and cleanup. This guide gives you a self-contained GitHub Actions pattern that uses service containers. It then shows how a controlled job or a webhook provider can reach a developer-managed test application through a Localtonet HTTP tunnel. It also covers tunnel-level access controls, the Host header, HTTP timeouts, request logs, webhook verification, troubleshooting, and cleanup.
📋 What's in this guide
Two architectures with different trust boundaries

The phrase “test against a live local environment” can describe two fundamentally different systems. In the first, the database, cache, application, and tests all run within a GitHub Actions job. In the second, the application remains on a developer-controlled machine and receives requests from a CI runner or an external provider through a public tunnel.
Keep these models separate when designing the pipeline. A self-contained runner is usually the best default for pull requests because it is repeatable and does not depend on a workstation. A tunnel is appropriate when the test specifically requires an internet-originated request, a provider callback, a device outside the local network, or behavior that only exists in a developer-managed environment.
What a hosted runner can and cannot receive
A third-party service normally cannot initiate a connection to an unexposed GitHub-hosted runner. The runner makes outbound connections, while its application ports are not automatically published as stable internet endpoints. It is technically possible to add a separate inbound exposure mechanism, but that is a different architecture and requires a verified installation, authentication, URL-discovery, lifecycle, and security workflow.
This guide does not claim that the Localtonet client can be installed or automated inside GitHub Actions, because no verified command sequence or URL-discovery workflow is presented here for that use case. Instead, the tunnel architecture keeps the Localtonet client on the developer-controlled device and passes the tunnel’s public URL into a deliberately triggered CI job.
| Requirement | Self-contained CI job | Developer-managed tunnel |
|---|---|---|
| Pull request database and API tests | Preferred. The environment is recreated for each job. | Usually unnecessary and introduces workstation availability as a dependency. |
| Internet-originated webhook | Not directly reachable unless a separate inbound mechanism is configured. | Suitable when the provider is configured with the tunnel’s public HTTPS endpoint. |
| OAuth or browser callback | Useful only if the complete callback environment is intentionally exposed. | Suitable when the registered callback URI, application origin, cookies, and proxy behavior are aligned. |
| Test data | Fresh fixtures in an isolated service container or test database. | Dedicated local test database with sanitized fixtures and test accounts. |
| Repeatability | High when dependencies and images are pinned and fixtures are deterministic. | Depends on the developer machine, local state, and whether the client and tunnel are running. The tunnel address itself stays the same across stops and starts until the tunnel is deleted. |
| Cleanup owner | The workflow and runner lifecycle. | The device operator or an independently verified external orchestrator. |
Neither architecture should use production data merely because it is convenient. Use isolated fixtures, synthetic identities, sandbox provider accounts, and sanitized data. A tunnel to an HTTP application port does not provide direct access to a local database, and the application should not expose database administration functions through the public endpoint.
Prerequisites and repository responsibilities
A pipeline file cannot make an application testable by itself. Before adding either workflow, define the commands, health endpoints, credentials, and expected results that belong to the repository. The examples below use conventional names, but your repository must actually implement them.
Requirements for the self-contained GitHub Actions job
- A GitHub repository with Actions enabled.
- A Linux runner with Docker available. GitHub Actions service containers require a Linux runner and Docker.
- A lockfile compatible with
npm ci, such aspackage-lock.json. - An
npm run migratescript that applies the test schema. - An
npm run start:testscript that starts the application without detaching itself unexpectedly. - An
npm run test:integrationscript that exits nonzero when assertions fail. - An application readiness endpoint, represented below as
/health/ready. - Deterministic fixture or seed logic that never imports production records.
- A test reporter configured to write machine-readable results if you want to upload them as artifacts.
Container image tags should identify a deliberate version. A broad tag can change underneath the pipeline. For stronger supply-chain reproducibility, use the image digest approved by your project. GitHub Actions references can also be pinned to reviewed commit SHAs when your security policy requires immutable dependencies.
Localtonet requirements before you create the HTTP tunnel
Our HTTP tunnel documentation lists the following items as things you need before you start. Check them before opening the tunnel form:
- The Localtonet client is installed on the device and connected with an AuthToken. If it is not, follow the Quick start in our documentation first.
- Your web service is running and you know its port, for example
3000. - For a Custom subdomain or Custom domain: Balance on your account.
- For a Custom domain only: a domain that you have added in DNS Manager.
Requirements for the tunneled test environment
- A dedicated local test application and database, not a production application copied onto a workstation.
- A device-specific AuthToken that is never exposed in logs, screenshots, workflow inputs, or source control.
- A protected readiness route and test API, or a provider-signed webhook route.
- A test account or sandbox account for the external provider.
- An operator responsible for starting the environment, monitoring it, and stopping or deleting the tunnel afterward.
Prepare the device before creating the tunnel
These preparation tasks happen on the developer-controlled device before the documented tunnel steps. Doing them first means that any later failure points at the tunnel or the caller, not at an application that never started.
- Install and connect the Localtonet client. Install the current Localtonet application for the device’s operating system, connect it with the device’s AuthToken, and keep it connected for the entire test window. Take installation details from the Localtonet downloads and Quick start pages rather than from unverified commands.
- Start the test application and verify it locally. Start the dedicated test application, its database, and required dependencies. Seed only synthetic or sanitized fixtures. From the same device as the Localtonet client, request the readiness route using the exact local IP address and port you plan to enter in the tunnel form.
When job steps run directly on the Linux runner, publish a service port and connect through localhost. When the job itself runs in a container, service containers share a Docker network and are reached by their service label, such as postgres:5432. Host port mapping is not required for communication between those job and service containers.
Architecture A: build a complete integration-test job

The following Node.js workflow creates an isolated PostgreSQL service, installs locked dependencies, applies migrations, starts the application, waits for application-level readiness, runs integration tests, collects artifacts, and terminates the application during cleanup. It also prevents overlapping runs for the same workflow and branch or pull request.
name: Integration Tests
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
permissions:
contents: read
concurrency:
group: integration-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
integration:
runs-on: ubuntu-latest
timeout-minutes: 20
services:
postgres:
image: postgres:16.4-alpine
env:
POSTGRES_USER: testuser
POSTGRES_PASSWORD: testpassword
POSTGRES_DB: testdb
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
NODE_ENV: test
DATABASE_URL: postgresql://testuser:testpassword@localhost:5432/testdb
TEST_BASE_URL: http://127.0.0.1:3000
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: npm
- name: Install locked dependencies
run: npm ci
- name: Apply test database migrations
run: npm run migrate
- name: Start test application
shell: bash
run: |
npm run start:test > application.log 2>&1 &
echo $! > application.pid
- name: Wait for application readiness
shell: bash
run: |
for attempt in {1..60}; do
if curl --silent --show-error --fail \
--max-time 2 \
"$TEST_BASE_URL/health/ready"; then
exit 0
fi
sleep 2
done
echo "Application did not become ready within 120 seconds."
cat application.log || true
exit 1
- name: Run integration assertions
run: npm run test:integration
- name: Upload logs and test results
if: always()
uses: actions/upload-artifact@v4
with:
name: integration-results
path: |
application.log
test-results/
if-no-files-found: warn
retention-days: 7
- name: Stop test application
if: always()
shell: bash
run: |
if [ -f application.pid ]; then
kill "$(cat application.pid)" 2>/dev/null || true
fi
Why both container health and application readiness matter
The PostgreSQL health command reports the health status of the database container. It reduces startup races, but it does not prove that your application has connected successfully, that migrations completed, or that the API can serve a real request. The separate readiness loop tests the application after migrations and startup.
A readiness route should check only the dependencies required for the test and return promptly. Do not place secrets, database contents, stack traces, or administrative controls in its response. If the route is included in production builds, restrict the information it reveals.
Credentials and fixtures
The PostgreSQL credentials in this example exist only inside the disposable CI job. They are not suitable for a shared or production database. If a test requires a third-party sandbox credential, store it as a GitHub Actions secret and expose it only to the step that needs it. Be especially careful with workflows triggered from forks because repository secrets are intentionally restricted in many forked pull-request contexts.
Run migrations before seeding fixtures, give each test an independent record namespace, and clean state between tests. Common application-level strategies include transaction rollback, a schema per suite, or a database per worker. The service container gives isolation between jobs, but tests within one job can still conflict when they share records or run concurrently.
Python variation with PostgreSQL and Redis
The same architecture works for Python when the repository defines its dependency and test commands. The following service configuration is valid for a Linux job whose steps run directly on the runner. The tests connect through mapped localhost ports.
jobs:
python-integration:
runs-on: ubuntu-latest
timeout-minutes: 20
services:
postgres:
image: postgres:16.4-alpine
env:
POSTGRES_USER: testuser
POSTGRES_PASSWORD: testpassword
POSTGRES_DB: testdb
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 12
redis:
image: redis:7.2-alpine
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
DATABASE_URL: postgresql://testuser:testpassword@localhost:5432/testdb
REDIS_URL: redis://localhost:6379
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: pip
- name: Install dependencies
run: pip install -r requirements.txt
- name: Apply migrations
run: python manage.py migrate
- name: Run integration tests
run: pytest tests/integration/ -v --junitxml=test-results/pytest.xml
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: python-integration-results
path: test-results/
if-no-files-found: warn
retention-days: 7
Replace python manage.py migrate with the migration command implemented by your project. If these tests also need a running HTTP process, start it, perform a bounded application-readiness check, capture its logs, and stop it using the same lifecycle shown in the Node.js job.
Architecture B: expose the local test application with Localtonet

With Localtonet, the client application on your device establishes an outbound connection to our relay. An HTTP tunnel then gives the web app, API, or webhook receiver on your device a public HTTPS address that forwards to the configured local IP address and port. No inbound router port forwarding, public IP address, VPN setup, or inbound firewall change is required for this workflow.
The public endpoint works only while the selected client or device is connected and the tunnel is running. Creating a tunnel does not start it. The operator must start it from the tunnel list, verify it, and later stop or delete it.
Choose a URL type for the test
The HTTP tunnel form offers three URL types. For most CI and webhook tests, a random subdomain is enough because it needs nothing extra and, as explained below, keeps its name until you delete the tunnel.
| URL type | Address you get | Needs |
|---|---|---|
| Random subdomain | A generated name on the selected domain, for example https://<RANDOM_NAME>.localto.net. |
Nothing extra. |
| Custom subdomain | The name you type in Subdomain, for example https://myapp.localto.net. Letters, digits, and hyphens are allowed. |
Balance on your account. |
| Custom domain | A domain of your own, selected in Domain. | Balance and a domain added in DNS Manager. |
Create and start the HTTP tunnel
The following five steps mirror the documented sequence in the Localtonet HTTP tunnel documentation. Complete the preparation tasks from the prerequisites section first.
Open the HTTP page
Open My Tunnels > HTTP and select Create HTTP Tunnel to open the form.
Choose the URL type
Select Random subdomain (for example https://<RANDOM_NAME>.localto.net, needs nothing extra), Custom subdomain (letters, digits, and hyphens, needs Balance), or Custom domain (needs Balance and a domain added in DNS Manager).
Choose the device and the region
In Device token, select the token used by the Localtonet app on the device that runs your test application. In Server region, choose a region close to that device for lower latency. AuthTokens are device-specific secrets and must never appear in repository files, workflow inputs, logs, or screenshots.
Enter the local address
Fill in Domain (localto.net or one of your own domains; for Custom domain the list only contains your own domains), Subdomain (only for Custom subdomain), Local IP address (use 127.0.0.1 for this device; the form accepts an IPv4 or IPv6 address or localhost), and Local port (the port your service listens on, from 1 to 65535). Then select Create tunnel. The tunnel appears under Your tunnels as Tunnel # followed by its ID.
Start the tunnel
Select the start button in the Actions column. When the tunnel runs, its address in the URL column becomes a link, and requests to that address reach the service on your device. If the Localtonet app of that token is offline, a dialog tells you so. Start the app, or select Start anyway and the tunnel goes live when the app connects.
Use 127.0.0.1 only when the application listens on the same device and network namespace as the Localtonet client. A containerized service or a service on another LAN host may need a different reachable address. Public endpoint verification is covered in the verification section; do not start a paid-provider or state-changing test until that check succeeds.
Your public address and how it behaves
The public address is https:// followed by the host name shown in the URL column. Several documented properties matter for CI and webhook testing:
- The subdomain is kept until you delete the tunnel. Stopping and starting a tunnel does not change its address. This lets you register one webhook URL with a provider, or store one base URL in CI, and reuse it across test sessions.
- The address has no port number. Callers open it like any other website, which avoids provider restrictions on non-standard ports.
- WebSocket connections pass through an HTTP tunnel. Tests that rely on WebSocket upgrades can use the same address.
- TLS ends at the Localtonet server. Visitors reach the tunnel over HTTPS with a certificate that Localtonet provides and renews. The request then travels through the tunnel to your device, and the Localtonet app passes it to your service, so the local test service can stay on plain HTTP.
HTTPS and connection settings
Select the settings button in the Actions column to open the Tunnel settings panel. Under Tunnel Details you can rename the tunnel and change its local IP address and local port. The connection switches live under Settings in the same panel.
| Setting | What it does | Recommendation for CI and webhook tests |
|---|---|---|
| Is Only Https? | Serves the public URL over HTTPS only. A request to http:// is redirected to the same address on https://. While it is off, the address answers on both. |
Turn it on. Test tokens, signatures, and cookies should never travel over plain HTTP. |
| Is HTTP/3 Active? | Lets clients reach the public URL over HTTP/3. A new tunnel has it turned on. | Leave it on unless a specific client or test tool has trouble with HTTP/3. |
| Is SslStream? | Tells the Localtonet app to connect to your local service with TLS. The app accepts the local service’s certificate as it is, so a self-signed certificate works. | Turn it on when the local service itself uses HTTPS, for example a dev server on https://localhost:5001. |
| Legacy Connect? | Connects the tunnel with the legacy method instead of the normal one. | Try it if the tunnel cannot connect with the normal method. |
Changing Is SslStream? or Legacy Connect? on a running tunnel restarts it, so the Localtonet app must be connected. Do not change these switches while a CI job or webhook test is in flight. If your service must present its own certificate end to end, an HTTP tunnel is the wrong type because Localtonet decrypts HTTP tunnel traffic at its server; use a TLS tunnel instead.
The Host header
Your service receives the host name the caller used, which is the tunnel address. Some local web servers and frameworks pick the site by host name and answer with the wrong site or an error when they see an unfamiliar host. In that case, open Headers in the tunnel settings and add a request header named Host with the name your server expects. Your service then receives that host name instead of the tunnel address. The origin and allowed-hosts guidance below explains when to rewrite the header and when to add the tunnel host to the application’s allowed list instead.
HTTP Timeout for slow handlers
HTTP Timeout sets how long our server waits for a response from your local application, from 1 to 600 seconds. Relate it to the other timeouts in the test path. A webhook provider has its own delivery timeout, and the CI job has curl --max-time values and a timeout-minutes limit. If a test handler genuinely needs longer than the tunnel waits, the caller sees a failure even though the application eventually finishes. Prefer fast acknowledgement with bounded background work for webhooks, and raise the tunnel timeout only to cover the slowest legitimate response you expect from a test route.
Our HTTP tunnel documentation includes a section titled “The warning page on the Free plan”. On the Free plan an interstitial warning page may be shown to visitors of the tunnel address. Automated callers such as webhook providers and CI readiness checks cannot click through an interstitial, so a page like this could cause unexpected HTML responses or failed assertions. Check the HTTP tunnel documentation for the current behavior and how it affects automated callers before relying on a Free plan tunnel for provider or CI traffic.
Anyone who obtains the public URL can attempt to connect while the client and tunnel are running. Because the subdomain persists until the tunnel is deleted, a URL that leaked in an old log stays valid for as long as you keep that tunnel. Protect test APIs with authorization, expose only the required routes, apply least privilege, avoid production data, validate provider signatures, and keep the running window short. A hard-to-guess URL is not a substitute for authentication.
Run a controlled CI job against the tunnel URL
The evidence available for this guide does not establish a documented Localtonet mechanism for automatically discovering a tunnel URL inside GitHub Actions, or a verified workflow for installing and automating the Localtonet client in a hosted runner. We therefore do not pretend that tunnel creation and URL handoff are automatic.
What makes the handoff manageable is that an HTTP tunnel keeps its subdomain until it is deleted. Once you have created the tunnel, its address does not change when you stop and start it. A safe, supportable pattern is to start and verify the tunnel on the developer-controlled device, then invoke a restricted workflow_dispatch job with the public base URL. The job receives the URL explicitly, waits for the local application to become ready, authenticates to a dedicated test API, runs assertions, uploads results, and times out if the workstation disappears.
name: Controlled Local Environment Test
on:
workflow_dispatch:
inputs:
public_base_url:
description: Verified temporary HTTPS base URL
required: true
type: string
permissions:
contents: read
concurrency:
group: controlled-local-integration
cancel-in-progress: false
jobs:
test-local-environment:
runs-on: ubuntu-latest
timeout-minutes: 15
environment: local-integration
env:
TEST_BASE_URL: ${{ inputs.public_base_url }}
TEST_API_TOKEN: ${{ secrets.LOCAL_TEST_API_TOKEN }}
steps:
- name: Validate input scheme
shell: bash
run: |
case "$TEST_BASE_URL" in
https://*) ;;
*)
echo "The test URL must use HTTPS."
exit 1
;;
esac
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: npm
- name: Install locked dependencies
run: npm ci
- name: Wait for remote application readiness
shell: bash
run: |
for attempt in {1..30}; do
if curl --silent --show-error --fail \
--max-time 5 \
--header "Authorization: Bearer $TEST_API_TOKEN" \
"$TEST_BASE_URL/test/ready" \
> readiness-response.txt; then
exit 0
fi
sleep 5
done
echo "The local environment did not become ready within 150 seconds."
exit 1
- name: Run remote integration assertions
env:
BASE_URL: ${{ inputs.public_base_url }}
API_TOKEN: ${{ secrets.LOCAL_TEST_API_TOKEN }}
run: npm run test:remote-integration
- name: Upload results
if: always()
uses: actions/upload-artifact@v4
with:
name: controlled-local-test-results
path: |
readiness-response.txt
test-results/
if-no-files-found: warn
retention-days: 7
This workflow assumes the repository implements test:remote-integration and writes reports to test-results/. Tests should use BASE_URL as their origin and send API_TOKEN only to the dedicated test application. Never print the token or include it in the URL.
Store a stable tunnel URL as a workflow variable
Because the subdomain persists until the tunnel is deleted, you do not have to type the URL into every dispatch. You can store it once as a repository or organization variable, or as a variable on the local-integration GitHub environment, and fall back to it when no input is supplied. Make the input optional and change the job environment as shown below, and use $TEST_BASE_URL instead of inputs.public_base_url in the assertion step.
on:
workflow_dispatch:
inputs:
public_base_url:
description: Optional override for the stored tunnel URL
required: false
type: string
jobs:
test-local-environment:
runs-on: ubuntu-latest
timeout-minutes: 15
environment: local-integration
env:
TEST_BASE_URL: ${{ inputs.public_base_url || vars.LOCAL_TEST_BASE_URL }}
TEST_API_TOKEN: ${{ secrets.LOCAL_TEST_API_TOKEN }}
A stored URL is a convenience, not a readiness guarantee. The address only reaches your application while the client is connected and the tunnel is running, so keep the bounded readiness step and verify that the tunnel is running before each test. Update the variable if you delete the tunnel and create a new one, because a newly created random subdomain receives a new name.
Configure the local-integration GitHub environment with appropriate reviewers if manual approval is required. Restrict who can dispatch the workflow because an arbitrary URL supplied to a privileged runner can create a server-side request forgery risk. A stored variable reduces that risk compared with free-form input, which is another reason to prefer it once the tunnel is stable. If your organization needs unattended tunnel creation, URL discovery, or teardown, implement it only from current documented Localtonet API behavior and have that automation reviewed separately.
What about starting a tunnel from the runner?
The tunnel settings panel includes a Show SSH Command option, which starts the tunnel with plain SSH, without installing the Localtonet app. That capability could be relevant if you ever consider opening a tunnel from inside a CI runner. Its details are covered in our Zero-install SSH documentation, which you should read before designing anything around it. This guide does not present a verified in-runner automation workflow, and the examples here keep the tunnel on the developer-controlled device.
Design assertions around observable outcomes
A remote test should do more than receive HTTP 200. Create a unique run identifier, submit a test request, poll a protected status route for a bounded period, and verify the expected state transition. Make retries safe by using an idempotency key or the unique run identifier. Capture response status, sanitized response bodies, correlation IDs, and application logs without recording credentials or personal data. Keep each test route’s expected response time well inside the tunnel’s HTTP Timeout and the job’s --max-time values.
Test webhook delivery without weakening verification

A webhook tunnel changes how the provider reaches your application, but it should not change the provider’s security model. Use the provider’s test or sandbox mode, store the endpoint signing secret outside source control, preserve the exact request body required by the signature algorithm, compare signatures safely, reject stale or invalid messages when the provider’s protocol supports timestamp validation, and make event processing idempotent.
Provider dashboard labels and test-event controls can change. Use the provider’s current first-party documentation and interface to create the endpoint, choose event types, obtain or rotate the signing secret, send a test delivery, and inspect delivery attempts. Do not rely on an old menu path copied from a tutorial.
Since the tunnel’s subdomain survives stops and starts, you can register the webhook endpoint with the provider once and keep it for later sessions, as long as you keep the same tunnel. Deliveries sent while the tunnel is stopped will fail on the provider side and may be retried according to the provider’s own policy, so start the tunnel before triggering test events.
Stripe webhook handler using the raw request body
const express = require('express');
const Stripe = require('stripe');
const app = express();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
// Register this route before any JSON body parser that would modify the body.
app.post(
'/webhooks/stripe',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signature = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (error) {
return res.status(400).send('Invalid webhook signature');
}
try {
// hasProcessedEvent and recordProcessedEvent must use durable,
// atomic storage keyed by the provider event ID.
if (await hasProcessedEvent(event.id)) {
return res.status(200).json({ received: true, duplicate: true });
}
if (event.type === 'payment_intent.succeeded') {
const paymentIntent = event.data.object;
await processTestPayment(paymentIntent);
}
await recordProcessedEvent(event.id);
return res.status(200).json({ received: true });
} catch (error) {
console.error('Webhook processing failed', {
eventId: event.id,
eventType: event.type
});
return res.sendStatus(500);
}
}
);
The signing secret belongs in the local environment’s secret store, not in code or a pipeline input. Use the signing secret associated with the exact test endpoint. Rotate it if it is exposed. Stripe can retry deliveries, and delivery can occur more than once, so the event ID must be recorded atomically before a duplicate can repeat a state-changing operation.
Webhook endpoints should respond within the provider’s required time window. For production designs, lengthy processing is commonly handed to a durable queue after signature verification and idempotent acceptance. For a local test, keep processing bounded, make sure the tunnel’s HTTP Timeout is not shorter than your handler’s realistic response time, and inspect the provider’s delivery log alongside local application logs.
GitHub webhook handler with safe payload access
from flask import Flask, request, abort
import hashlib
import hmac
import json
import os
app = Flask(__name__)
@app.post('/webhooks/github')
def github_webhook():
body = request.get_data(cache=True)
supplied_signature = request.headers.get('X-Hub-Signature-256', '')
delivery_id = request.headers.get('X-GitHub-Delivery', '')
event_name = request.headers.get('X-GitHub-Event', '')
secret = os.environ['GITHUB_WEBHOOK_SECRET'].encode('utf-8')
digest = hmac.new(secret, body, hashlib.sha256).hexdigest()
expected_signature = f'sha256={digest}'
if not hmac.compare_digest(supplied_signature, expected_signature):
abort(401)
if not delivery_id:
abort(400)
if delivery_already_processed(delivery_id):
return '', 200
payload = json.loads(body.decode('utf-8'))
if event_name == 'push':
ref = payload.get('ref')
head_commit = payload.get('head_commit')
commit_message = (
head_commit.get('message')
if isinstance(head_commit, dict)
else None
)
process_test_push(
delivery_id=delivery_id,
ref=ref,
commit_message=commit_message
)
record_processed_delivery(delivery_id)
return '', 200
The example reads the exact request bytes before parsing JSON, verifies X-Hub-Signature-256, uses a constant-time comparison, and does not assume that head_commit is always present. Implement delivery_already_processed and record_processed_delivery with durable, atomic storage. GitHub can redeliver events, so processing must tolerate duplicates.
Create the webhook in a test repository or another deliberately limited context. Configure only the events required by the test, use a unique random secret, and enter the tunnel’s public URL plus the handler path as the payload URL. After triggering a test event, compare the provider delivery ID, HTTP status, request timestamp, local log correlation ID, and resulting test record.
A CI job can authenticate to a protected test API with a dedicated bearer token. A webhook provider generally will not send that custom bearer token, so the webhook route must use the provider’s documented signature scheme. Do not disable webhook signature verification merely because the endpoint is temporary.
Verify locally, publicly, and end to end
Test each network segment independently. This avoids blaming the tunnel when the application is not listening, or blaming the application when the provider is still configured with an old URL. The tunnel’s own logs sit between the caller and your application, which makes them the fastest way to tell which side of the boundary failed.
Verify the local process
From the Localtonet client device, request the exact local target and readiness path. Confirm the process is listening on the expected interface and port, the database is reachable, migrations are complete, and the response contains no sensitive diagnostics.
Verify the public HTTPS endpoint before starting CI
Confirm the tunnel is running and its URL column shows a link. Request the public readiness endpoint from a network path outside the local application process. Check the HTTPS status code, expected body, authentication rejection for unauthorized requests, HTTP to HTTPS redirect when Is Only Https? is on, and the matching application log entry. Do not begin a paid-provider or state-changing test until this check succeeds.
Inspect the tunnel’s logs and health
Open the tunnel’s Request Log to inspect requests that reached the tunnel, the Activity Log to review starts, stops, and setting changes, and Tunnel Health to see the health checks. If a request appears in the Request Log but not in your application log, investigate the local target, Host header, or application routing. If it never appears, investigate the caller, the URL, or the tunnel state.
Verify CI-to-local connectivity
Run the bounded readiness step before state-changing tests. If it fails, retain the CI response, timestamps, and local application logs, and compare them with the Request Log. Confirm that the runner can make outbound HTTPS requests through any organizational proxy or egress policy.
Verify the business outcome
Send a uniquely identified test request, then assert the resulting test-only record, state transition, callback, or queued operation. A successful transport response alone does not prove that the integration worked.
Verify provider delivery details
For webhooks, inspect the provider’s current delivery log. Match its delivery or event ID to the tunnel’s Request Log and the local application record, verify the returned status, and distinguish an initial delivery from a retry or manual redelivery.
The documentation describes what these three views are for but this guide does not enumerate the exact fields they display. Use them to establish whether a request arrived and when, and rely on your application’s own structured logs for request-level detail.
Security and operational controls
A public tunnel shifts an application from loopback-only access to internet-reachable access for as long as the tunnel runs. Treat that as a temporary deployment, even when the code runs on a laptop.
Tunnel-level access controls
The HTTP tunnel settings include controls that narrow who can reach the tunnel and for how long. Their full configuration is described in our Access control, Single Sign-On, Web Application Firewall, and Limits and expiration documentation pages. The table relates each control to CI and webhook testing.
| Control | What it does | CI and webhook considerations |
|---|---|---|
| Basic Authentication? | Asks visitors for a username and password. | A good fit for CI-only test APIs, where the job can send the credentials. Many webhook providers cannot send Basic Authentication credentials, so do not enable it on a tunnel that must accept provider deliveries unless your provider supports it. Basic Authentication and a bearer token both normally use the HTTP Authorization header, so check the documented behavior before combining the two. |
| IP Restriction | Controls which client IP addresses can access the tunnel. | Useful for limiting a test API to known callers. Provider delivery ranges and hosted-runner IP ranges change over time, so an allowlist can silently go stale and block legitimate traffic. For webhooks, prefer signature verification over IP allowlists. |
| SSO Providers | Visitors sign in with one of your identity providers before they can open the tunnel. The SSO button at the top of the page manages the providers. | Suited to human reviewers opening a test environment in a browser. Automated callers such as CI jobs and webhook providers generally cannot complete an interactive sign-in. |
| WAF button in the Actions column | Opens WAF Setting. The button shows whether the Web Application Firewall is not configured, active, or inactive. | Adds a filtering layer in front of the test application. Verify that legitimate test and provider requests still pass after enabling it. |
| Expiration Date | Stops the tunnel on a date. | A good safeguard against forgotten tunnels. Set it to shortly after the planned test window. |
| Speed Limits and Bandwidth Limit | Cap the tunnel’s speed and its data. Related views reset the data counter and show traffic over time. | Bound what an exposed test environment can transfer if the URL leaks. Leave enough headroom for the expected test traffic. |
These controls reduce exposure at the tunnel, but authentication of test API callers and verification of webhook signatures remain the application’s responsibility. They also do not turn an HTTP tunnel into a VPN. The tunnel still publishes one HTTP service at a public address.
Origin, host, and HTTPS behavior
The browser or provider sees the public HTTPS origin, while the Localtonet client forwards to a local IP address and port that may use plain HTTP. Applications that generate absolute URLs, enforce allowed hosts, validate callback origins, use secure cookies, or trust forwarded proxy information must be configured for the externally visible origin.
By default your service receives the tunnel address as the Host header. If the framework rejects unknown hosts, add the tunnel host name to its allowed-hosts configuration for the test environment. If the local web server selects a site or virtual host by name, add a Host request header under Headers in the tunnel settings so the server receives the name it expects. Rewriting the Host header changes what the application sees, so check that absolute URL generation and callback validation still use the public origin.
Do not globally disable host validation or TLS-origin checks to make a test pass. Configure the exact test origin using the mechanism supported by the installed framework version. For OAuth, the provider’s registered callback URI must match the public scheme, host, and callback path expected by the application. Because the tunnel address has no port number and keeps its subdomain until the tunnel is deleted, a registered callback URI stays valid across stops and starts of the same tunnel.
Troubleshooting failed pipeline and tunnel tests
Start every investigation by checking the tunnel’s Request Log. A request that reached the tunnel points you toward the local target or application. A request that never arrived points you toward the caller, the URL, or the tunnel state.
| Symptom | Likely boundary | What to check |
|---|---|---|
| Connection refused locally | Application process | Confirm the process is running, the port is correct, startup did not fail, and the service listens on an address reachable by the Localtonet client. |
| Local URL works but public URL fails | Tunnel configuration | Confirm the app for the selected Device token is connected, the tunnel was started after creation, and the Local IP address and Local port match the verified target. Use the Activity Log and Tunnel Health to check recent starts, stops, setting changes, and health checks. |
| The tunnel cannot connect | Client connection | Confirm the Localtonet app is running and connected. If the normal method fails, try Legacy Connect?. Changing it restarts the tunnel, so the app must be connected. |
| Local service uses HTTPS and public requests fail | Client to service TLS | Turn on Is SslStream? so the Localtonet app connects to the local service with TLS. A self-signed local certificate is accepted. |
| Public URL returns an application 404 or the wrong site | Route or host handling | Check the full path, base-path configuration, and allowed-host settings. If the local server picks sites by host name, add a Host request header under Headers in the tunnel settings with the name the server expects. |
| Automated callers receive an unexpected HTML page | Free plan warning page | On the Free plan an interstitial warning page may be shown. Check the HTTP tunnel documentation section “The warning page on the Free plan” for current behavior and how it affects webhook providers and CI requests. |
| Slow handler requests fail although the application finishes | Timeouts | Compare the handler’s duration with the tunnel’s HTTP Timeout (1 to 600 seconds), the provider’s delivery timeout, and the CI --max-time value. Acknowledge webhooks quickly and move long work out of the request. |
| CI cannot reach a public URL that works in a browser | Runner egress or access controls | Check organizational proxies, DNS resolution, outbound firewall rules, URL input or variable errors, tunnel state, and the workflow timeout. If IP Restriction, Basic Authentication, or SSO is enabled, confirm the runner can satisfy it. |
| Webhook never arrives | Provider or access controls | Check whether the request appears in the Request Log. If not, confirm the registered URL, that the tunnel was running at delivery time, and that IP Restriction or Basic Authentication is not rejecting the provider. |
| Webhook signature fails | Request verification | Preserve the raw body, use the signing secret for the exact endpoint and mode, read the correct signature header, and verify that middleware did not parse or alter the body first. |
| Webhook is processed twice | Application idempotency | Use the provider event or delivery ID as an atomic idempotency key. Account for retries, delayed delivery, and manual redelivery. |
| Database container is healthy but tests fail at startup | Application readiness | Inspect migrations, fixture loading, application logs, database permissions, and the application readiness endpoint. Container health is not application readiness. |
| Tests intermittently time out | Readiness or shared state | Add bounded polling, avoid fixed sleeps, isolate records, prevent concurrent runs, record timing data, and fail with retained diagnostics. |
| OAuth redirects to localhost or loses its session | External-origin configuration | Align the registered callback URI, application base URL, proxy trust, secure-cookie behavior, callback path, and public HTTPS host. |
| A previously used public URL no longer works | Tunnel lifecycle | An HTTP tunnel keeps its subdomain until the tunnel is deleted, and stopping and starting does not change it. If the URL stopped working, first confirm the client is connected and the tunnel is running. The address changes only if the tunnel was deleted and recreated; in that case, update the stored CI variable and the provider’s registered endpoint. Verify the tunnel is running before each test either way. |
| The developer machine becomes unavailable | External environment | Let the CI job fail within its timeout, preserve artifacts, mark the run as an environment failure, and rerun only after the device, application, and tunnel are verified again. |
Container binding mistakes
If the application runs inside Docker on the developer machine, a process bound only to the container’s loopback interface may not be reachable from the host. Publish the application port according to the project’s container configuration and verify it from the host before targeting it with Localtonet. Do not guess a container IP that can change between starts.
Failure artifacts that are worth retaining
Capture application startup logs, migration output, sanitized HTTP status and response data, test reports, correlation IDs, provider delivery IDs, and timestamps that let you match entries in the tunnel’s Request Log. Keep artifact retention proportionate to the test and avoid collecting complete webhook bodies when they contain personal or payment-related data. Never upload environment dumps or authorization headers as debugging artifacts.
Complete the test with explicit cleanup
Cleanup is part of the pipeline design, not an optional task after a successful run. The self-contained GitHub Actions environment is discarded after the job, while its explicit if: always() steps preserve diagnostics and stop the application process even when assertions fail.
In the developer-managed architecture, the CI runner does not own the Localtonet tunnel. The device operator must perform cleanup after success, failure, cancellation, or timeout. Decide up front whether you are stopping the tunnel for reuse or deleting it. Stopping keeps the subdomain, so stored CI variables and provider endpoints keep working next time. Deleting releases the address, so a recreated tunnel needs new registrations. Setting an Expiration Date on the tunnel protects you if this step is forgotten.
Record the final result
Preserve the CI conclusion, test report, provider delivery ID, and sanitized local logs needed to diagnose a failure. Do not retain secrets or unnecessary payload data.
Remove or pause temporary provider configuration
Delete or disable the test webhook endpoint or callback registration when it is no longer required. If you plan to reuse the same tunnel, disabling may be enough. Rotate the signing secret if it was exposed during debugging.
Stop or delete the Localtonet tunnel
Stop the running tunnel immediately after the test. Delete the tunnel as well when you no longer need its address, and update or remove the stored CI variable. Verify that the public endpoint no longer reaches the application.
Stop the local environment and clear fixtures
Stop the test application and dependencies, revoke temporary test tokens, and remove or reset test records. Preserve only the sanitized evidence required by your development process.
Frequently asked questions
Can every Docker image be used as a GitHub Actions service container?
No. Service containers require a Linux runner with Docker, and the image must operate correctly in the service-container environment. You must supply any required environment variables, ports, volumes, startup options, and health command. Licensing, architecture compatibility, authentication, resource requirements, and image entrypoint behavior can also affect whether an image is suitable.
Does a service-container health check prove my application is ready?
No. It reports the container health defined by that command. A database can accept basic connections while migrations, fixtures, application startup, or another dependency still fails. Add a separate bounded application-level readiness check before running assertions.
Can GitHub Actions automatically discover my Localtonet tunnel URL?
No verified automatic URL-discovery workflow is presented in this article. Because an HTTP tunnel keeps its subdomain until the tunnel is deleted, you can copy the URL once from the URL column and store it as a workflow or GitHub environment variable, or pass it to a restricted manually dispatched job. Do not build automation around guessed commands or undocumented output formats.
Can I assume the same public tunnel URL will be available next time?
Yes, as long as you keep the same tunnel. An HTTP tunnel keeps its subdomain until you delete it, and stopping and starting does not change the address. If you delete the tunnel and create a new one, a random subdomain receives a new name. The address only reaches your application while the client is connected and the tunnel is running, so verify the tunnel is running before each test.
Does my local test service need its own HTTPS certificate?
No. TLS ends at the Localtonet server, and Localtonet provides and renews the public certificate, so the local service can stay on plain HTTP. If your local service already uses HTTPS, for example on https://localhost:5001, turn on Is SslStream?, which accepts self-signed certificates. If the service must present its own certificate to callers end to end, use a TLS tunnel instead of an HTTP tunnel.
Will webhook providers work with a Free plan tunnel?
Our HTTP tunnel documentation has a section on the warning page shown on the Free plan. An interstitial page may affect automated callers such as webhook providers and CI readiness checks, which cannot click through it. Check the current documentation for the exact behavior before relying on a Free plan tunnel for automated traffic.
Should a tunneled test use my local copy of production data?
No. Use a dedicated test database with synthetic or sanitized fixtures. Remove production credentials and integrations from the process before publishing it. The tunnel exposes the selected HTTP service while it is running, so the application must not provide routes that reveal production records or administrative capabilities.
Should I use an IP allowlist to protect a webhook endpoint?
IP Restriction is available on HTTP tunnels, but provider delivery ranges and CI runner ranges change, and a stale allowlist silently blocks legitimate deliveries. Prefer verifying the provider’s webhook signature in the application. Use IP Restriction as an additional layer only when you can keep the ranges current.
Why does a webhook need idempotency if the signature is valid?
A valid signature authenticates the delivery but does not guarantee it will arrive only once. Providers can retry after timeouts or server errors, and operators can initiate redelivery. Record the provider’s event or delivery ID atomically so a repeated request returns success without repeating the state-changing operation.
Which architecture should run on every pull request?
Prefer the self-contained runner for routine pull-request tests because it is reproducible and does not depend on a developer machine. Reserve the tunneled architecture for controlled tests that genuinely require an external callback or a developer-managed environment. Keep those runs manually approved or externally orchestrated until every lifecycle step is documented and reviewed.
Open a controlled path to your local test application
When an integration genuinely requires an internet-originated callback, use Localtonet to publish only the required local HTTP service at a stable HTTPS address, protect it with access controls and an expiration date, confirm deliveries in the Request Log, run a bounded test with isolated data, and stop the tunnel as soon as the test finishes.
Get Started Free →Corrections & updates
Substantive changes approved by the Localtonet editorial team are listed transparently below.
Localtonet is a secure multi-protocol tunneling and proxy platform designed to expose localhost, devices, private services, and AI agents to the public internet supporting HTTP/HTTPS tunnels, TCP/UDP forwarding, mobile proxy infrastructure, file server publishing, latency-optimized game connectivity, and developer-ready AI agent endpoint exposure from a single unified control plane.