Skip to content

Commit 88777b8

Browse files
fix(opencode): close audit-v12 wave I-B instance-store reload + mcp catalog findings
1 parent 3f69dad commit 88777b8

4 files changed

Lines changed: 334 additions & 8 deletions

File tree

‎packages/opencode/src/mcp/catalog.ts‎

Lines changed: 74 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -237,15 +237,49 @@ const STRING_KEYWORDS = new Set([
237237
"contentEncoding",
238238
"contentMediaType",
239239
"$comment",
240-
"$id",
241-
"$anchor",
242-
"$dynamicAnchor",
240+
"title",
241+
"description",
243242
])
244243
const BOOLEAN_KEYWORDS = new Set(["uniqueItems", "deprecated", "readOnly", "writeOnly"])
245244

245+
// ajv compiles `patternProperties` keys and `pattern` values with the JS `RegExp` constructor;
246+
// a value that does not parse makes the whole document uncompilable.
247+
const isValidRegex = (value: string) => {
248+
try {
249+
new RegExp(value)
250+
return true
251+
} catch {
252+
return false
253+
}
254+
}
255+
256+
// JSON Schema 2020-12 anchors start with a letter or underscore and continue with
257+
// `[-A-Za-z0-9._]`; ajv's meta-schema rejects any other name.
258+
const ANCHOR_PATTERN = /^[A-Za-z_][-A-Za-z0-9._]*$/
259+
260+
// ajv resolves `$schema` against its registered meta-schemas; any other value fails the whole
261+
// document with `no schema with key or ref`. Keep only dialects the installed ajv knows.
262+
const KNOWN_DIALECTS = new Set([
263+
"https://json-schema.org/draft/2020-12/schema",
264+
"https://json-schema.org/draft/2020-12/schema#",
265+
"http://json-schema.org/schema#",
266+
])
267+
268+
// `$id` must not contain an interior fragment, and a `urn:` id needs a non-empty NID and NSS
269+
// or ajv cannot serialize it ("URN without nid").
270+
const isResolvableId = (value: string) => {
271+
const hash = value.indexOf("#")
272+
if (hash !== -1 && hash !== value.length - 1) return false
273+
if (/^urn:/i.test(value) && !/^urn:[a-z0-9][a-z0-9-]*:.+/i.test(value)) return false
274+
return true
275+
}
276+
246277
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
247278
typeof value === "object" && value !== null && !Array.isArray(value)
248279
const isSchema = (value: unknown) => typeof value === "boolean" || isPlainObject(value)
280+
// Schema maps are emitted with a null prototype so a `__proto__` member arriving from an
281+
// untrusted server is stored as an own key instead of rewriting the map's prototype.
282+
const makeRecord = () => Object.create(null) as Record<string, unknown>
249283

250284
// Schemas, maps of schemas (`properties`/`$defs`) and instance data (`enum`/`const`)
251285
// all recurse through `boundSchema`. Only real schema nodes are sanitized; without the
@@ -275,7 +309,7 @@ function boundSchema(
275309
if (value.length > 0 && bounded.length === 0) return BOUNDED
276310
return bounded
277311
}
278-
const out: Record<string, unknown> = {}
312+
const out = makeRecord()
279313
for (const [key, item] of Object.entries(value)) {
280314
// Draft-07 tuple form (`items: [a, b]`) is invalid under 2020-12, where `items`
281315
// must be a single schema. Normalize conservatively to an unconstrained schema
@@ -296,6 +330,20 @@ function boundSchema(
296330
if (kept.length > 0) out[key] = kept
297331
continue
298332
}
333+
// `patternProperties` keys are compiled as regular expressions by ajv; an invalid key makes
334+
// the whole document uncompilable even though the meta-schema accepts it, so drop that entry.
335+
if (kind === "schema" && key === "patternProperties") {
336+
if (!isPlainObject(item)) continue
337+
const clean = makeRecord()
338+
for (const [pattern, entry] of Object.entries(item)) {
339+
if (!isValidRegex(pattern)) continue
340+
const bounded = boundSchema(entry, depth + 1, seen, counter, "schema")
341+
if (bounded === BOUNDED || !isSchema(bounded)) continue
342+
clean[pattern] = bounded
343+
}
344+
out[key] = clean
345+
continue
346+
}
299347
const childKind: SchemaKind =
300348
kind === "map"
301349
? "schema"
@@ -336,7 +384,7 @@ function boundSchema(
336384
}
337385
if (key === "dependentRequired") {
338386
if (!isPlainObject(bounded)) continue
339-
const clean: Record<string, string[]> = {}
387+
const clean = makeRecord() as Record<string, string[]>
340388
for (const [name, names] of Object.entries(bounded)) {
341389
if (!Array.isArray(names)) continue
342390
const kept = names.filter((entry): entry is string => typeof entry === "string")
@@ -355,6 +403,27 @@ function boundSchema(
355403
if (typeof bounded === "string" && bounded.startsWith("#")) out[key] = bounded
356404
continue
357405
}
406+
if (key === "$anchor" || key === "$dynamicAnchor") {
407+
if (typeof bounded === "string" && ANCHOR_PATTERN.test(bounded)) out[key] = bounded
408+
continue
409+
}
410+
if (key === "$id") {
411+
if (typeof bounded === "string" && isResolvableId(bounded)) out[key] = bounded
412+
continue
413+
}
414+
if (key === "$schema") {
415+
if (typeof bounded === "string" && KNOWN_DIALECTS.has(bounded)) out[key] = bounded
416+
continue
417+
}
418+
if (key === "$vocabulary") {
419+
if (!isPlainObject(bounded)) continue
420+
const clean = makeRecord()
421+
for (const [vocabulary, flag] of Object.entries(bounded)) {
422+
if (typeof flag === "boolean") clean[vocabulary] = flag
423+
}
424+
out[key] = clean
425+
continue
426+
}
358427
if (SCHEMA_ARRAY_KEYWORDS.has(key)) {
359428
// Array members must themselves be schemas (object or boolean). `prefixItems` already
360429
// filters, but `anyOf`/`oneOf`/`allOf` emitted a non-schema member verbatim, which is

‎packages/opencode/src/project/instance-store.ts‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,22 @@ interface Entry {
3838
disposed: boolean
3939
/** Resolves when a claimed teardown finished and the entry left the cache. */
4040
readonly closed: Deferred.Deferred<void>
41+
/**
42+
* Resolves when this entry's directory-global `runDisposers` settles, even if the teardown
43+
* fiber was interrupted while it was in flight.
44+
*/
45+
readonly teardown: Deferred.Deferred<void>
46+
/** Whether this entry's claim reached `runDisposers`, so `teardown` settles on its own. */
47+
teardownStarted: boolean
4148
}
4249

4350
const makeEntry = (): Entry => ({
4451
deferred: Deferred.makeUnsafe<InstanceContext>(),
4552
uses: 0,
4653
disposed: false,
4754
closed: Deferred.makeUnsafe<void>(),
55+
teardown: Deferred.makeUnsafe<void>(),
56+
teardownStarted: false,
4857
})
4958

5059
const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Service> = Layer.effect(
@@ -57,6 +66,10 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
5766
// file-search index), so the cache is bounded and evicts the oldest done entry.
5867
const MAX_CACHED_INSTANCES = 16
5968
const cache = new Map<string, Entry>()
69+
// Disposers are directory-global and keep running after an interrupt, even though the
70+
// interrupted entry has already left `cache`. Track those in-flight teardowns by directory
71+
// so a `reload` can wait for them before booting a replacement (NEW-V12-06).
72+
const teardowns = new Map<string, Set<Entry>>()
6073

6174
const boot = (input: LoadInput & { directory: string }) =>
6275
Effect.gen(function* () {
@@ -118,19 +131,48 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
118131
}),
119132
)
120133

121-
const disposeContext = Effect.fn("InstanceStore.disposeContext")(function* (ctx: InstanceContext) {
134+
const disposeContext = Effect.fn("InstanceStore.disposeContext")(function* (ctx: InstanceContext, entry?: Entry) {
122135
yield* Effect.logInfo("disposing instance", { directory: ctx.directory })
123-
yield* Effect.promise(() => runDisposers(ctx.directory))
136+
const teardown = yield* Effect.sync(() => {
137+
const promise = runDisposers(ctx.directory)
138+
if (entry) {
139+
entry.teardownStarted = true
140+
const pending = teardowns.get(ctx.directory) ?? new Set<Entry>()
141+
pending.add(entry)
142+
teardowns.set(ctx.directory, pending)
143+
const settle = () => {
144+
const active = teardowns.get(ctx.directory)
145+
if (active) {
146+
active.delete(entry)
147+
if (active.size === 0) teardowns.delete(ctx.directory)
148+
}
149+
Deferred.doneUnsafe(entry.teardown, Effect.void)
150+
}
151+
promise.then(settle, settle)
152+
}
153+
return promise
154+
})
155+
yield* Effect.promise(() => teardown)
124156
yield* emitDisposed({ directory: ctx.directory, project: ctx.project.id })
125157
})
126158

159+
const awaitTeardowns = (directory: string) =>
160+
Effect.gen(function* () {
161+
const pending = teardowns.get(directory)
162+
if (!pending || pending.size === 0) return
163+
yield* Effect.forEach([...pending], (entry) => Deferred.await(entry.teardown), { discard: true })
164+
})
165+
127166
// Release a claimed entry: drop it from the cache (only if it is still the cached one, so a
128167
// reload that already installed a replacement is not clobbered) and resolve `closed` so a
129168
// `provide` waiting on the claim can reload. Must be uninterruptible: the whole point is that
130169
// this runs even when the teardown around it is interrupted or times out (REGRESSION-2).
131170
const releaseClaim = (directory: string, entry: Entry) =>
132171
Effect.uninterruptible(
133172
Effect.gen(function* () {
173+
// A claim interrupted before it reached the disposers has no teardown left to wait
174+
// for; resolve the gate so a reload does not wait on a run that never started.
175+
if (!entry.teardownStarted) yield* Deferred.succeed(entry.teardown, undefined)
134176
if (cache.get(directory) === entry) cache.delete(directory)
135177
yield* Deferred.succeed(entry.closed, undefined)
136178
}),
@@ -164,7 +206,7 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
164206
// awaited `closed` forever (REGRESSION-2). The finalizer must always run.
165207
yield* Effect.gen(function* () {
166208
yield* awaitLease(entry)
167-
yield* disposeContext(ctx)
209+
yield* disposeContext(ctx, entry)
168210
}).pipe(Effect.ensuring(releaseClaim(directory, entry)))
169211
return true
170212
})
@@ -237,6 +279,11 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
237279
// to serialize reload against a claimed entry.
238280
yield* Deferred.await(previous.closed)
239281
}
282+
// An interrupted teardown resolves `closed` immediately while its disposers keep
283+
// running, and its entry is already gone from the cache, so the check above cannot
284+
// see it. Wait for every directory-global teardown still in flight before booting
285+
// the replacement (NEW-V12-06).
286+
yield* awaitTeardowns(directory)
240287
yield* completeLoad(directory, input, entry)
241288
}).pipe(Effect.forkIn(scope, { startImmediately: true }))
242289
return yield* restore(Deferred.await(entry.deferred))

‎packages/opencode/test/mcp/catalog.test.ts‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,132 @@ describe("McpCatalog.convertTool bounds untrusted server input", () => {
496496
expect(() => new Ajv2020({ strict: false }).compile(schema)).not.toThrow()
497497
})
498498

499+
test("never emits a schema map whose hostile keys inject a prototype", () => {
500+
const schema = emitted(
501+
JSON.parse(
502+
'{"type":"object","properties":{"__proto__":{"type":"string"},"constructor":{"type":"number"},"prototype":{"type":"boolean"}},"$defs":{"__proto__":{"type":"string"}}}',
503+
),
504+
)
505+
const properties = schema.properties as Record<string, unknown>
506+
const defs = schema.$defs as Record<string, unknown>
507+
508+
expect(Object.hasOwn(properties, "__proto__")).toBe(true)
509+
expect(Object.hasOwn(properties, "constructor")).toBe(true)
510+
expect(Object.hasOwn(properties, "prototype")).toBe(true)
511+
expect(Object.hasOwn(defs, "__proto__")).toBe(true)
512+
expect(Object.getPrototypeOf(properties)).not.toBe(Object.prototype)
513+
expect(Object.keys(Object.prototype)).toEqual([])
514+
expect(() => new Ajv2020({ strict: false }).compile(schema)).not.toThrow()
515+
})
516+
517+
test("drops keyword values that make the emitted document uncompilable", () => {
518+
const hostile: Array<[string, Record<string, unknown>]> = [
519+
["invalid $anchor", { type: "object", properties: { p: { $anchor: "not valid!" } } }],
520+
["invalid $dynamicAnchor", { type: "object", properties: { p: { $dynamicAnchor: "1bad" } } }],
521+
["invalid root $anchor", { $anchor: "bad name", type: "object" }],
522+
["invalid anchor in $defs", { type: "object", $defs: { D: { $anchor: "1 bad", type: "string" } } }],
523+
["$anchor wrong type", { type: "object", properties: { p: { $anchor: 5 } } }],
524+
["$schema wrong type", { $schema: 5, type: "object" }],
525+
["$schema bogus", { $schema: "bogus", type: "object" }],
526+
["$schema unresolvable dialect", { $schema: "https://json-schema.org/draft/2019-09/schema", type: "object" }],
527+
["nested bogus $schema", { type: "object", properties: { p: { $schema: "bogus" } } }],
528+
["$vocabulary wrong type", { type: "object", $vocabulary: 5 }],
529+
[
530+
"$vocabulary non-boolean member",
531+
{ type: "object", $vocabulary: { "https://json-schema.org/draft/2020-12/vocab/core": 5 } },
532+
],
533+
["invalid patternProperties key", { type: "object", patternProperties: { "(": { type: "string" } } }],
534+
["invalid nested patternProperties key", { type: "object", properties: { p: { patternProperties: { "[a": {} } } } }],
535+
["non-string title", { type: "object", title: 7 }],
536+
["non-string description", { type: "object", description: [] }],
537+
["non-string nested title", { type: "object", properties: { p: { title: 7 } } }],
538+
[
539+
"malformed urn $id",
540+
{
541+
$id: "urn:root",
542+
type: "object",
543+
$defs: { A: { type: "string" } },
544+
properties: { a: { $ref: "#/$defs/A" } },
545+
},
546+
],
547+
["interior fragment $id", { $id: "foo#bar", type: "object" }],
548+
["$schema inside contentSchema", { type: "object", properties: { p: { contentSchema: { $schema: 5 } } } }],
549+
[
550+
"invalid anchor inside contentSchema",
551+
{ type: "object", properties: { p: { contentSchema: { $anchor: "no good" } } } },
552+
],
553+
["title inside contentSchema", { type: "object", properties: { p: { contentSchema: { title: 7 } } } }],
554+
[
555+
"hostile keywords inside $defs and allOf members",
556+
{
557+
type: "object",
558+
$defs: { D: { $schema: "bogus", title: 7, patternProperties: { "(": {} } } },
559+
properties: { p: { allOf: [{ $anchor: "bad name" }, { $vocabulary: 5 }] } },
560+
},
561+
],
562+
]
563+
564+
for (const [label, input] of hostile) {
565+
const schema = emitted(input)
566+
try {
567+
new Ajv2020({ strict: false }).compile(schema)
568+
} catch (error) {
569+
throw new Error(`${label}: ${(error as Error).message}\n${JSON.stringify(schema)}`)
570+
}
571+
}
572+
})
573+
574+
test("preserves resolvable dialects, anchors, ids and string metadata", () => {
575+
const schema = emitted({
576+
$schema: "https://json-schema.org/draft/2020-12/schema",
577+
$id: "https://example.com/schema.json",
578+
title: "Tool",
579+
description: "A tool",
580+
type: "object",
581+
properties: {
582+
p: {
583+
$anchor: "good-anchor_1",
584+
patternProperties: { "^a": { type: "string" } },
585+
},
586+
urn: { $id: "urn:example:x", type: "string" },
587+
},
588+
$vocabulary: { "https://json-schema.org/draft/2020-12/vocab/core": true, dropped: 5 },
589+
})
590+
591+
expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema")
592+
expect(schema.$id).toBe("https://example.com/schema.json")
593+
expect(schema.title).toBe("Tool")
594+
expect(schema.description).toBe("A tool")
595+
expect(schema.$vocabulary).toEqual({ "https://json-schema.org/draft/2020-12/vocab/core": true })
596+
const props = schema.properties as Record<string, Record<string, unknown>>
597+
expect(props.p.$anchor).toBe("good-anchor_1")
598+
expect(props.p.patternProperties).toEqual({ "^a": { type: "string" } })
599+
expect(props.urn.$id).toBe("urn:example:x")
600+
expect(() => new Ajv2020({ strict: false }).compile(schema)).not.toThrow()
601+
})
602+
603+
test("sanitizes the same keyword families at every container", () => {
604+
const schema = emitted({
605+
type: "object",
606+
$defs: { D: { title: 7, $anchor: "bad name", patternProperties: { "(": {} } } },
607+
patternProperties: { "[a": { title: 7 }, "^ok": { $anchor: "fine_1" } },
608+
properties: { p: { contentSchema: { $schema: 5, title: 7 }, items: { $vocabulary: 5 } } },
609+
})
610+
const defs = schema.$defs as Record<string, Record<string, unknown>>
611+
const patterns = schema.patternProperties as Record<string, Record<string, unknown>>
612+
const p = (schema.properties as Record<string, Record<string, unknown>>).p
613+
614+
expect(defs.D.title).toBeUndefined()
615+
expect(defs.D.$anchor).toBeUndefined()
616+
expect(defs.D.patternProperties).toEqual({})
617+
expect(Object.hasOwn(patterns, "[a")).toBe(false)
618+
expect(patterns["^ok"].$anchor).toBe("fine_1")
619+
expect((p.contentSchema as Record<string, unknown>).$schema).toBeUndefined()
620+
expect((p.contentSchema as Record<string, unknown>).title).toBeUndefined()
621+
expect((p.items as Record<string, unknown>).$vocabulary).toBeUndefined()
622+
expect(() => new Ajv2020({ strict: false }).compile(schema)).not.toThrow()
623+
})
624+
499625
test("accepts only refs that resolve from the top-level document", () => {
500626
const schema = emitted({
501627
type: "object",

0 commit comments

Comments
 (0)