mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 03:15:01 +00:00
fix(cloud): APPROVALS-REFUSED review G1-G4: firewall forwards every App write; unnormalized write paths refused; unreadable GraphQL refused; dismissals, fork-run and environment approvals refused
This commit is contained in:
@@ -5,12 +5,13 @@
|
||||
// mode those requests are forwarded to the proxy for this check instead of being swapped by the firewall.
|
||||
import { Kind, parse, type DocumentNode, type FragmentDefinitionNode, type SelectionSetNode, type ValueNode } from 'graphql'
|
||||
|
||||
const pathOfEarly = (path: string) => (path.split('?')[0] ?? '').toLowerCase()
|
||||
export const APPROVAL_REFUSED_MESSAGE =
|
||||
"Approvals have to be done by a person on GitHub, not from an Orca Cloud workspace. Open the pull request on github.com to approve it."
|
||||
|
||||
/** The answer a refused approval gets: GitHub-shaped JSON for REST, a GraphQL error for /graphql. */
|
||||
export function approvalRefusal(path: string): { deny: string; answer: { status: number; contentType: string; body: string } } {
|
||||
const graphql = (path.split('?')[0] ?? '') === '/graphql'
|
||||
const graphql = pathOfEarly(path) === '/graphql'
|
||||
return {
|
||||
deny: 'approval_refused',
|
||||
answer: {
|
||||
@@ -21,22 +22,76 @@ export function approvalRefusal(path: string): { deny: string; answer: { status:
|
||||
}
|
||||
}
|
||||
|
||||
/** Review G2's refusal: GitHub-shaped, says what to do. */
|
||||
export const UNNORMALIZED_WRITE_REFUSAL = {
|
||||
deny: 'path_not_allowed',
|
||||
answer: { status: 403, contentType: 'application/json', body: JSON.stringify({ message: 'Orca Cloud refused this request: its path has escapes or empty or dot segments. Send the plain path.' }) }
|
||||
}
|
||||
|
||||
/** A pull request review, or a pending review's submission (case-insensitive, optional trailing slash). */
|
||||
export const REVIEW_PATH = /\/pulls\/\d+\/reviews(\/\d+\/events)?\/?$/i
|
||||
/** Dismissing a review (unblocks a merge a REQUEST_CHANGES review was holding). */
|
||||
const DISMISSAL_PATH = /\/pulls\/\d+\/reviews\/\d+\/dismissals\/?$/i
|
||||
/** Approving a fork PR's workflow run, or an environment deployment waiting for review. */
|
||||
const RUN_APPROVAL_PATH = /\/actions\/runs\/\d+\/approve\/?$/i
|
||||
const PENDING_DEPLOYMENTS_PATH = /\/actions\/runs\/\d+\/pending_deployments\/?$/i
|
||||
|
||||
const pathOf = (path: string) => (path.split('?')[0] ?? '').toLowerCase()
|
||||
const writes = (method: string) => !['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())
|
||||
|
||||
/**
|
||||
* Review G2: a write whose path GitHub would normalize differently than these checks read it (percent-escapes, empty
|
||||
* or dot segments) is refused outright, so `/repos/o/r/pulls/7/%72eviews` or `/x/%2e%2e/repos/...` can't slip past.
|
||||
*/
|
||||
export function unnormalizedWrite(method: string, path: string): boolean {
|
||||
if (!writes(method)) {
|
||||
return false
|
||||
}
|
||||
const raw = path.split('?')[0] ?? ''
|
||||
return raw.includes('%') || raw.includes('//') || raw.split('/').some((segment) => segment === '.' || segment === '..')
|
||||
}
|
||||
|
||||
/** Requests whose body the approval check must read (the proxy reads it as text only for these). */
|
||||
export function approvalCheckReadsBody(method: string, path: string): boolean {
|
||||
const pathname = path.split('?')[0] ?? ''
|
||||
return method.toUpperCase() === 'POST' && (pathname === '/graphql' || REVIEW_PATH.test(pathname))
|
||||
if (method.toUpperCase() !== 'POST') {
|
||||
return false
|
||||
}
|
||||
const pathname = pathOf(path)
|
||||
return pathname === '/graphql' || REVIEW_PATH.test(pathname) || PENDING_DEPLOYMENTS_PATH.test(pathname)
|
||||
}
|
||||
|
||||
/** Is this request an approval (REST or GraphQL)? Anything unreadable on those endpoints counts as one. */
|
||||
/** Is this request an approval, or approval-shaped (REST or GraphQL)? Anything unreadable on those counts as one. */
|
||||
export function requestApproves(request: { method: string; path: string; body: string | null }): boolean {
|
||||
const method = request.method.toUpperCase()
|
||||
const pathname = pathOf(request.path)
|
||||
if (method === 'PUT' && DISMISSAL_PATH.test(pathname)) {
|
||||
return true
|
||||
}
|
||||
if (method === 'POST' && RUN_APPROVAL_PATH.test(pathname)) {
|
||||
return true
|
||||
}
|
||||
if (!approvalCheckReadsBody(request.method, request.path)) {
|
||||
return false
|
||||
}
|
||||
const pathname = request.path.split('?')[0] ?? ''
|
||||
return pathname === '/graphql' ? graphqlApproves(request.body) : restApproves(request.body)
|
||||
if (pathname === '/graphql') {
|
||||
return graphqlApproves(request.body)
|
||||
}
|
||||
if (PENDING_DEPLOYMENTS_PATH.test(pathname)) {
|
||||
return deploymentApproves(request.body)
|
||||
}
|
||||
return restApproves(request.body)
|
||||
}
|
||||
|
||||
function deploymentApproves(body: string | null): boolean {
|
||||
if (body === null) {
|
||||
return true
|
||||
}
|
||||
try {
|
||||
const state = (JSON.parse(body) as { state?: unknown } | null)?.state
|
||||
return String(state ?? '').toLowerCase() !== 'rejected'
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
function restApproves(body: string | null): boolean {
|
||||
@@ -52,6 +107,8 @@ function restApproves(body: string | null): boolean {
|
||||
}
|
||||
|
||||
const REVIEW_MUTATIONS = new Set(['addPullRequestReview', 'submitPullRequestReview'])
|
||||
/** Approval-shaped mutations refused whatever their input (review G4). */
|
||||
const ALWAYS_REFUSED_MUTATIONS = new Set(['dismissPullRequestReview'])
|
||||
type Variables = Record<string, unknown>
|
||||
|
||||
/** Fails toward "approves": an unreadable body, or a review mutation whose event can't be resolved. */
|
||||
@@ -63,15 +120,17 @@ export function graphqlApproves(body: string | null): boolean {
|
||||
try {
|
||||
parsed = JSON.parse(body)
|
||||
} catch {
|
||||
return mentionsReviewApproval(body)
|
||||
// Review G3: unreadable (a Content-Encoding'd body never parses as JSON): refused.
|
||||
return true
|
||||
}
|
||||
// Batched requests: any of them.
|
||||
const requests = Array.isArray(parsed) ? parsed : [parsed]
|
||||
return requests.some((request) => requestBodyApproves(request))
|
||||
}
|
||||
|
||||
function mentionsReviewApproval(text: string): boolean {
|
||||
return /addPullRequestReview|submitPullRequestReview/.test(text) && /approve/i.test(text)
|
||||
/** Review G3: a query graphql-js can't parse but GitHub might: refused if it names a review mutation at all. */
|
||||
function mentionsReviewMutation(text: string): boolean {
|
||||
return /addPullRequestReview|submitPullRequestReview|dismissPullRequestReview/i.test(text)
|
||||
}
|
||||
|
||||
function requestBodyApproves(request: unknown): boolean {
|
||||
@@ -86,7 +145,7 @@ function requestBodyApproves(request: unknown): boolean {
|
||||
try {
|
||||
document = parse(query, { noLocation: true, maxTokens: 20_000 })
|
||||
} catch {
|
||||
return mentionsReviewApproval(query)
|
||||
return mentionsReviewMutation(query)
|
||||
}
|
||||
const vars: Variables = variables && typeof variables === 'object' && !Array.isArray(variables) ? (variables as Variables) : {}
|
||||
const fragments = new Map<string, FragmentDefinitionNode>()
|
||||
@@ -115,6 +174,9 @@ function requestBodyApproves(request: unknown): boolean {
|
||||
function selectionsApprove(set: SelectionSetNode, fragments: ReadonlyMap<string, FragmentDefinitionNode>, vars: Variables, seen: Set<string>): boolean {
|
||||
for (const selection of set.selections) {
|
||||
if (selection.kind === Kind.FIELD) {
|
||||
if (ALWAYS_REFUSED_MUTATIONS.has(selection.name.value)) {
|
||||
return true
|
||||
}
|
||||
if (REVIEW_MUTATIONS.has(selection.name.value) && fieldApproves(selection.name.value, selection.arguments ?? [], vars)) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
// Operator (OPERATOR_TOKEN): /v1/internal/* (see operator.ts)
|
||||
// Public share links (src/share-gateway.ts): /s/<token>/*, plus the root-path cookie fallback
|
||||
// Vercel network-policy forwardURL target (Vercel sandbox OIDC): /v1/egress/proxy
|
||||
import { approvalCheckReadsBody, approvalRefusal, requestApproves } from './github-approval-guard'
|
||||
import { UNNORMALIZED_WRITE_REFUSAL, approvalCheckReadsBody, approvalRefusal, requestApproves, unnormalizedWrite } from './github-approval-guard'
|
||||
import { purgeTeamSecrets, teamDeleteRoute, teamWorkspaceCount } from './team-delete'
|
||||
import { ReadSnapshotRouteError, getReadSnapshot, handleReaderKeysRoute, pruneReadSnapshotToOwner, revokeDeviceSessionReaderKeys } from './read-snapshots'
|
||||
import { refreshEnvironment, refreshStaleEnvironments, type GoldenRefreshOptions } from './environment-golden-refresh'
|
||||
@@ -601,7 +601,12 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
|
||||
placeholders: githubPlaceholderHeaders(row),
|
||||
// APPROVALS-REFUSED: the App's token never approves a pull request (it would count as a review).
|
||||
readsBody: approvalCheckReadsBody,
|
||||
credential: async (request) => (requestApproves(request) ? approvalRefusal(request.path) : broker.authorizationFor(row, host))
|
||||
credential: async (request) =>
|
||||
unnormalizedWrite(request.method, request.path)
|
||||
? UNNORMALIZED_WRITE_REFUSAL
|
||||
: requestApproves(request)
|
||||
? approvalRefusal(request.path)
|
||||
: broker.authorizationFor(row, host)
|
||||
},
|
||||
// A user's own GitHub token for Copilot CLI (COPILOT_GITHUB_TOKEN), on its own placeholder.
|
||||
...secretRoutes(row, host)
|
||||
|
||||
@@ -516,18 +516,16 @@ export function egressPolicy(
|
||||
: []),
|
||||
...(appOnFirewall && gitToken
|
||||
? [
|
||||
// APPROVALS-REFUSED: what could be an approval (GraphQL, and POSTs under /repos/, reviews among them)
|
||||
// goes to the proxy, which reads the body and refuses approvals; the firewall swaps the rest.
|
||||
// APPROVALS-REFUSED: every write with the App placeholder goes to the proxy, which reads it and refuses
|
||||
// approvals; only reads (GET/HEAD) are swapped by the firewall. Not scoped by path: the firewall matches
|
||||
// the raw path and GitHub normalizes it (review G1, the #776 lesson).
|
||||
{
|
||||
host: 'api.github.com',
|
||||
header: 'authorization',
|
||||
placeholders: githubPlaceholderHeaders(row),
|
||||
via: 'forward' as const,
|
||||
forwardURL: proxyUrl,
|
||||
paths: [
|
||||
{ exact: '/graphql', methods: ['POST'] },
|
||||
{ startsWith: '/repos/', methods: ['POST'] }
|
||||
]
|
||||
paths: [{ startsWith: '/', methods: ['POST', 'PUT', 'PATCH', 'DELETE'] }]
|
||||
},
|
||||
...githubPlaceholderHeaders(row).map(
|
||||
(placeholder): CredentialRoute => ({
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { ProxiedRoute } from './egress-proxy'
|
||||
import { parseGitHubRepo } from './github-app'
|
||||
import { getUserTokenRow, memberPlaceholder, type MemberGitIdentity } from './github-user-tokens'
|
||||
import { gitBasicAuthorization } from './network-policy'
|
||||
import { approvalCheckReadsBody, approvalRefusal, requestApproves } from './github-approval-guard'
|
||||
import { UNNORMALIZED_WRITE_REFUSAL, approvalCheckReadsBody, approvalRefusal, requestApproves, unnormalizedWrite } from './github-approval-guard'
|
||||
import { MEMBER_OUT_OF_REPO_BODY, NODE_REPOSITORY_QUERY, classifyGraphqlRequest, repositoryIdOfNode, type MemberTarget } from './github-graphql-pin'
|
||||
import { settledCache } from './settled-cache'
|
||||
import type { SandboxRow } from './store'
|
||||
@@ -88,7 +88,7 @@ export function memberGitRoutes(deps: MemberGitDeps) {
|
||||
: {
|
||||
header: 'authorization',
|
||||
placeholders: [`Bearer ${placeholder}`, `token ${placeholder}`],
|
||||
readsBody: (method, path) => (method.toUpperCase() === 'POST' && path.split('?')[0] === '/graphql') || approvalCheckReadsBody(method, path),
|
||||
readsBody: (method, path) => (method.toUpperCase() === 'POST' && (path.split('?')[0] ?? '').toLowerCase() === '/graphql') || approvalCheckReadsBody(method, path),
|
||||
credential: async (request) => memberApiCredential(deps, row, identity, allowed, request)
|
||||
}
|
||||
)
|
||||
@@ -171,7 +171,11 @@ async function memberApiCredential(
|
||||
allowed: (method: string, path: string) => boolean,
|
||||
request: { method: string; path: string; body: string | null }
|
||||
): ReturnType<ProxiedRoute['credential']> {
|
||||
// APPROVALS-REFUSED (github-approval-guard.ts): never from a workspace, on any identity.
|
||||
// APPROVALS-REFUSED (github-approval-guard.ts): never from a workspace, on any identity. A write whose path GitHub
|
||||
// would normalize differently than this check reads it is refused first (review G2).
|
||||
if (unnormalizedWrite(request.method, request.path)) {
|
||||
return UNNORMALIZED_WRITE_REFUSAL
|
||||
}
|
||||
if (requestApproves(request)) {
|
||||
return approvalRefusal(request.path)
|
||||
}
|
||||
|
||||
@@ -61,11 +61,11 @@ describe('EGRESS firewall mode', () => {
|
||||
const git = gitBasicAuthorization(githubPlaceholderToken(row))
|
||||
expect(claims(rules('github.com'), git)[0]).toMatchObject({ transform: [{ headers: { authorization: gitBasicAuthorization(APP_TOKEN) } }] })
|
||||
const [bearer, token] = githubPlaceholderHeaders(row)
|
||||
// APPROVALS-REFUSED: POST /graphql and POSTs under /repos/ go to the proxy first; the firewall swaps the rest.
|
||||
// APPROVALS-REFUSED: every write goes to the proxy first; the firewall swaps reads.
|
||||
const swap = (placeholder: string) => claims(rules('api.github.com'), placeholder).find((rule) => 'transform' in rule)
|
||||
expect(swap(bearer!)).toMatchObject({ transform: [{ headers: { authorization: `Bearer ${APP_TOKEN}` } }] })
|
||||
expect(swap(token!)).toMatchObject({ transform: [{ headers: { authorization: `token ${APP_TOKEN}` } }] })
|
||||
expect(claims(rules('api.github.com'), bearer!)[0]).toMatchObject({ match: { path: { exact: '/graphql' }, method: ['POST'] } })
|
||||
expect(claims(rules('api.github.com'), bearer!)[0]).toMatchObject({ match: { path: { startsWith: '/' }, method: ['POST', 'PUT', 'PATCH', 'DELETE'] } })
|
||||
})
|
||||
|
||||
it('W1: Cursor’s key exchange stays on the egress proxy (its reply is filtered), never in the policy', async () => {
|
||||
@@ -100,7 +100,7 @@ describe('EGRESS firewall mode', () => {
|
||||
expect(JSON.stringify(box().policy.allow['api.anthropic.com'])).not.toContain(ANTHROPIC_KEY)
|
||||
})
|
||||
|
||||
it('APPROVALS-REFUSED: with the App token on the firewall, POST /graphql and POSTs under /repos/ go to the proxy first', async () => {
|
||||
it('APPROVALS-REFUSED: with the App token on the firewall, every write goes to the proxy first, whatever its path', async () => {
|
||||
const { egressPolicy } = await import('../src/lifecycle')
|
||||
const { h } = await setup()
|
||||
const life = (await lifecycleDeps(h.env, h.deps))!
|
||||
@@ -108,11 +108,8 @@ describe('EGRESS firewall mode', () => {
|
||||
const policy = egressPolicy(life, row, 'ghs_app_token', [], { classes: new Set(['github_app']), full: true, accounts: [], secrets: new Map() })
|
||||
const api = policy.allow['api.github.com']!
|
||||
const forwards = api.filter((rule) => 'forwardURL' in rule)
|
||||
expect(forwards.map((rule) => [(rule as { match: { path: unknown; method?: unknown } }).match.path, (rule as { match: { method?: unknown } }).match.method])).toEqual(
|
||||
expect.arrayContaining([
|
||||
[{ exact: '/graphql' }, ['POST']],
|
||||
[{ startsWith: '/repos/' }, ['POST']]
|
||||
])
|
||||
expect(new Set(forwards.map((rule) => JSON.stringify([(rule as { match: { path: unknown } }).match.path, (rule as { match: { method?: unknown } }).match.method])))).toEqual(
|
||||
new Set([JSON.stringify([{ startsWith: '/' }, ['POST', 'PUT', 'PATCH', 'DELETE']])])
|
||||
)
|
||||
// The forwards come before the firewall swap, so they claim those requests first; the token is only in the swap.
|
||||
const firstTransform = api.findIndex((rule) => 'transform' in rule)
|
||||
|
||||
@@ -168,6 +168,11 @@ describe('APPROVALS-REFUSED: no approval leaves a workspace; merges are the owne
|
||||
expect((await app('/repos/acme/app/pulls/7/reviews', { event: 'APPROVE' })).status).toBe(403)
|
||||
expect((await app('/graphql', { query: 'mutation { addPullRequestReview(input: { pullRequestId: "PR_x", event: APPROVE }) { clientMutationId } }' })).status).toBe(403)
|
||||
expect(t.upstream.length).toBe(before)
|
||||
// Review G2/G4: an escaped path or a dismissal is refused too.
|
||||
expect((await app('/repos/acme/app/pulls/7/%72eviews', { event: 'APPROVE' })).status).toBe(403)
|
||||
expect((await t.api('/repos/acme/app/pulls/7/reviews/3/dismissals', 'PUT', { message: 'x' }, `Bearer orca-ph-${t.id}`)).status).toBe(403)
|
||||
expect((await t.api('/repos/acme/app/pulls/7/%72eviews', 'POST', { event: 'APPROVE' })).status).toBe(403)
|
||||
expect(t.upstream.length).toBe(before)
|
||||
expect((await app('/repos/acme/app/issues/7/comments', { body: 'x' })).status).toBe(200)
|
||||
expect(t.upstream.at(-1)!.authorization).toBe(APP)
|
||||
expect((await app('/repos/acme/app/pulls/7/reviews', { event: 'COMMENT', body: 'x' })).status).toBe(200)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// APPROVALS-REFUSED: what counts as an approval on api.github.com, fail-closed on anything unclear.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { graphqlApproves, requestApproves } from '../src/github-approval-guard'
|
||||
import { graphqlApproves, requestApproves, unnormalizedWrite } from '../src/github-approval-guard'
|
||||
|
||||
const gql = (query: string, variables?: unknown, extra: Record<string, unknown> = {}) => JSON.stringify({ query, ...(variables ? { variables } : {}), ...extra })
|
||||
|
||||
@@ -24,7 +24,13 @@ describe('GraphQL approvals', () => {
|
||||
gql('mutation M($i: AddPullRequestReviewInput!) { addPullRequestReview(input: $i) { clientMutationId } }'),
|
||||
gql('mutation { submitPullRequestReview(input: { pullRequestReviewId: "R" }) { clientMutationId } }'),
|
||||
gql('mutation { addPullRequestReview(input: { pullRequestId: "P", event: APPROVE }'),
|
||||
'not json addPullRequestReview APPROVE'
|
||||
'not json addPullRequestReview APPROVE',
|
||||
// Review G3: unreadable is refused (a gzip body never parses); an unparsable query naming a review mutation too,
|
||||
// its event may be in the variables.
|
||||
'\u001f\u008b\u0008binary',
|
||||
gql('mutation M($i: X!) { addPullRequestReview(input: $i) { clientMutationId } ', { i: { pullRequestId: 'P', event: 'APPROVE' } }),
|
||||
// Review G4: dismissing a review unblocks a merge.
|
||||
gql('mutation { dismissPullRequestReview(input: { pullRequestReviewId: "R", message: "x" }) { clientMutationId } }')
|
||||
]) {
|
||||
expect(graphqlApproves(body), body).toBe(true)
|
||||
}
|
||||
@@ -59,3 +65,23 @@ describe('REST approvals', () => {
|
||||
expect(requestApproves({ method: 'GET', path: '/repos/a/b/pulls/1/reviews', body: null })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('review G2 and G4: unnormalized write paths; approval-shaped REST actions', () => {
|
||||
it('a write with escapes, empty or dot segments is refused before any check; reads are untouched', () => {
|
||||
for (const path of ['/repos/o/r/pulls/7/%72eviews', '/x/%2e%2e/repos/o/r/pulls/7/reviews', '//repos/o/r/pulls/7/reviews', '/repos/o/r/./pulls/7/reviews', '/repos/o/r/../r/pulls/7/reviews']) {
|
||||
expect(unnormalizedWrite('POST', path), path).toBe(true)
|
||||
}
|
||||
expect(unnormalizedWrite('GET', '/repos/o/r/%2e%2e')).toBe(false)
|
||||
expect(unnormalizedWrite('POST', '/repos/o/r/issues/7/comments?x=%20')).toBe(false)
|
||||
})
|
||||
|
||||
it('dismissals, fork-run approvals and environment approvals are refused; repository-id routes are covered', () => {
|
||||
expect(requestApproves({ method: 'PUT', path: '/repos/o/r/pulls/7/reviews/9/dismissals', body: '{}' })).toBe(true)
|
||||
expect(requestApproves({ method: 'POST', path: '/repos/o/r/actions/runs/5/approve', body: null })).toBe(true)
|
||||
expect(requestApproves({ method: 'POST', path: '/repos/o/r/actions/runs/5/pending_deployments', body: JSON.stringify({ state: 'approved', environment_ids: [1] }) })).toBe(true)
|
||||
expect(requestApproves({ method: 'POST', path: '/repos/o/r/actions/runs/5/pending_deployments', body: JSON.stringify({ state: 'rejected', environment_ids: [1] }) })).toBe(false)
|
||||
expect(requestApproves({ method: 'POST', path: '/repositories/123/pulls/7/reviews', body: JSON.stringify({ event: 'APPROVE' }) })).toBe(true)
|
||||
expect(requestApproves({ method: 'POST', path: '/GraphQL', body: gql('mutation { addPullRequestReview(input: { pullRequestId: "P", event: APPROVE }) { clientMutationId } }') })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user