Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): require an ADMIN key to set a session proxy

Yudhi Armyndharis7da8e11ae798
diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.ts
index 694cc5717..6bb1b73f3 100644
--- a/dashboard/src/pages/Sessions.test.ts
+++ b/dashboard/src/pages/Sessions.test.ts
@@ -484,6 +484,33 @@ test('saving proxy settings issues PATCH /api/sessions/:id/proxy', async () => {
});
});
+// The API accepts a session proxy only from an ADMIN key, so an operator is not offered the controls.
+test('an operator key is not offered proxy writes, in the create modal or the proxy modal', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ window.sessionStorage.setItem('openwa_user_role', 'operator');
+ try {
+ renderSessions();
+ await screen.findByText('new-device');
+
+ fireEvent.click(screen.getByRole('button', { name: 'New Session' }));
+ const createDialog = await screen.findByRole('dialog');
+ assert.equal(createDialog.querySelector('#create-use-proxy'), null);
+ fireEvent.click(within(createDialog).getByRole('button', { name: 'Cancel' }));
+ await waitFor(() => assert.equal(screen.queryByRole('dialog'), null));
+
+ const qrCard = screen.getByText('new-device').closest('.session-card') as HTMLElement;
+ fireEvent.click(within(qrCard).getByRole('button', { name: 'Proxy' }));
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => assert.ok(findFetchCall('GET', '/api/sessions/sess-qr-1/proxy')));
+ const toggle = (await within(dialog).findByRole('checkbox')) as HTMLInputElement;
+ assert.equal(toggle.disabled, true);
+ assert.equal(within(dialog).queryByRole('button', { name: 'Save' }), null);
+ } finally {
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
+ }
+});
+
test('a typed pairing phone number survives toggling to the QR tab and back', async () => {
const { screen, fireEvent, within } = rtl;
resetFetchCalls();
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index c53d0ec65..84b2a4345 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -70,7 +70,7 @@ export function Sessions() {
const { t } = useTranslation();
useDocumentTitle(t('sessions.title'));
const toast = useToast();
- const { canWrite } = useRole();
+ const { canWrite, isAdmin } = useRole();
const queryClient = useQueryClient();
const [sessions, setSessions] = useState<Session[]>([]);
const [loading, setLoading] = useState(true);
@@ -730,33 +730,36 @@ export function Sessions() {
<p className="input-error">{t('sessions.create.tooLong', { length: newSessionName.length })}</p>
)}
{nameIssues.includes('duplicate') && <p className="input-error">{t('sessions.create.duplicate')}</p>}
- <div className="proxy-form-section">
- <label className="detail-toggle-row" htmlFor="create-use-proxy">
- <span>{t('sessions.proxy.enabled')}</span>
- <input
- id="create-use-proxy"
- type="checkbox"
- checked={useProxy}
- onChange={e => setUseProxy(e.target.checked)}
- />
- </label>
- {useProxy && (
- <>
- <label htmlFor="create-proxy-url">{t('sessions.proxy.url')}</label>
+ {/* The API refuses proxyUrl from a key below ADMIN, so the section is not offered. */}
+ {isAdmin && (
+ <div className="proxy-form-section">
+ <label className="detail-toggle-row" htmlFor="create-use-proxy">
+ <span>{t('sessions.proxy.enabled')}</span>
<input
- id="create-proxy-url"
- type="text"
- placeholder={t('sessions.proxy.urlPlaceholder')}
- value={createProxyUrl}
- onChange={e => setCreateProxyUrl(e.target.value)}
+ id="create-use-proxy"
+ type="checkbox"
+ checked={useProxy}
+ onChange={e => setUseProxy(e.target.checked)}
/>
- {createProxyInvalid && createProxyUrl.trim() && (
- <p className="input-error">{t('sessions.proxy.invalidUrl')}</p>
- )}
- <p className="input-hint">{t('sessions.proxy.createHint')}</p>
- </>
- )}
- </div>
+ </label>
+ {useProxy && (
+ <>
+ <label htmlFor="create-proxy-url">{t('sessions.proxy.url')}</label>
+ <input
+ id="create-proxy-url"
+ type="text"
+ placeholder={t('sessions.proxy.urlPlaceholder')}
+ value={createProxyUrl}
+ onChange={e => setCreateProxyUrl(e.target.value)}
+ />
+ {createProxyInvalid && createProxyUrl.trim() && (
+ <p className="input-error">{t('sessions.proxy.invalidUrl')}</p>
+ )}
+ <p className="input-hint">{t('sessions.proxy.createHint')}</p>
+ </>
+ )}
+ </div>
+ )}
</Modal>
)}
@@ -987,7 +990,7 @@ export function Sessions() {
<button className="btn-secondary" onClick={() => setProxySession(null)}>
{t('common.cancel')}
</button>
- {canWrite && !proxyLoadFailed && (
+ {isAdmin && !proxyLoadFailed && (
<button
className="btn-primary"
onClick={() => void handleProxySave()}
@@ -1037,7 +1040,7 @@ export function Sessions() {
type="checkbox"
aria-labelledby="proxy-enabled-label"
checked={proxyEnabled}
- disabled={!canWrite || proxySaving}
+ disabled={!isAdmin || proxySaving}
onChange={e => setProxyEnabled(e.target.checked)}
/>
<span className="toggle-slider"></span>
@@ -1059,7 +1062,7 @@ export function Sessions() {
: t('sessions.proxy.urlPlaceholder')
}
value={proxyUrl}
- disabled={!canWrite || proxySaving}
+ disabled={!isAdmin || proxySaving}
onChange={e => {
setProxyUrl(e.target.value);
setProxyUrlError(null);
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index 61e4f1184..50633442f 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -93,6 +93,13 @@ The key-lifecycle routes (`/api/auth/api-keys`) are additionally fenced with `@R
a session-scoped key is refused there whatever its role, so it cannot mint or widen credentials
beyond its own confinement.
+A session's egress proxy (`proxyUrl` on `POST /api/sessions`, `PATCH /api/sessions/:sessionId/proxy`)
+is set only by an unscoped `admin` key; any other key gets `403`. The proxy is trusted egress chosen by
+the administrator, so its host is deliberately not checked against internal addresses (a loopback or
+private-network proxy sidecar works). The destinations of caller-supplied URLs fetched through it are
+still vetted by the SSRF guard. Reading the proxy (`GET /api/sessions/:sessionId/proxy`) returns only
+the masked host, type and a `hasCredentials` flag.
+
## 4.3 IP Whitelisting
IP whitelisting adds an extra security layer by restricting API key access to specific IP addresses.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index a7d49a42a..b2749e456 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -372,7 +372,7 @@ When no proxy is configured, `enabled` is `false` and the other fields are `null
Update per-session proxy settings. No restart is required or performed — changes apply on the **next** `POST /start`. Send `proxyUrl: null` to clear the proxy.
-**Auth:** API key (OPERATOR) that is not restricted to specific sessions. Redirecting a session's whole egress through a chosen host is a deployment-level act, and before this route existed `proxyUrl` could only be set through `POST /api/sessions`, which is unscoped for the same reason. A session-scoped key is rejected with `403` (`@RequireUnscopedKey`).
+**Auth:** API key (ADMIN) that is not restricted to specific sessions. The proxy carries all of the session's egress, including the gateway's fetches of URLs a caller supplies, and its host is trusted egress that is not checked against internal addresses, so setting or clearing it is an administrator's decision. A key below ADMIN, or a session-scoped key, is rejected with `403` (`@RequireRole(ADMIN)`, `@RequireUnscopedKey`). Reading it (`GET` above) stays available to any key and never returns credentials.
**Path parameters**
@@ -392,7 +392,7 @@ Update per-session proxy settings. No restart is required or performed — chang
**Response** `200` — the resulting `SessionProxyResponseDto` (same shape as the GET above).
-**Errors:** `400` validation (bad `proxyUrl`) · `401` missing/invalid key, or key not scoped to this session · `403` key lacks OPERATOR role, or the key is restricted to specific sessions · `404` session not found
+**Errors:** `400` validation (bad `proxyUrl`) · `401` missing/invalid key, or key not scoped to this session · `403` key lacks ADMIN role, or the key is restricted to specific sessions · `404` session not found
#### GET /api/sessions/:sessionId/qr
@@ -524,16 +524,16 @@ Get session statistics for multi-session monitoring.
Create a new WhatsApp session.
-**Auth:** API key (OPERATOR) that is not restricted to specific sessions. Creating a session is a deployment-level act: the new session is outside the caller's `allowedSessions` by construction, so a session-scoped key is rejected with `403` (`@RequireUnscopedKey`). An unscoped OPERATOR/ADMIN key may create a session.
+**Auth:** API key (OPERATOR) that is not restricted to specific sessions. Creating a session is a deployment-level act: the new session is outside the caller's `allowedSessions` by construction, so a session-scoped key is rejected with `403` (`@RequireUnscopedKey`). An unscoped OPERATOR/ADMIN key may create a session; setting `proxyUrl` requires an ADMIN key.
**Request body** — `CreateSessionDto`
-| Field | Type | Required | Constraints | Description |
-| ----------- | ----------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `name` | string | Yes | `@IsString`; length 3–50; `@Matches(/^[a-zA-Z0-9-]+$/)` (letters, numbers, hyphens only) | Unique session name; duplicate → `409` |
-| `config` | object | No | `@IsOptional` (arbitrary object, no shape validation) | Opaque engine config; defaults to `{}`; never returned in responses |
-| `proxyUrl` | string | No | `@IsOptional`; `@IsString`; max 255; `@IsUrl` (protocols `http`/`https`/`socks4`/`socks5`, `require_protocol`, `require_tld:false`, `allow_underscores`) | Per-session proxy egress; credentialed `http://user:pass@host` and single-label hosts allowed; not SSRF-blocked. ⚠ **Must be a real, reachable proxy** — an unreachable value silently blocks the WhatsApp WebSocket (no QR, start → `504`); leave unset unless you need it. See "Per-session egress proxy" below. |
-| `proxyType` | `http` \| `https` \| `socks4` \| `socks5` | No | `@IsOptional`; `@IsIn([...])` | Proxy protocol |
+| Field | Type | Required | Constraints | Description |
+| ----------- | ----------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `name` | string | Yes | `@IsString`; length 3–50; `@Matches(/^[a-zA-Z0-9-]+$/)` (letters, numbers, hyphens only) | Unique session name; duplicate → `409` |
+| `config` | object | No | `@IsOptional` (arbitrary object, no shape validation) | Opaque engine config; defaults to `{}`; never returned in responses |
+| `proxyUrl` | string | No | `@IsOptional`; `@IsString`; max 255; `@IsUrl` (protocols `http`/`https`/`socks4`/`socks5`, `require_protocol`, `require_tld:false`, `allow_underscores`) | Per-session proxy egress; credentialed `http://user:pass@host` and single-label hosts allowed; trusted egress, not SSRF-blocked; setting it requires an ADMIN key (`403` otherwise). ⚠ **Must be a real, reachable proxy** — an unreachable value silently blocks the WhatsApp WebSocket (no QR, start → `504`); leave unset unless you need it. See "Per-session egress proxy" below. |
+| `proxyType` | `http` \| `https` \| `socks4` \| `socks5` | No | `@IsOptional`; `@IsIn([...])` | Proxy protocol |
```json
{
@@ -580,6 +580,11 @@ cannot be pinned to the address that was vetted: a name that passes the check an
internal address reaches it, if the proxy can. Use a SOCKS proxy, or `SESSION_PROXY_URL_FETCH=false`, to keep
that DNS-rebinding protection.
+Only an ADMIN key may set or clear a session proxy (`proxyUrl` here, or `PATCH /api/sessions/:sessionId/proxy`).
+The proxy host itself is trusted egress chosen by the administrator: it is not checked against internal
+addresses, so a loopback or private-network proxy works. The destinations of URLs you supply are checked
+whichever proxy they go through.
+
**Response** `201`
```json
@@ -600,7 +605,7 @@ that DNS-rebinding protection.
Like every other session route, this returns the `SessionResponseDto` shape (via `fromEntity`), so `config`, `proxyUrl` and `proxyType` are stripped and `lastActiveAt` appears as `lastActive`. Newly created `status` is `created`. Masked proxy details come only from `GET /api/sessions/{sessionId}/proxy`.
-**Errors:** `400` validation (bad `name`/`proxyUrl`/`proxyType`, or an extra non-whitelisted field) · `401` · `403` key lacks OPERATOR role · `409` session name already exists
+**Errors:** `400` validation (bad `name`/`proxyUrl`/`proxyType`, or an extra non-whitelisted field) · `401` · `403` key lacks OPERATOR role, `proxyUrl` set by a key below ADMIN, or the key is restricted to specific sessions · `409` session name already exists
#### POST /api/sessions/:sessionId/start
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index ba5a07908..452e0811b 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -109,7 +109,9 @@ curl -X POST "$BASE/api/sessions" \
With an optional per-session egress proxy — only if your network can't reach WhatsApp directly. The
proxy **must be a real, reachable host**; an unreachable value silently blocks the WhatsApp WebSocket
-(no QR is ever delivered) and `POST /api/sessions/:sessionId/start` returns `504` after ~30s:
+(no QR is ever delivered) and `POST /api/sessions/:sessionId/start` returns `504` after ~30s.
+
+Setting `proxyUrl` requires an unscoped ADMIN key; any other key gets `403`.
```bash
curl -X POST "$BASE/api/sessions" \
@@ -129,7 +131,7 @@ curl "$BASE/api/sessions/$SESSION_ID/proxy" \
#### PATCH /api/sessions/:sessionId/proxy
-Update per-session proxy settings (OPERATOR). No restart — changes apply on the next start. Send `"proxyUrl": null` to clear.
+Update per-session proxy settings (ADMIN, unscoped key). No restart — changes apply on the next start. Send `"proxyUrl": null` to clear.
```bash
curl -X PATCH "$BASE/api/sessions/$SESSION_ID/proxy" \
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index e20e40a55..3d54974be 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -132,9 +132,9 @@ The top-level client also exposes:
| `getConfig` | `getConfig(id)` | Read a session's engine configuration. |
| `updateConfig` | `updateConfig(id, body)` | Update a running session's configuration; takes effect without re-linking the account. **OPERATOR** |
| `getProxy` | `getProxy(id)` | Read a session's masked proxy configuration (credentials never returned). |
-| `updateProxy` | `updateProxy(id, body)` | Update per-session proxy settings; changes apply on the next start, not to a running engine. Send `proxyUrl: null` to clear. **OPERATOR** |
+| `updateProxy` | `updateProxy(id, body)` | Update per-session proxy settings; changes apply on the next start, not to a running engine. Send `proxyUrl: null` to clear. **ADMIN** |
| `get` | `get(id)` | Get a single session by id. |
-| `create` | `create(body)` | Create a new session (`body.name` required). **OPERATOR** |
+| `create` | `create(body)` | Create a new session (`body.name` required). **OPERATOR**; setting `proxyUrl` requires **ADMIN** |
| `delete` | `delete(id)` | Delete a session. **OPERATOR** |
| `start` | `start(id)` | Start a session and initialize the WhatsApp connection. **OPERATOR** |
| `stop` | `stop(id)` | Stop a session and disconnect gracefully. **OPERATOR** |
@@ -508,9 +508,9 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| `get_config` | `get_config(session_id) -> SessionConfig` | Read a session's engine configuration. |
| `update_config` | `update_config(session_id, body) -> SessionConfig` | Update a running session's configuration; takes effect without re-linking the account. **OPERATOR** |
| `get_proxy` | `get_proxy(session_id) -> SessionProxy` | Read a session's masked proxy configuration (credentials never returned). |
-| `update_proxy` | `update_proxy(session_id, body) -> SessionProxy` | Update per-session proxy settings; changes apply on the next start. Send `proxyUrl: null` to clear. **OPERATOR** |
+| `update_proxy` | `update_proxy(session_id, body) -> SessionProxy` | Update per-session proxy settings; changes apply on the next start. Send `proxyUrl: null` to clear. **ADMIN** |
| `get` | `get(session_id) -> SessionResponse` | Get one session. |
-| `create` | `create(body) -> SessionResponse` | Create a session (`body["name"]` required). **OPERATOR** |
+| `create` | `create(body) -> SessionResponse` | Create a session (`body["name"]` required). **OPERATOR**; setting `proxyUrl` requires **ADMIN** |
| `delete` | `delete(session_id) -> None` | Delete a session. **OPERATOR** |
| `start` | `start(session_id) -> SessionResponse` | Start (connect) a session. **OPERATOR** |
| `stop` | `stop(session_id) -> SessionResponse` | Stop a session. **OPERATOR** |
@@ -858,9 +858,9 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| `getConfig` | `getConfig(string $id): array` | Read a session's engine configuration. |
| `updateConfig` | `updateConfig(string $id, array $body): array` | Update a running session's configuration; takes effect without re-linking the account. **OPERATOR** |
| `getProxy` | `getProxy(string $id): array` | Read a session's masked proxy configuration (credentials never returned). |
-| `updateProxy` | `updateProxy(string $id, array $body): array` | Update per-session proxy settings; changes apply on the next start. Send `proxyUrl: null` to clear. **OPERATOR** |
+| `updateProxy` | `updateProxy(string $id, array $body): array` | Update per-session proxy settings; changes apply on the next start. Send `proxyUrl: null` to clear. **ADMIN** |
| `get` | `get(string $id): array` | Get one session. |
-| `create` | `create(array $body): array` | Create a session (`$body['name']` required). **OPERATOR** |
+| `create` | `create(array $body): array` | Create a session (`$body['name']` required). **OPERATOR**; setting `proxyUrl` requires **ADMIN** |
| `delete` | `delete(string $id): void` | Delete a session. **OPERATOR** |
| `start` | `start(string $id): array` | Start a session. **OPERATOR** |
| `stop` | `stop(string $id): array` | Stop a session. **OPERATOR** |
diff --git a/sdk/go/sessions.go b/sdk/go/sessions.go
index 5d7844146..dd9c614cf 100644
--- a/sdk/go/sessions.go
+++ b/sdk/go/sessions.go
@@ -45,7 +45,7 @@ func (s *SessionsService) GetProxy(ctx context.Context, sessionID string) (*Sess
}
// UpdateProxy changes per-session proxy settings. No restart is performed -- changes apply on the
-// next start. Send ProxyURL as JSON null to clear the proxy.
+// next start. Send ProxyURL as JSON null to clear the proxy. Requires an unscoped ADMIN key.
func (s *SessionsService) UpdateProxy(ctx context.Context, sessionID string, body UpdateSessionProxyRequest) (*SessionProxy, error) {
var out SessionProxy
err := s.client.do(ctx, "PATCH", "/api/sessions/"+pathEscape(sessionID)+"/proxy", nil, body, &out)
@@ -65,7 +65,7 @@ func (s *SessionsService) Get(ctx context.Context, sessionID string) (*SessionRe
return &out, nil
}
-// Create provisions a new session.
+// Create provisions a new session. Requires an OPERATOR-level key; setting ProxyURL requires an ADMIN key.
func (s *SessionsService) Create(ctx context.Context, body CreateSessionRequest) (*SessionResponse, error) {
var out SessionResponse
err := s.client.do(ctx, "POST", "/api/sessions", nil, body, &out)
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.java
index 8accfac1d..30a02b286 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.java
@@ -60,7 +60,7 @@ public final class SessionsResource {
/**
* Update per-session proxy settings. No restart is performed — changes apply on the next start.
- * Send {@code proxyUrl: null} to clear the proxy. Requires an OPERATOR-level key.
+ * Send {@code proxyUrl: null} to clear the proxy. Requires an unscoped ADMIN key.
*/
public SessionProxy updateProxy(String id, UpdateSessionProxyRequest body) {
return client.request(
@@ -72,7 +72,7 @@ public final class SessionsResource {
return client.request(HttpMethod.GET, "/api/sessions/" + encodeSegment(id), null, null, SessionResponse.class);
}
- /** Create a new session. Requires an OPERATOR-level key. */
+ /** Create a new session. Requires an OPERATOR-level key; setting proxyUrl requires an ADMIN key. */
public SessionResponse create(CreateSessionRequest body) {
return client.request(HttpMethod.POST, "/api/sessions", null, body, SessionResponse.class);
}
diff --git a/sdk/javascript/src/resources/sessions.ts b/sdk/javascript/src/resources/sessions.ts
index 2e5a13bb5..e0f218c8f 100644
--- a/sdk/javascript/src/resources/sessions.ts
+++ b/sdk/javascript/src/resources/sessions.ts
@@ -68,7 +68,7 @@ export class SessionsResource {
/**
* Update per-session proxy settings. No restart is performed — changes apply on the next start.
- * Send `proxyUrl: null` to clear the proxy. **OPERATOR**
+ * Send `proxyUrl: null` to clear the proxy. **ADMIN** (unscoped key)
*/
updateProxy(id: string, body: UpdateSessionProxyRequest): Promise<SessionProxy> {
return this.client.request<SessionProxy>({
@@ -83,7 +83,7 @@ export class SessionsResource {
return this.client.request<SessionResponse>({ method: 'GET', path: `/api/sessions/${encodeSegment(id)}` });
}
- /** Create a new session. Requires an OPERATOR-level key. */
+ /** Create a new session. Requires an OPERATOR-level key; setting proxyUrl requires an ADMIN key. */
create(body: CreateSessionRequest): Promise<SessionResponse> {
return this.client.request<SessionResponse>({ method: 'POST', path: '/api/sessions', body });
}
diff --git a/sdk/php/src/Resources/SessionsResource.php b/sdk/php/src/Resources/SessionsResource.php
index e8fcd124f..7a8203545 100644
--- a/sdk/php/src/Resources/SessionsResource.php
+++ b/sdk/php/src/Resources/SessionsResource.php
@@ -65,7 +65,7 @@ class SessionsResource
/**
* Update per-session proxy settings. No restart — changes apply on the next start.
- * Send proxyUrl: null to clear. OPERATOR role required.
+ * Send proxyUrl: null to clear. Unscoped ADMIN key required.
*
* @param array{proxyUrl?: ?string} $body
* @return array{enabled: bool, proxyType: ?string, proxyHost: ?string, hasCredentials: bool}
@@ -82,6 +82,8 @@ class SessionsResource
}
/**
+ * Create a session. Requires an OPERATOR-level key; setting proxyUrl requires an ADMIN key.
+ *
* @param array<string,mixed> $body
* @return array<string,mixed>
*/
diff --git a/sdk/python/openwa/resources/sessions.py b/sdk/python/openwa/resources/sessions.py
index 08e8985b7..58b7e83ef 100644
--- a/sdk/python/openwa/resources/sessions.py
+++ b/sdk/python/openwa/resources/sessions.py
@@ -64,7 +64,10 @@ class SessionsResource:
return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/proxy")
def update_proxy(self, session_id: str, body: UpdateSessionProxyRequest) -> SessionProxy:
- """Update per-session proxy settings. No restart — changes apply on the next start."""
+ """Update per-session proxy settings. No restart — changes apply on the next start.
+
+ Requires an unscoped ADMIN key.
+ """
return self._http.request(
"PATCH", f"/api/sessions/{quote_segment(session_id)}/proxy", body=body
)
@@ -74,7 +77,7 @@ class SessionsResource:
return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}")
def create(self, body: CreateSessionRequest) -> SessionResponse:
- """Provision a new session."""
+ """Provision a new session. Requires an OPERATOR-level key; setting proxyUrl requires an ADMIN key."""
return self._http.request("POST", "/api/sessions", body=body)
def delete(self, session_id: str) -> None:
diff --git a/src/modules/session/dto/create-session.dto.ts b/src/modules/session/dto/create-session.dto.ts
index a39624c65..0a24f5588 100644
--- a/src/modules/session/dto/create-session.dto.ts
+++ b/src/modules/session/dto/create-session.dto.ts
@@ -41,14 +41,15 @@ export class CreateSessionDto {
'Optional per-session egress proxy URL (http/https/socks4/socks5; credentialed form ' +
'"http://user:pass@host" allowed). Must be a REAL, REACHABLE proxy — an unreachable value ' +
'silently blocks the WhatsApp WebSocket (no QR is ever delivered) and the session start times ' +
- 'out (~30s → 504 Gateway Timeout). Leave unset unless your network cannot reach WhatsApp directly.',
+ 'out (~30s → 504 Gateway Timeout). Leave unset unless your network cannot reach WhatsApp directly. ' +
+ 'Setting it requires an ADMIN key (403 otherwise).',
})
@IsOptional()
@IsString()
@MaxLength(255)
// Reject a malformed/non-proxy URL at the boundary (credentialed http://user:pass@host and
// socks4/5 still validate). The host is intentionally NOT SSRF-blocked here — a per-session proxy
- // is operator-chosen egress, and a loopback proxy sidecar is a legitimate setup.
+ // is trusted egress that only an ADMIN key may set, and a loopback proxy sidecar is a legitimate setup.
// require_tld:false + allow_underscores:true so single-label container hostnames (e.g. `squid`,
// `localhost`) and IP-literal proxies validate, matching the engine's URL-parse check.
@IsUrl(
diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.ts
index b9cf15783..302f3b729 100644
--- a/src/modules/session/session.controller.spec.ts
+++ b/src/modules/session/session.controller.spec.ts
@@ -7,8 +7,9 @@ import type { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { ChatScopeService } from '../auth/chat-scope.service';
import type { ChatSummary } from '../../engine/interfaces/whatsapp-engine.interface';
-import type { ApiKey } from '../auth/entities/api-key.entity';
-import { BadGatewayException, BadRequestException, ConflictException } from '@nestjs/common';
+import { ApiKeyRole, type ApiKey } from '../auth/entities/api-key.entity';
+import { REQUIRED_ROLE_KEY, UNSCOPED_KEY } from '../auth/decorators/auth.decorators';
+import { BadGatewayException, BadRequestException, ConflictException, ForbiddenException } from '@nestjs/common';
// POST /sessions declared a SessionResponseDto in its Swagger metadata but returned the raw
// TypeORM entity, leaking internal columns (config, proxyUrl, proxyType) and the entity-only
@@ -102,6 +103,50 @@ describe('SessionController — create() response contract', () => {
});
});
+// A session proxy is deployment-level egress: setting or clearing one needs an ADMIN key on every
+// route that writes it.
+describe('SessionController: session proxy writes are ADMIN only', () => {
+ const key = (role: ApiKeyRole) => ({ id: 'k', role }) as ApiKey;
+ let sessionService: { create: jest.Mock; engineLoaded: jest.Mock };
+ let controller: SessionController;
+
+ beforeEach(() => {
+ sessionService = {
+ create: jest.fn().mockResolvedValue({ id: 'sess-uuid-1', name: 'with-proxy', config: {} }),
+ engineLoaded: jest.fn().mockReturnValue(false),
+ };
+ controller = new SessionControllerClass(
+ sessionService as unknown as SessionService,
+ { logInfo: jest.fn().mockResolvedValue(undefined) } as unknown as AuditService,
+ new ChatScopeService(),
+ );
+ });
+
+ it('PATCH :sessionId/proxy requires the ADMIN role and an unscoped key', () => {
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata, not invoking
+ const handler = SessionControllerClass.prototype.updateProxy;
+ expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, handler)).toBe(ApiKeyRole.ADMIN);
+ expect(Reflect.getMetadata(UNSCOPED_KEY, handler)).toBe(true);
+ });
+
+ it.each([
+ ['an OPERATOR key', key(ApiKeyRole.OPERATOR)],
+ ['no key', undefined],
+ ])('POST /sessions with proxyUrl from %s is refused before anything is created', async (_, apiKey) => {
+ await expect(
+ controller.create({ name: 'with-proxy', proxyUrl: 'http://proxy.internal:8080' }, apiKey),
+ ).rejects.toBeInstanceOf(ForbiddenException);
+ expect(sessionService.create).not.toHaveBeenCalled();
+ });
+
+ it('POST /sessions with proxyUrl from an ADMIN key, or without one from an OPERATOR key, creates', async () => {
+ await controller.create({ name: 'with-proxy', proxyUrl: 'http://proxy.internal:8080' }, key(ApiKeyRole.ADMIN));
+ await controller.create({ name: 'no-proxy' }, key(ApiKeyRole.OPERATOR));
+
+ expect(sessionService.create).toHaveBeenCalledTimes(2);
+ });
+});
+
// POST /sessions/:sessionId/logout audits SESSION_LOGGED_OUT only after the service resolves — an
// incomplete engine-backed attempt (502 SESSION_LOGOUT_INCOMPLETE) must NOT record a success
// audit row, and the service's structured rejection must be forwarded verbatim.
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 6a976605a..ccd4497bf 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -12,6 +12,7 @@ import {
HttpStatus,
ParseUUIDPipe,
BadRequestException,
+ ForbiddenException,
Res,
} from '@nestjs/common';
import type { Response } from 'express';
@@ -92,8 +93,19 @@ export class SessionController {
description: 'Session created',
type: SessionResponseDto,
})
+ @ApiResponse({
+ status: 403,
+ description:
+ 'Key lacks the OPERATOR role, is restricted to specific sessions, or set proxyUrl without the ADMIN role',
+ })
@ApiResponse({ status: 409, description: 'Session name already exists' })
- async create(@Body() dto: CreateSessionDto): Promise<SessionResponseDto> {
+ async create(@Body() dto: CreateSessionDto, @CurrentApiKey() apiKey?: ApiKey): Promise<SessionResponseDto> {
+ // A session proxy carries the session's egress, including the gateway's fetches of caller-supplied
+ // URLs, so choosing one is a deployment decision: ADMIN only, like PATCH :sessionId/proxy. The
+ // global guard always attaches the key, so a missing one is refused too.
+ if (dto.proxyUrl && apiKey?.role !== ApiKeyRole.ADMIN) {
+ throw new ForbiddenException('Setting proxyUrl requires an ADMIN key');
+ }
const session = await this.sessionService.create(dto);
await this.auditService.logInfo(AuditAction.SESSION_CREATED, {
sessionId: session.id,
@@ -214,11 +226,11 @@ export class SessionController {
}
@Patch(':sessionId/proxy')
- @RequireRole(ApiKeyRole.OPERATOR)
- // Routing a session's whole egress through an attacker-chosen host is an instance-level decision,
- // not a per-session one. Before this route existed, `proxyUrl` could only be set through POST
- // /sessions, which is unscoped by the fence above, so a key restricted to specific sessions could
- // never configure a proxy. Keep that reachability rather than widening it as a side effect.
+ // A session proxy carries all of the session's egress, including the gateway's fetches of
+ // caller-supplied URLs, and its host is not checked against internal addresses: it is trusted
+ // egress chosen by the deployment's administrator. Setting or clearing it is therefore ADMIN only,
+ // like proxyUrl on POST /sessions, and never open to a key restricted to specific sessions.
+ @RequireRole(ApiKeyRole.ADMIN)
@RequireUnscopedKey()
@ApiOperation({
summary: 'Update the per-session egress proxy configuration',
@@ -233,6 +245,7 @@ export class SessionController {
type: SessionProxyResponseDto,
})
@ApiResponse({ status: 400, description: 'Invalid proxyUrl' })
+ @ApiResponse({ status: 403, description: 'Key lacks the ADMIN role, or is restricted to specific sessions' })
@ApiResponse({ status: 404, description: 'Session not found' })
async updateProxy(
@Param('sessionId', ParseUUIDPipe) id: string,