Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Connector sign-ins work with a server on this computer (#918)

Louis Amaudruz6ac68bf4f873
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 7e1d2bdac..540a7fc5a 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -45,6 +45,7 @@ import {
gitHubConnectionSchema,
gitHubFlowSchema,
} from '@shared/core/switch-servers/github-connection';
+import { isHttpsOrLoopback } from '@shared/core/switch-servers/loopback';
import type {
SlackOwnAppSetup,
SlackTokensChecked,
@@ -3375,8 +3376,8 @@ export async function startGitHubConnection(
server: SwitchServer,
input: { port: number; state: string; completion_secret: string }
) {
- if (new URL(server.gatewayUrl).protocol !== 'https:')
- throw new Error('GitHub connections require HTTPS.');
+ if (!isHttpsOrLoopback(new URL(server.gatewayUrl)))
+ throw new Error('GitHub connections require HTTPS, unless the server is on this computer.');
const value = z.object({ id: z.string().regex(/^[A-Za-z0-9_-]{43}$/), url: z.string() }).parse(
await (
await gatewayFetch(server, '/provider-connections/github/flows', {
@@ -3459,8 +3460,8 @@ export async function startServiceConnection(
service: string,
input: { port: number; state: string; completion_secret: string }
): Promise<ServiceFlowStart> {
- if (new URL(server.gatewayUrl).protocol !== 'https:')
- throw new Error('Service connections require HTTPS.');
+ if (!isHttpsOrLoopback(new URL(server.gatewayUrl)))
+ throw new Error('Service connections require HTTPS, unless the server is on this computer.');
const value = serviceFlowStartSchema.parse(
await (
await gatewayFetch(server, serviceFlows(service), {
@@ -3476,7 +3477,7 @@ export async function startServiceConnection(
!url.username &&
!url.password &&
(value.mode === 'core'
- ? url.protocol === 'https:' &&
+ ? isHttpsOrLoopback(url) &&
[server.gatewayUrl, server.apiUrl].some((own) => new URL(own).origin === url.origin) &&
url.pathname === `/gateway${serviceFlows(service)}/authorize` &&
url.searchParams.get('state') === value.id
@@ -3804,10 +3805,7 @@ export async function giveMachineLogin(
// The login is sealed, but the key it was sealed to came from this server:
// over plain HTTP anyone in between could have handed over their own.
const gateway = new URL(server.gatewayUrl);
- if (
- gateway.protocol !== 'https:' &&
- !['localhost', '127.0.0.1', '[::1]'].includes(gateway.hostname)
- )
+ if (!isHttpsOrLoopback(gateway))
throw new Error('Giving a machine a provider login requires HTTPS.');
const res = await managementFetch(
server,
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.test.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.test.ts
new file mode 100644
index 000000000..1991882a0
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+import { isHttpsOrLoopback } from './loopback';
+
+describe('isHttpsOrLoopback', () => {
+ it('takes https anywhere, and http to this computer', () => {
+ expect(isHttpsOrLoopback(new URL('https://switch.example.com'))).toBe(true);
+ expect(isHttpsOrLoopback(new URL('http://127.0.0.1:51001'))).toBe(true);
+ expect(isHttpsOrLoopback(new URL('http://localhost:3000'))).toBe(true);
+ expect(isHttpsOrLoopback(new URL('http://[::1]:3000'))).toBe(true);
+ });
+
+ it('refuses http to anywhere else', () => {
+ expect(isHttpsOrLoopback(new URL('http://switch.example.com'))).toBe(false);
+ expect(isHttpsOrLoopback(new URL('http://192.168.1.10:3000'))).toBe(false);
+ expect(isHttpsOrLoopback(new URL('http://127.0.0.1.example.com'))).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.ts
new file mode 100644
index 000000000..855da260c
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/loopback.ts
@@ -0,0 +1,13 @@
+/** This computer's own addresses, as a URL's `hostname` gives them. */
+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
+
+/**
+ * Whether `url` is safe to send a sign-in or a secret over: https anywhere, or
+ * plain http to this computer itself, where nothing in between can read it.
+ * A server Console runs on this computer is on http://127.0.0.1.
+ */
+export function isHttpsOrLoopback(url: URL): boolean {
+ return (
+ url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))
+ );
+}
diff --git a/core/switch_core/gateway/service_flows.py b/core/switch_core/gateway/service_flows.py
index 440d4b401..d84aafccb 100644
--- a/core/switch_core/gateway/service_flows.py
+++ b/core/switch_core/gateway/service_flows.py
@@ -150,10 +150,25 @@ async def start(
return {"id": body.state, "url": url, "mode": flow.mode}
+_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
+
+
+def _secure_cookie(request: Request) -> bool:
+ """Whether the flow's cookie is marked Secure: always, except on a server
+ reached over plain http on this computer's own address, such as one
+ Switch Console runs. Some browsers drop a Secure cookie set over http
+ even there, and on the loopback address nothing in between could read it.
+ """
+ return not (
+ request.url.scheme == "http" and request.url.hostname in _LOOPBACK_HOSTS
+ )
+
+
@router.get("/authorize")
async def authorize(
service: str,
state: str,
+ request: Request,
broker: Annotated[ServiceBroker, Depends(get_service_broker)],
flows: Annotated[ServiceFlows, Depends(get_service_flows)],
) -> Response:
@@ -176,7 +191,7 @@ async def authorize(
_cookie(state),
nonce,
max_age=600,
- secure=True,
+ secure=_secure_cookie(request),
httponly=True,
samesite="lax",
path=_cookie_path(service),
@@ -211,7 +226,7 @@ async def callback(
response.delete_cookie(
_cookie(state),
path=_cookie_path(service),
- secure=True,
+ secure=_secure_cookie(request),
httponly=True,
samesite="lax",
)
diff --git a/core/tests/switch_core/gateway/test_service_flows.py b/core/tests/switch_core/gateway/test_service_flows.py
index 610c760ce..1643f9869 100644
--- a/core/tests/switch_core/gateway/test_service_flows.py
+++ b/core/tests/switch_core/gateway/test_service_flows.py
@@ -540,6 +540,29 @@ class TestCoreCallback:
]
assert exchange["redirect_uri"] == f"{PUBLIC}{FLOWS}/callback"
+ async def test_the_cookie_is_secure_except_on_this_computer(
+ self, session_factory, tmp_path
+ ) -> None:
+ # A server Switch Console runs is reached over plain http on the
+ # loopback address, where a Secure cookie may be dropped by the browser.
+ world = _world(
+ session_factory, tmp_path / "catalog", redirect="[core]", public_url=PUBLIC
+ )
+ ada = await add_member(session_factory, "ada")
+ async with world.harness.client() as client:
+ remote = Console(client, ada)
+ started = await remote.start()
+ authorize = started.json()["url"].removeprefix(PUBLIC)
+ left = await client.get(f"https://switch.example.test{authorize}")
+ assert "secure" in left.headers["set-cookie"].lower()
+
+ local = Console(client, ada)
+ started = await local.start()
+ authorize = started.json()["url"].removeprefix(PUBLIC)
+ left = await client.get(f"http://127.0.0.1:51001{authorize}")
+ assert left.status_code == 307
+ assert "secure" not in left.headers["set-cookie"].lower()
+
async def test_a_code_cannot_skip_core(self, session_factory, tmp_path) -> None:
world = _world(
session_factory, tmp_path / "catalog", redirect="[core]", public_url=PUBLIC