Skip to content

Commit f4019ca

Browse files
authored
fix(github): support immutable OIDC subjects (anomalyco#44776)
1 parent f8b4dd7 commit f4019ca

6 files changed

Lines changed: 97 additions & 31 deletions

File tree

‎packages/function/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
"private": true,
66
"type": "module",
77
"license": "MIT",
8+
"scripts": {
9+
"test": "bun test"
10+
},
811
"devDependencies": {
912
"@cloudflare/workers-types": "catalog:",
1013
"@tsconfig/node22": "22.0.2",

‎packages/function/src/api.ts‎

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { jwtVerify, createRemoteJWKSet } from "jose"
55
import { createAppAuth } from "@octokit/auth-app"
66
import { Octokit } from "@octokit/rest"
77
import { Resource } from "sst"
8+
import { parseRepositoryClaim } from "./github"
89

910
type Env = {
1011
SYNC_SERVER: DurableObjectNamespace<SyncServer>
@@ -269,42 +270,41 @@ export default new Hono<{ Bindings: Env }>()
269270

270271
// verify token
271272
const JWKS = createRemoteJWKSet(new URL(JWKS_URL))
272-
let owner, repo
273+
let repository: ReturnType<typeof parseRepositoryClaim>
273274
try {
274275
const { payload } = await jwtVerify(token, JWKS, {
275276
issuer: GITHUB_ISSUER,
276277
audience: EXPECTED_AUDIENCE,
277278
})
278-
const sub = payload.sub // e.g. 'repo:my-org/my-repo:ref:refs/heads/main'
279-
const parts = sub.split(":")[1].split("/")
280-
owner = parts[0]
281-
repo = parts[1]
279+
repository = parseRepositoryClaim(payload)
282280
} catch (err) {
283281
console.error("Token verification failed:", err)
284282
return c.json({ error: "Invalid or expired token" }, { status: 403 })
285283
}
286284

287-
// Create app JWT token
288-
const auth = createAppAuth({
289-
appId: Resource.GITHUB_APP_ID.value,
290-
privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
291-
})
292-
const appAuth = await auth({ type: "app" })
293-
294-
// Lookup installation
295-
const octokit = new Octokit({ auth: appAuth.token })
296-
const { data: installation } = await octokit.apps.getRepoInstallation({
297-
owner,
298-
repo,
299-
})
300-
301-
// Get installation token
302-
const installationAuth = await auth({
303-
type: "installation",
304-
installationId: installation.id,
305-
})
306-
307-
return c.json({ token: installationAuth.token })
285+
try {
286+
const auth = createAppAuth({
287+
appId: Resource.GITHUB_APP_ID.value,
288+
privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
289+
})
290+
const appAuth = await auth({ type: "app" })
291+
const octokit = new Octokit({ auth: appAuth.token })
292+
const { data: installation } = await octokit.apps.getRepoInstallation({
293+
owner: repository.owner,
294+
repo: repository.repo,
295+
})
296+
const installationAuth = await auth({
297+
type: "installation",
298+
installationId: installation.id,
299+
})
300+
return c.json({ token: installationAuth.token })
301+
} catch (error) {
302+
console.error("GitHub App token exchange failed:", error)
303+
return c.json(
304+
{ error: `Failed to exchange GitHub App token for ${repository.owner}/${repository.repo}` },
305+
{ status: 502 },
306+
)
307+
}
308308
})
309309
/**
310310
* Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally)

‎packages/function/src/github.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import type { JWTPayload } from "jose"
2+
3+
export function parseRepositoryClaim(payload: JWTPayload) {
4+
const claim = payload.repository
5+
if (typeof claim !== "string") throw new Error("Repository claim is missing")
6+
7+
const parts = claim.split("/")
8+
if (parts.length !== 2 || !parts[0] || !parts[1]) throw new Error("Repository claim is invalid")
9+
10+
return {
11+
owner: parts[0],
12+
repo: parts[1],
13+
}
14+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { parseRepositoryClaim } from "../src/github"
3+
4+
describe("parseRepositoryClaim", () => {
5+
test("reads repository identity with a legacy subject", () => {
6+
expect(
7+
parseRepositoryClaim({
8+
repository: "octocat/my-repo",
9+
sub: "repo:octocat/my-repo:ref:refs/heads/main",
10+
}),
11+
).toEqual({ owner: "octocat", repo: "my-repo" })
12+
})
13+
14+
test("reads repository identity with an immutable subject", () => {
15+
expect(
16+
parseRepositoryClaim({
17+
repository: "octocat/my-repo",
18+
sub: "repo:octocat@123456/my-repo@456789:ref:refs/heads/main",
19+
}),
20+
).toEqual({ owner: "octocat", repo: "my-repo" })
21+
})
22+
23+
test("does not depend on a repository path in a customized subject", () => {
24+
expect(
25+
parseRepositoryClaim({
26+
repository: "octocat/my-repo",
27+
sub: "repository_owner:octocat:repository_visibility:private",
28+
}),
29+
).toEqual({ owner: "octocat", repo: "my-repo" })
30+
})
31+
32+
test("rejects a missing repository claim", () => {
33+
expect(() => parseRepositoryClaim({})).toThrow("Repository claim is missing")
34+
})
35+
36+
test("rejects an invalid repository claim", () => {
37+
expect(() => parseRepositoryClaim({ repository: "octocat" })).toThrow("Repository claim is invalid")
38+
})
39+
})

‎packages/opencode/src/cli/cmd/github.handler.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,7 @@ export const githubRun = Effect.fn("Cli.github.run")(function* (args: { event?:
437437
let session: { id: SessionID; title: string; version: string }
438438
let shareId: string | undefined
439439
let exitCode = 0
440+
let githubClientReady = false
440441
type PromptFiles = Awaited<ReturnType<typeof getUserPrompt>>["promptFiles"]
441442
const triggerCommentId = isCommentEvent
442443
? (payload as IssueCommentEvent | PullRequestReviewCommentEvent).comment.id
@@ -485,6 +486,7 @@ export const githubRun = Effect.fn("Cli.github.run")(function* (args: { event?:
485486
octoGraph = graphql.defaults({
486487
headers: { authorization: `token ${appToken}` },
487488
})
489+
githubClientReady = true
488490

489491
const { userPrompt, promptFiles } = await getUserPrompt()
490492
if (!useGithubToken) {
@@ -639,9 +641,13 @@ export const githubRun = Effect.fn("Cli.github.run")(function* (args: { event?:
639641
} else if (e instanceof Error) {
640642
msg = e.message
641643
}
642-
if (isUserEvent) {
643-
await createComment(`${msg}${footer()}`)
644-
await removeReaction(commentType)
644+
if (isUserEvent && githubClientReady) {
645+
try {
646+
await createComment(`${msg}${footer()}`)
647+
await removeReaction(commentType)
648+
} catch (error) {
649+
console.error("Failed to report error on GitHub:", error)
650+
}
645651
}
646652
core.setFailed(msg)
647653
// Also output the clean error message for the action to capture
@@ -1004,8 +1010,9 @@ export const githubRun = Effect.fn("Cli.github.run")(function* (args: { event?:
10041010
})
10051011

10061012
if (!response.ok) {
1007-
const responseJson = (await response.json()) as { error?: string }
1008-
throw new Error(`App token exchange failed: ${response.status} ${response.statusText} - ${responseJson.error}`)
1013+
throw new Error(
1014+
`App token exchange failed: ${response.status} ${response.statusText} - ${await response.text()}`,
1015+
)
10091016
}
10101017

10111018
const responseJson = (await response.json()) as { token: string }

‎turbo.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
"dependsOn": ["^build"],
1818
"outputs": []
1919
},
20+
"@opencode-ai/function#test": {
21+
"outputs": []
22+
},
2023
"@opencode-ai/app#test": {
2124
"dependsOn": ["^build"],
2225
"outputs": []

0 commit comments

Comments
 (0)