Skip to content

Commit f269fbd

Browse files
fix(server): port upstream PTY connect route authorization (anomalyco/opencode#58258)
1 parent a1fefe9 commit f269fbd

9 files changed

Lines changed: 84 additions & 51 deletions

File tree

‎packages/opencode/src/server/routes/instance/httpapi/groups/pty.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { Pty } from "@opencode-ai/core/pty"
22
import { PtyTicket } from "@opencode-ai/core/pty/ticket"
33
import { PtyID } from "@opencode-ai/core/pty/schema"
4-
import { PTY_CONNECT_TICKET_QUERY } from "@/server/shared/pty-ticket"
4+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
5+
import { PTY_CONNECT_PATH, PTY_CONNECT_TICKET_QUERY } from "@/server/shared/pty-ticket"
6+
// altimate_change end
57
import { Schema } from "effect"
68
import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi"
79
import { Authorization, PtyConnectAuthorization } from "../middleware/authorization"
@@ -34,7 +36,9 @@ export const PtyPaths = {
3436
update: `${root}/:ptyID`,
3537
remove: `${root}/:ptyID`,
3638
connectToken: `${root}/:ptyID/connect-token`,
37-
connect: `${root}/:ptyID/connect`,
39+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
40+
connect: PTY_CONNECT_PATH,
41+
// altimate_change end
3842
} as const
3943

4044
export const PtyApi = HttpApi.make("pty")

‎packages/opencode/src/server/routes/instance/httpapi/handlers/pty.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,14 @@ export const ptyConnectHandlers = HttpApiBuilder.group(PtyConnectApi, "pty-conne
184184
params: { ptyID: PtyID }
185185
request: HttpServerRequest.HttpServerRequest
186186
}) {
187+
// altimate_change start — upstream_fix: check origin and ticket before PTY existence (anomalyco/opencode@7b39a338a0)
188+
if (!validOrigin(ctx.request, cors)) return HttpServerResponse.empty({ status: 403 })
189+
190+
const ticket = new URL(ctx.request.url, "http://localhost").searchParams.get(PTY_CONNECT_TICKET_QUERY)
191+
if (ticket && !(yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID, ...(yield* ticketScope) })))
192+
return HttpServerResponse.empty({ status: 403 })
193+
// altimate_change end
194+
187195
const exists = yield* pty(Pty.Service.use((service) => service.get(ctx.params.ptyID))).pipe(
188196
Effect.map((info) => info.status === "running"),
189197
Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(false)),
@@ -192,13 +200,6 @@ export const ptyConnectHandlers = HttpApiBuilder.group(PtyConnectApi, "pty-conne
192200

193201
const query = Schema.decodeUnknownOption(CursorQuery)(yield* HttpServerRequest.ParsedSearchParams)
194202
if (Option.isNone(query)) return HttpServerResponse.empty({ status: 400 })
195-
const ticket = new URL(ctx.request.url, "http://localhost").searchParams.get(PTY_CONNECT_TICKET_QUERY)
196-
if (ticket) {
197-
const valid = validOrigin(ctx.request, cors)
198-
? yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID, ...(yield* ticketScope) })
199-
: false
200-
if (!valid) return HttpServerResponse.empty({ status: 403 })
201-
}
202203
const parsedCursor = query.value.cursor === undefined ? undefined : Number(query.value.cursor)
203204
const cursor =
204205
parsedCursor !== undefined && Number.isSafeInteger(parsedCursor) && parsedCursor >= -1

‎packages/opencode/src/server/routes/instance/httpapi/middleware/authorization.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ import { ServerAuth } from "@/server/auth"
22
import { Effect, Encoding, Layer, Redacted } from "effect"
33
import { HttpEffect, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"
44
import { HttpApiError, HttpApiMiddleware } from "effect/unstable/httpapi"
5-
import { hasPtyConnectTicketURL } from "@/server/shared/pty-ticket"
5+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
6+
import { PTY_CONNECT_PATH, PTY_CONNECT_TICKET_QUERY } from "@/server/shared/pty-ticket"
7+
// altimate_change end
68
import { isPublicUIPath } from "@/server/shared/public-ui"
79
export {
810
Authorization as ServerAuthorization,
@@ -139,8 +141,13 @@ export const ptyConnectAuthorizationLayer = Layer.effect(
139141
return PtyConnectAuthorization.of((effect) =>
140142
Effect.gen(function* () {
141143
const request = yield* HttpServerRequest.HttpServerRequest
144+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
145+
// Use the route selected by Effect so authorization and dispatch cannot disagree about the request path.
146+
const route = yield* HttpRouter.RouteContext
142147
const url = new URL(request.url, "http://localhost")
143-
if (hasPtyConnectTicketURL(url)) return yield* effect
148+
if (route.route.path === PTY_CONNECT_PATH && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY))
149+
return yield* effect
150+
// altimate_change end
144151
return yield* credentialFromURL(url, request).pipe(
145152
Effect.flatMap((credential) => validateCredential(effect, credential, config)),
146153
)

‎packages/opencode/src/server/shared/pty-ticket.ts‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,6 @@ export const PTY_CONNECT_TICKET_QUERY = "ticket"
22
export const PTY_CONNECT_TOKEN_HEADER = "x-opencode-ticket"
33
export const PTY_CONNECT_TOKEN_HEADER_VALUE = "1"
44

5-
const PTY_CONNECT_PATH = /^\/pty\/[^/]+\/connect$/
6-
7-
// Auth middleware skips Basic Auth when this matches; the PTY connect handler
8-
// is then responsible for validating the ticket.
9-
export function isPtyConnectPath(pathname: string) {
10-
return PTY_CONNECT_PATH.test(pathname)
11-
}
12-
13-
export function hasPtyConnectTicketURL(url: URL) {
14-
return isPtyConnectPath(url.pathname) && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
15-
}
5+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
6+
export const PTY_CONNECT_PATH = "/pty/:ptyID/connect"
7+
// altimate_change end

‎packages/opencode/test/server/httpapi-pty.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,22 @@ describe("pty HttpApi bridge", () => {
216216
expect(response.status).toBe(404)
217217
})
218218

219+
// altimate_change start — upstream_fix: check origin and ticket before PTY existence (anomalyco/opencode@7b39a338a0)
220+
test("rejects bad tickets and origins before revealing whether a PTY exists", async () => {
221+
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
222+
const path = PtyPaths.connect.replace(":ptyID", PtyID.ascending())
223+
const badTicket = await typedApp().request(`${path}?ticket=not-a-ticket`, {
224+
headers: { "x-opencode-directory": tmp.path },
225+
})
226+
expect(badTicket.status).toBe(403)
227+
228+
const crossOrigin = await typedApp().request(path, {
229+
headers: { "x-opencode-directory": tmp.path, origin: "https://evil.example" },
230+
})
231+
expect(crossOrigin.status).toBe(403)
232+
})
233+
// altimate_change end
234+
219235
test("returns typed not found errors for missing PTY HTTP resources", async () => {
220236
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
221237
const headers = { "x-opencode-directory": tmp.path }

‎packages/opencode/test/upstream/adversarial/upi-server.test.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ import fs from "fs/promises"
33
import path from "path"
44
import { ServerAuth } from "../../../src/server/auth"
55
import { cspForHtml, upstreamURL } from "../../../src/server/shared/ui"
6-
import { hasPtyConnectTicketURL, isPtyConnectPath } from "../../../src/server/shared/pty-ticket"
6+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
7+
import { PTY_CONNECT_PATH } from "../../../src/server/shared/pty-ticket"
8+
import { PtyPaths } from "../../../src/server/routes/instance/httpapi/groups/pty"
9+
// altimate_change end
710
import { isPublicUIPath } from "../../../src/server/shared/public-ui"
811

912
const repoRoot = path.resolve(import.meta.dir, "..", "..", "..", "..", "..")
@@ -36,13 +39,12 @@ describe("UPI-29 authorization and PTY-ticket boundaries", () => {
3639
}
3740
})
3841

39-
test("PTY connect ticket bypass is path-specific and still requires the ticket query", () => {
40-
expect(isPtyConnectPath("/pty/abc/connect")).toBe(true)
41-
expect(isPtyConnectPath("/pty/abc/other")).toBe(false)
42-
expect(hasPtyConnectTicketURL(new URL("http://localhost/pty/abc/connect?ticket=one"))).toBe(true)
43-
expect(hasPtyConnectTicketURL(new URL("http://localhost/pty/abc/connect"))).toBe(false)
44-
expect(hasPtyConnectTicketURL(new URL("http://localhost/session?ticket=one"))).toBe(false)
42+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
43+
test("PTY connect ticket bypass is keyed to the routed connect path", () => {
44+
expect(PTY_CONNECT_PATH).toBe("/pty/:ptyID/connect")
45+
expect(PtyPaths.connect).toBe(PTY_CONNECT_PATH)
4546
})
47+
// altimate_change end
4648

4749
test("public UI auth bypass is limited to GET asset paths", () => {
4850
expect(isPublicUIPath("GET", "/site.webmanifest")).toBe(true)
@@ -66,8 +68,10 @@ describe("UPI-29 authorization and PTY-ticket boundaries", () => {
6668
const ptyBody = source.slice(source.indexOf("export const ptyConnectAuthorizationLayer"))
6769
const regularBody = source.slice(source.indexOf("export const authorizationLayer"), source.indexOf("export const ptyConnectAuthorizationLayer"))
6870

69-
expect(ptyBody).toContain("if (hasPtyConnectTicketURL(url)) return yield* effect")
70-
expect(regularBody).not.toContain("hasPtyConnectTicketURL")
71+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
72+
expect(ptyBody).toContain("route.route.path === PTY_CONNECT_PATH && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY)")
73+
expect(regularBody).not.toContain("PTY_CONNECT_TICKET_QUERY")
74+
// altimate_change end
7175
})
7276
})
7377

‎packages/server/src/groups/pty.ts‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,9 @@ export const PTY_CONNECT_TICKET_QUERY = "ticket"
1111
export const PTY_CONNECT_TOKEN_HEADER = "x-opencode-ticket"
1212
export const PTY_CONNECT_TOKEN_HEADER_VALUE = "1"
1313

14-
const PTY_CONNECT_PATH = /^\/api\/pty\/[^/]+\/connect$/
15-
16-
// Authorization middleware skips credential checks when this matches; the PTY connect handler
17-
// is then responsible for consuming and validating the ticket.
18-
export function hasPtyConnectTicketURL(url: URL) {
19-
return PTY_CONNECT_PATH.test(url.pathname) && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
20-
}
14+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
15+
export const PTY_CONNECT_PATH = "/api/pty/:ptyID/connect"
16+
// altimate_change end
2117

2218
export const PtyGroup = HttpApiGroup.make("server.pty")
2319
.add(
@@ -117,7 +113,9 @@ export const PtyGroup = HttpApiGroup.make("server.pty")
117113
.add(
118114
// Query fields are decoded in the raw handler after the existence check so a missing
119115
// session responds with an empty 404 before any upgrade work.
120-
HttpApiEndpoint.get("pty.connect", "/api/pty/:ptyID/connect", {
116+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
117+
HttpApiEndpoint.get("pty.connect", PTY_CONNECT_PATH, {
118+
// altimate_change end
121119
params: { ptyID: PtyID },
122120
success: Schema.Boolean,
123121
error: [ForbiddenError, PtyNotFoundError],

‎packages/server/src/handlers/pty.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -136,21 +136,22 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) =>
136136
.handleRaw(
137137
"pty.connect",
138138
Effect.fn("PtyHandler.connect")(function* (ctx) {
139+
// altimate_change start — upstream_fix: check origin and ticket before PTY existence (anomalyco/opencode@7b39a338a0)
140+
if (!isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors))
141+
return HttpServerResponse.empty({ status: 403 })
142+
143+
const url = new URL(ctx.request.url, "http://localhost")
144+
const ticket = url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
145+
if (ticket && !(yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID, ...(yield* ticketScope) })))
146+
return HttpServerResponse.empty({ status: 403 })
147+
// altimate_change end
148+
139149
const pty = yield* Pty.Service
140150
const exists = yield* pty.get(ctx.params.ptyID).pipe(
141151
Effect.as(true),
142152
Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(false)),
143153
)
144154
if (!exists) return HttpServerResponse.empty({ status: 404 })
145-
146-
const url = new URL(ctx.request.url, "http://localhost")
147-
const ticket = url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
148-
if (ticket) {
149-
const valid = isAllowedRequestOrigin(ctx.request.headers.origin, ctx.request.headers.host, cors)
150-
? yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID, ...(yield* ticketScope) })
151-
: false
152-
if (!valid) return HttpServerResponse.empty({ status: 403 })
153-
}
154155
const parsedCursor = url.searchParams.get("cursor")
155156
const cursorNumber = parsedCursor === null ? undefined : Number(parsedCursor)
156157
const cursor =

‎packages/server/src/middleware/authorization.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
import { ServerAuth } from "../auth"
22
import { UnauthorizedError } from "../errors"
3-
import { hasPtyConnectTicketURL } from "../groups/pty"
3+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
4+
import { PTY_CONNECT_PATH, PTY_CONNECT_TICKET_QUERY } from "../groups/pty"
5+
// altimate_change end
46
import { Effect, Encoding, Layer, Redacted } from "effect"
5-
import { HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"
7+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
8+
import { HttpEffect, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"
9+
// altimate_change end
610
import { HttpApiMiddleware } from "effect/unstable/httpapi"
711

812
const AUTH_TOKEN_QUERY = "auth_token"
@@ -48,7 +52,13 @@ export const authorizationLayer = Layer.effect(
4852
const request = yield* HttpServerRequest.HttpServerRequest
4953
// Browsers cannot set headers on WebSocket upgrades, so a ticketed PTY connect skips
5054
// credential checks here; the connect handler consumes and validates the ticket.
51-
if (hasPtyConnectTicketURL(new URL(request.url, "http://localhost"))) return yield* effect
55+
// altimate_change start — upstream_fix: authorize PTY ticket bypass from the matched route (anomalyco/opencode#58258)
56+
// Use the route selected by Effect so authorization and dispatch cannot disagree about the request path.
57+
const route = yield* HttpRouter.RouteContext
58+
const url = new URL(request.url, "http://localhost")
59+
if (route.route.path === PTY_CONNECT_PATH && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY))
60+
return yield* effect
61+
// altimate_change end
5262
const credential = yield* credentialFromRequest(request)
5363
if (ServerAuth.authorized(credential, config)) return yield* effect
5464
yield* HttpEffect.appendPreResponseHandler((_request, response) =>

0 commit comments

Comments
 (0)