Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions apps/web/src/app/api/auth/resource-token/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { NextRequest } from 'next/server';
import { createDelegatedResourceToken } from '@/lib/auth/resource-delegation';
import { POST } from './route';

jest.mock('@/lib/user/server', () => ({
getUserFromAuth: jest.fn(async () => ({ user: { id: 'oauth/test-user' } })),
}));
jest.mock('@/lib/auth/resource-delegation', () => ({
isDelegableResource: (value: string) =>
['api', 'gateway', 'attribution', 'html-deploy'].includes(value),
createDelegatedResourceToken: jest.fn(async () => ({ token: 'delegated', expiresAt: 'expiry' })),
}));

beforeEach(() => jest.clearAllMocks());

it('rejects personal attribution issuance because the reader requires organization claims', async () => {
const response = await POST(
new NextRequest('https://example.test/api/auth/resource-token', {
method: 'POST',
headers: { origin: 'https://example.test' },
body: JSON.stringify({ resource: 'attribution' }),
})
);
expect(response.status).toBe(403);
expect(createDelegatedResourceToken).not.toHaveBeenCalled();
});

it.each(['api', 'gateway', 'html-deploy'])('retains personal %s negotiation', async resource => {
const response = await POST(
new NextRequest('https://example.test/api/auth/resource-token', {
method: 'POST',
headers: { origin: 'https://example.test' },
body: JSON.stringify({ resource }),
})
);
expect(response.status).toBe(200);
expect(createDelegatedResourceToken).toHaveBeenCalledWith(
{ id: 'oauth/test-user' },
resource,
expect.objectContaining({ headers: expect.any(Headers) })
);
});
59 changes: 59 additions & 0 deletions apps/web/src/app/api/auth/resource-token/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { getUserFromAuth } from '@/lib/user/server';
import {
createDelegatedResourceToken,
isDelegableResource,
TypedResourceDelegationError,
} from '@/lib/auth/resource-delegation';

function isSameOriginRequest(request: NextRequest): boolean {
const origin = request.headers.get('origin');
return origin !== null && origin === request.nextUrl.origin;
}

export async function POST(request: NextRequest) {
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
const resource =
body && typeof body === 'object' && 'resource' in body ? body.resource : undefined;
if (!isDelegableResource(resource)) {
return NextResponse.json({ error: 'Unsupported resource' }, { status: 400 });
}
if (!request.headers.has('authorization') && !isSameOriginRequest(request)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Same-origin guard is skipped by an empty Authorization header

request.headers.has('authorization') is true for an empty header value, so a request carrying Authorization: bypasses isSameOriginRequest. Downstream, getUserFromAuth -> resolveUserFromAuth reads headersList.get('Authorization') (an empty string is falsy) and falls back to session-cookie auth, so such a request is authenticated by cookie without the intended same-origin check. Browsers cannot set this header cross-site, so this is defense-in-depth rather than a live CSRF, but using get('authorization') here would match the auth layer's semantics and close the gap.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

return NextResponse.json({ error: 'Invalid request origin' }, { status: 403 });
}
const { user, authFailedResponse, organizationId, tokenSource } = await getUserFromAuth({
adminOnly: false,
});
if (authFailedResponse) return authFailedResponse;
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
if (organizationId) {
return NextResponse.json(
{ error: 'Organization credentials are not supported' },
{ status: 403 }
);
}
if (resource === 'attribution') {
return NextResponse.json(
{ error: 'Attribution requires an organization resource token' },
{ status: 403 }
);
}
try {
const result = await createDelegatedResourceToken(user, resource, {
headers: request.headers,
tokenSource,
});
return NextResponse.json({ token: result.token, expiresAt: result.expiresAt });
} catch (error) {
if (error instanceof TypedResourceDelegationError) {
return NextResponse.json({ error: error.message }, { status: error.status });
}
throw error;
}
}
Loading