GeezerVison is showing github.com — fix(opencode): close audit-v12 wave I-B instance-store reload + mcp c… · anomalyco/opencode@88777b8
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/mcp/catalog.ts +74-5Lines changed: 74 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -237,15 +237,49 @@ const STRING_KEYWORDS = new Set([ | 237 | 237 | "contentEncoding", | 238 | 238 | "contentMediaType", | 239 | 239 | "$comment", | 240 | | - "$id", | 241 | | - "$anchor", | 242 | | - "$dynamicAnchor", | | 240 | + "title", | | 241 | + "description", | 243 | 242 | ]) | 244 | 243 | const BOOLEAN_KEYWORDS = new Set(["uniqueItems", "deprecated", "readOnly", "writeOnly"]) | 245 | 244 |
| | 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 | + | 246 | 277 | const isPlainObject = (value: unknown): value is Record<string, unknown> => | 247 | 278 | typeof value === "object" && value !== null && !Array.isArray(value) | 248 | 279 | 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> | 249 | 283 |
| 250 | 284 | // Schemas, maps of schemas (`properties`/`$defs`) and instance data (`enum`/`const`) | 251 | 285 | // all recurse through `boundSchema`. Only real schema nodes are sanitized; without the | @@ -275,7 +309,7 @@ function boundSchema( | 275 | 309 | if (value.length > 0 && bounded.length === 0) return BOUNDED | 276 | 310 | return bounded | 277 | 311 | } | 278 | | - const out: Record<string, unknown> = {} | | 312 | + const out = makeRecord() | 279 | 313 | for (const [key, item] of Object.entries(value)) { | 280 | 314 | // Draft-07 tuple form (`items: [a, b]`) is invalid under 2020-12, where `items` | 281 | 315 | // must be a single schema. Normalize conservatively to an unconstrained schema | @@ -296,6 +330,20 @@ function boundSchema( | 296 | 330 | if (kept.length > 0) out[key] = kept | 297 | 331 | continue | 298 | 332 | } | | 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 | + } | 299 | 347 | const childKind: SchemaKind = | 300 | 348 | kind === "map" | 301 | 349 | ? "schema" | @@ -336,7 +384,7 @@ function boundSchema( | 336 | 384 | } | 337 | 385 | if (key === "dependentRequired") { | 338 | 386 | if (!isPlainObject(bounded)) continue | 339 | | - const clean: Record<string, string[]> = {} | | 387 | + const clean = makeRecord() as Record<string, string[]> | 340 | 388 | for (const [name, names] of Object.entries(bounded)) { | 341 | 389 | if (!Array.isArray(names)) continue | 342 | 390 | const kept = names.filter((entry): entry is string => typeof entry === "string") | @@ -355,6 +403,27 @@ function boundSchema( | 355 | 403 | if (typeof bounded === "string" && bounded.startsWith("#")) out[key] = bounded | 356 | 404 | continue | 357 | 405 | } | | 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 | + } | 358 | 427 | if (SCHEMA_ARRAY_KEYWORDS.has(key)) { | 359 | 428 | // Array members must themselves be schemas (object or boolean). `prefixItems` already | 360 | 429 | // filters, but `anyOf`/`oneOf`/`allOf` emitted a non-schema member verbatim, which is | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/project/instance-store.ts +50-3Lines changed: 50 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -38,13 +38,22 @@ interface Entry { | 38 | 38 | disposed: boolean | 39 | 39 | /** Resolves when a claimed teardown finished and the entry left the cache. */ | 40 | 40 | 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 | 41 | 48 | } | 42 | 49 |
| 43 | 50 | const makeEntry = (): Entry => ({ | 44 | 51 | deferred: Deferred.makeUnsafe<InstanceContext>(), | 45 | 52 | uses: 0, | 46 | 53 | disposed: false, | 47 | 54 | closed: Deferred.makeUnsafe<void>(), | | 55 | + teardown: Deferred.makeUnsafe<void>(), | | 56 | + teardownStarted: false, | 48 | 57 | }) | 49 | 58 |
| 50 | 59 | 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 | 57 | 66 | // file-search index), so the cache is bounded and evicts the oldest done entry. | 58 | 67 | const MAX_CACHED_INSTANCES = 16 | 59 | 68 | 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>>() | 60 | 73 |
| 61 | 74 | const boot = (input: LoadInput & { directory: string }) => | 62 | 75 | Effect.gen(function* () { | @@ -118,19 +131,48 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser | 118 | 131 | }), | 119 | 132 | ) | 120 | 133 |
| 121 | | - const disposeContext = Effect.fn("InstanceStore.disposeContext")(function* (ctx: InstanceContext) { | | 134 | + const disposeContext = Effect.fn("InstanceStore.disposeContext")(function* (ctx: InstanceContext, entry?: Entry) { | 122 | 135 | 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) | 124 | 156 | yield* emitDisposed({ directory: ctx.directory, project: ctx.project.id }) | 125 | 157 | }) | 126 | 158 |
| | 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 | + | 127 | 166 | // Release a claimed entry: drop it from the cache (only if it is still the cached one, so a | 128 | 167 | // reload that already installed a replacement is not clobbered) and resolve `closed` so a | 129 | 168 | // `provide` waiting on the claim can reload. Must be uninterruptible: the whole point is that | 130 | 169 | // this runs even when the teardown around it is interrupted or times out (REGRESSION-2). | 131 | 170 | const releaseClaim = (directory: string, entry: Entry) => | 132 | 171 | Effect.uninterruptible( | 133 | 172 | 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) | 134 | 176 | if (cache.get(directory) === entry) cache.delete(directory) | 135 | 177 | yield* Deferred.succeed(entry.closed, undefined) | 136 | 178 | }), | @@ -164,7 +206,7 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser | 164 | 206 | // awaited `closed` forever (REGRESSION-2). The finalizer must always run. | 165 | 207 | yield* Effect.gen(function* () { | 166 | 208 | yield* awaitLease(entry) | 167 | | - yield* disposeContext(ctx) | | 209 | + yield* disposeContext(ctx, entry) | 168 | 210 | }).pipe(Effect.ensuring(releaseClaim(directory, entry))) | 169 | 211 | return true | 170 | 212 | }) | @@ -237,6 +279,11 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser | 237 | 279 | // to serialize reload against a claimed entry. | 238 | 280 | yield* Deferred.await(previous.closed) | 239 | 281 | } | | 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) | 240 | 287 | yield* completeLoad(directory, input, entry) | 241 | 288 | }).pipe(Effect.forkIn(scope, { startImmediately: true })) | 242 | 289 | return yield* restore(Deferred.await(entry.deferred)) | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/test/mcp/catalog.test.ts +126Lines changed: 126 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -496,6 +496,132 @@ describe("McpCatalog.convertTool bounds untrusted server input", () => { | 496 | 496 | expect(() => new Ajv2020({ strict: false }).compile(schema)).not.toThrow() | 497 | 497 | }) | 498 | 498 |
| | 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 | + | 499 | 625 | test("accepts only refs that resolve from the top-level document", () => { | 500 | 626 | const schema = emitted({ | 501 | 627 | type: "object", | |
|