Skip to content
Merged
34 changes: 29 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,40 @@ export PIPEGATE_JWT_SECRET="change-me-to-something-secret"
export PIPEGATE_JWT_ALGORITHMS='["HS256"]'

# Generate a tunnel token (21-day expiry)
python -m pipegate.auth
pipegate token
# Connection-id: a1b2c3d4...
# JWT Bearer: eyJhbGci...

# Run the server (on your public VPS)
python -m pipegate.server
pipegate server

# Run the client (on your local machine, another terminal)
python -m pipegate.client http://localhost:3000 "ws://yourserver:8000/?token=<jwt>"
pipegate client http://localhost:3000 "ws://yourserver:8000/?token=<jwt>"
```

Requests to `http://yourserver:8000/a1b2c3d4/anything` now reach `http://localhost:3000/anything`.

## CLI

```
pipegate token [-c ID] Generate a JWT bearer token
pipegate client TARGET_URL WS_URL Start the tunnel client
pipegate server [--host H] [-p N] Start the server (default: 0.0.0.0:8000)
```

Pin a connection ID so your public URL stays stable across token renewals:

```bash
# via flag (one-off)
pipegate token --connection-id my-app

# via env var (persistent)
export PIPEGATE_CONNECTION_ID=my-app
pipegate token
```

Flag takes precedence over the env var.

## How It Works

A caller hits the server at `/{connection_id}/{path}`. The server wraps the request into a JSON message (method, path, headers, base64-encoded body) tagged with a `correlation_id` (UUID4), and pushes it into an in-memory `asyncio.Queue` for that connection. A background task drains the queue over the WebSocket to the tunnel client.
Expand Down Expand Up @@ -67,10 +88,10 @@ export PIPEGATE_JWT_SECRET="my-secret"
export PIPEGATE_JWT_ALGORITHMS='["HS256"]'

# Generate token
python -m pipegate.auth
pipegate token

# Client connects with the token
python -m pipegate.client http://localhost:3000 "ws://server/?token=<jwt>"
pipegate client http://localhost:3000 "ws://server/?token=<jwt>"
```

External HTTP callers don't need the JWT. They only need the connection ID in the URL path. The server rejects WebSocket connections with missing, expired, or invalid tokens (close code 1008).
Expand All @@ -83,6 +104,9 @@ Environment variables via pydantic-settings:
|---|---|---|---|
| `PIPEGATE_JWT_SECRET` | Yes | -- | Shared secret for JWT signing/verification |
| `PIPEGATE_JWT_ALGORITHMS` | Yes | -- | Algorithm list, e.g. `'["HS256"]'` |
| `PIPEGATE_JWT_ISSUER` | No | `pipegate` | JWT `iss` claim — must match on both sides |
| `PIPEGATE_JWT_AUDIENCE` | No | `pipegate` | JWT `aud` claim — must match on both sides |
| `PIPEGATE_JWT_TTL_DAYS` | No | `21` | Token lifetime in days |
| `PIPEGATE_CONNECTION_ID` | No | random UUID | Pin a specific connection ID when generating tokens |
| `PIPEGATE_MAX_BODY_BYTES` | No | 10 MB | Reject requests larger than this (413) |
| `PIPEGATE_MAX_QUEUE_DEPTH` | No | 100 | Per-tunnel queue size before returning 503 |
Expand Down
56 changes: 31 additions & 25 deletions pipegate/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,47 @@

import uuid
from datetime import UTC, datetime, timedelta
from typing import NamedTuple

import jwt

from .schemas import JWTPayload, Settings


class TokenResult(NamedTuple):
connection_id: str
bearer: str


def generate_token(settings: Settings, connection_id: str | None = None) -> TokenResult:
"""Create a connection ID and signed JWT."""
cid = connection_id or settings.connection_id or uuid.uuid4().hex
now = datetime.now(UTC)
ts = int(now.timestamp())
payload = JWTPayload(
sub=cid,
exp=int((now + timedelta(days=settings.jwt_ttl_days)).timestamp()),
nbf=ts,
iat=ts,
iss=settings.jwt_issuer,
aud=settings.jwt_audience,
jti=uuid.uuid4().hex,
)
token = jwt.encode(
payload.model_dump(mode="json"),
key=settings.jwt_secret.get_secret_value(),
algorithm=settings.jwt_algorithms[0],
)
return TokenResult(connection_id=cid, bearer=token)


def verify_token(token: str, settings: Settings) -> JWTPayload:
"""Decode and verify a JWT, returning the payload (connection ID in ``sub``)."""
"""Decode and verify a JWT, validating all standard claims."""
decoded = jwt.decode(
token,
settings.jwt_secret.get_secret_value(),
algorithms=settings.jwt_algorithms,
audience=settings.jwt_audience,
issuer=settings.jwt_issuer,
)
return JWTPayload.model_validate(decoded)


def make_jwt_bearer() -> None:
"""CLI helper: generate a connection ID and JWT token."""
settings = Settings(_cli_parse_args=True) # #10: only here do we want CLI parsing
connection_id = settings.connection_id or uuid.uuid4().hex

jwt_payload = JWTPayload(
sub=connection_id,
exp=int((datetime.now(UTC) + timedelta(days=21)).timestamp()),
)

jwt_bearer = jwt.encode(
jwt_payload.model_dump(mode="json"),
key=settings.jwt_secret.get_secret_value(),
algorithm=settings.jwt_algorithms[0],
)

print(f"Connection-id: {connection_id}")
print(f"JWT Bearer: {jwt_bearer}")


if __name__ == "__main__":
make_jwt_bearer()
50 changes: 50 additions & 0 deletions pipegate/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from __future__ import annotations

import asyncio

import typer
import uvicorn

from .auth import generate_token
from .client import main as run_client
from .schemas import Settings
from .server import create_app

app = typer.Typer(help="PipeGate — self-hosted HTTP tunnel.")


@app.command("token")
def token_cmd(
connection_id: str | None = typer.Option(
None, "--connection-id", "-c", help="Pin a connection ID (overrides env var)."
),
) -> None:
"""Generate a JWT bearer token for a tunnel connection."""
settings = Settings()
result = generate_token(settings, connection_id)
typer.echo(f"Connection-id: {result.connection_id}")
typer.echo(f"JWT Bearer: {result.bearer}")


@app.command("client")
def client_cmd(
target_url: str = typer.Argument(..., help="Local server to forward requests to."),
server_url: str = typer.Argument(
..., help="PipeGate server WebSocket URL (include ?token=…)"
),
) -> None:
"""Start the tunnel client."""
asyncio.run(run_client(target_url, server_url))


@app.command("server")
def server_cmd(
host: str = typer.Option("0.0.0.0", "--host", help="Host to bind to."),
port: int = typer.Option(8000, "--port", "-p", help="Port to listen on."),
) -> None:
"""Start the PipeGate server."""
uvicorn.run(create_app(), host=host, port=port)


if __name__ == "__main__":
app()
34 changes: 14 additions & 20 deletions pipegate/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,18 @@

import asyncio
import base64
import sys

import httpx
import orjson
import typer
from websockets.asyncio.client import ClientConnection, connect

from .schemas import BufferGateRequest, BufferGateResponse

app = typer.Typer()

_BACKOFF_BASE: float = 1.0
_BACKOFF_MAX: float = 60.0


@app.command()
def start_client(target_url: str, server_url: str) -> None:
"""Start the PipeGate client to expose a local server."""
asyncio.run(main(target_url, server_url))


async def handle_request(
target: str,
request: BufferGateRequest,
Expand All @@ -43,7 +35,10 @@ async def handle_request(
status_code=response.status_code,
)
except Exception as e:
typer.echo(f"Error processing request {request.correlation_id}: {e}", err=True)
print(
f"Error processing request {request.correlation_id}: {e}",
file=sys.stderr,
)
payload = BufferGateResponse(
correlation_id=request.correlation_id,
headers="{}",
Expand All @@ -61,17 +56,20 @@ async def main(target_url: str, server_url: str) -> None:
delay = min(_BACKOFF_BASE * (2**attempt), _BACKOFF_MAX)

if attempt > 0:
typer.echo(f"Reconnecting in {delay:.0f}s (attempt {attempt + 1})...")
print(
f"Reconnecting in {delay:.0f}s (attempt {attempt + 1})...",
file=sys.stderr,
)
await asyncio.sleep(delay)

typer.echo(f"Connecting to {server_url}...")
print(f"Connecting to {server_url}...")

try:
async with (
connect(server_url) as ws_client,
httpx.AsyncClient() as http_client,
):
typer.echo("Connected.")
print("Connected.")
attempt = 0
async with asyncio.TaskGroup() as tg:
while True:
Expand All @@ -86,16 +84,12 @@ async def main(target_url: str, server_url: str) -> None:
except asyncio.CancelledError:
raise
except Exception as e:
typer.echo(f"Error receiving message: {e}", err=True)
print(f"Error receiving message: {e}", file=sys.stderr)
except asyncio.CancelledError:
raise
except (ConnectionRefusedError, OSError) as e:
typer.echo(f"Connection failed: {e}", err=True)
print(f"Connection failed: {e}", file=sys.stderr)
except Exception as e:
typer.echo(f"Unexpected error: {e}", err=True)
print(f"Unexpected error: {e}", file=sys.stderr)

attempt += 1


if __name__ == "__main__":
app()
13 changes: 11 additions & 2 deletions pipegate/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,24 @@ class BufferGateResponse(BaseModel):


class JWTPayload(BaseModel):
sub: str
exp: int
sub: str # connection_id
exp: int # expiry (unix)
nbf: int # not before (unix)
iat: int # issued at (unix)
iss: str # issuer
aud: str # audience
jti: str # unique token id


class Settings(BaseSettings):
model_config = SettingsConfigDict(cli_parse_args=False)

connection_id: str | None = Field(alias="PIPEGATE_CONNECTION_ID", default=None)
jwt_secret: SecretStr = Field(alias="PIPEGATE_JWT_SECRET")
jwt_algorithms: list[str] = Field(alias="PIPEGATE_JWT_ALGORITHMS")
jwt_issuer: str = Field(alias="PIPEGATE_JWT_ISSUER", default="pipegate")
jwt_audience: str = Field(alias="PIPEGATE_JWT_AUDIENCE", default="pipegate")
jwt_ttl_days: int = Field(alias="PIPEGATE_JWT_TTL_DAYS", default=21)
max_body_bytes: int = Field(
alias="PIPEGATE_MAX_BODY_BYTES",
default=10 * 1024 * 1024,
Expand Down
8 changes: 1 addition & 7 deletions pipegate/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from typing import cast, get_args

import orjson
import uvicorn
from fastapi import (
FastAPI,
HTTPException,
Expand Down Expand Up @@ -38,7 +37,7 @@ def create_app() -> FastAPI:

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
app.extra["settings"] = Settings(_cli_parse_args=False)
app.extra["settings"] = Settings()
app.extra["buffers"] = buffers
try:
yield
Expand Down Expand Up @@ -201,8 +200,3 @@ async def send() -> None:
buffers.pop(connection_id, None)

return app


if __name__ == "__main__":
app = create_app()
uvicorn.run(app, host="0.0.0.0", port=8000)
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ dependencies = [
"httpx>=0.27",
]

[project.scripts]
pipegate = "pipegate.cli:app"

[dependency-groups]
dev = [
"pytest>=9.0.3",
Expand Down
17 changes: 14 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

JWT_SECRET = "test-secret-that-is-long-enough-for-hs256!"
JWT_ALGORITHM = "HS256"
JWT_ISSUER = "pipegate"
JWT_AUDIENCE = "pipegate"


@pytest.fixture(autouse=True)
Expand All @@ -25,7 +27,7 @@ def _set_env(monkeypatch: pytest.MonkeyPatch) -> None:

@pytest.fixture
def settings() -> Settings:
return Settings(_cli_parse_args=False)
return Settings()


@pytest.fixture
Expand All @@ -38,19 +40,28 @@ def make_token(
*,
secret: str = JWT_SECRET,
algorithm: str = JWT_ALGORITHM,
issuer: str = JWT_ISSUER,
audience: str = JWT_AUDIENCE,
expires_in: timedelta = timedelta(days=1),
) -> str:
now = datetime.now(UTC)
ts = int(now.timestamp())
payload = {
"sub": connection_id,
"exp": int((datetime.now(UTC) + expires_in).timestamp()),
"exp": int((now + expires_in).timestamp()),
"nbf": ts,
"iat": ts,
"iss": issuer,
"aud": audience,
"jti": uuid.uuid4().hex,
}
return jwt.encode(payload, secret, algorithm=algorithm)


@pytest.fixture
def app() -> FastAPI:
application = create_app()
application.extra["settings"] = Settings(_cli_parse_args=False)
application.extra["settings"] = Settings()
return application


Expand Down
Loading
Loading