This repository has been archived on 2026-11-17. You can view files and clone it, but cannot push or open issues or pull requests.
gitgram-ai/gitgram/backend/tests/trendingConfigRouteAuthz.test.ts
caelum0x 14b1fe6b2c feat: build out + functionally verify all 7 subprojects to working state
Autonomous multi-agent build/verify drive across gitgram + aitimemachine.
All 7 subprojects now build and run; agents fixed real defects throughout.

Backend (gitgram/backend):
- Migrate to Express 5 typing (ambient .d.ts shims for express-rate-limit,
  @apollo/server, @trpc/server that resolve Express 5 types under workspace
  hoisting); fix 2 real GraphQL typing defects; scope typeRoots to local types
- Fix startup crash (missing `buffer` pkg required by nsfwjs)
- Install ioredis + web-push; build clean, boots (HTTP 200), 1241/1266 tests

Web (gitgram/web): next build green (fix route-slug conflict, remove dead
lib/trpc.ts); document monorepo dual-React vitest harness limitation (71/86)

Mobile (gitgram/mobile): port proximity-unique features (org, starred,
reading-list, languages, snippets) onto modern expo-router + axios stack;
exclude standalone proximity/ from tsconfig + jest; typecheck clean, 8/8 tests

AITM core: fix CLI crash from duplicate command registrations (vendored merge);
secure 2 unauthenticated API routes; 520/520 tests
AITM api-server: fix ioredis construct + a2a SDK decls + test mocks; 715/715
AITM mcp: fix TS5076 syntax + slow gitnexus import; 63/63
AITM website: next build green (88 routes)

Root deps: fix broken @types/uuid stub (real v9), relax override to $@types/uuid

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 04:10:22 +03:00

177 lines
5.7 KiB
TypeScript

const authMock = (req: any, res: any, next: any) => {
if (req.header('x-auth-mode') === 'ok') {
req.userId = 'user_test';
return next();
}
return res.status(401).json({ error: 'Authentication required' });
};
const requireRoleMock = (..._roles: string[]) => {
return (req: any, res: any, next: any) => {
if (req.header('x-role-mode') === 'allow') return next();
return res.status(403).json({ error: 'Insufficient permissions' });
};
};
jest.mock('../src/middleware/auth', () => ({
authenticate: authMock,
optionalAuth: (_req: any, _res: any, next: any) => next(),
}));
jest.mock('../src/middleware/authorization', () => ({
requireRole: requireRoleMock,
}));
jest.mock('../src/controllers/trendingController', () => ({
trendingController: {
getTrending: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingPosts: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingRepos: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingCreators: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingRepositories: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingUsers: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingTags: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingHashtags: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingDevelopers: (_req: any, res: any) => res.status(200).json({ ok: true }),
getTrendingSnippets: (_req: any, res: any) => res.status(200).json({ ok: true }),
getSignalConfig: (_req: any, res: any) => res.status(200).json({ success: true, data: [] }),
updateSignalConfig: (_req: any, res: any) => res.status(200).json({ success: true }),
},
}));
import trendingRoutes from '../src/routes/trending';
function getHandlers(
router: any,
method: 'get' | 'put',
path: string
): Array<(req: any, res: any, next: any) => any> {
const layer = router.stack.find((l: any) => l.route?.path === path && l.route?.methods?.[method]);
if (!layer) throw new Error(`Route ${method.toUpperCase()} ${path} not found`);
return layer.route.stack.map((s: any) => s.handle);
}
function createReq(input: {
headers?: Record<string, string>;
body?: any;
params?: Record<string, string>;
query?: Record<string, string>;
}) {
const normalized: Record<string, string> = {};
for (const [k, v] of Object.entries(input.headers || {})) normalized[k.toLowerCase()] = v;
return {
headers: normalized,
body: input.body || {},
params: input.params || {},
query: input.query || {},
header(name: string) {
return this.headers[name.toLowerCase()];
},
};
}
function createRes() {
return {
statusCode: 200,
body: undefined as any,
ended: false,
status(code: number) {
this.statusCode = code;
return this;
},
json(payload: any) {
this.body = payload;
this.ended = true;
return this;
},
};
}
async function runRoute(
handlers: Array<(req: any, res: any, next: any) => any>,
input: { headers?: Record<string, string>; body?: any; params?: Record<string, string>; query?: Record<string, string> } = {}
) {
const req = createReq(input);
const res = createRes();
const invoke = async (index: number): Promise<void> => {
if (index >= handlers.length || res.ended) return;
await new Promise<void>((resolve, reject) => {
let nextCalled = false;
const next = (err?: any) => {
if (err) return reject(err);
nextCalled = true;
resolve();
};
try {
const out = handlers[index](req, res, next);
Promise.resolve(out)
.then(() => {
if (!nextCalled) resolve();
})
.catch(reject);
} catch (error) {
reject(error);
}
});
return invoke(index + 1);
};
await invoke(0);
return res;
}
describe('Trending config route authz', () => {
const configGetHandlers = getHandlers(trendingRoutes, 'get', '/config');
const configPutHandlers = getHandlers(trendingRoutes, 'put', '/config/:signalName');
it('returns 401 for unauthenticated signal config read', async () => {
const res = await runRoute(configGetHandlers);
expect(res.statusCode).toBe(401);
});
it('returns 401 for unauthenticated signal config update', async () => {
const res = await runRoute(configPutHandlers, {
params: { signalName: 'post_likes' },
body: { weight: 2.1 },
});
expect(res.statusCode).toBe(401);
});
it('returns 403 for authenticated non-admin signal config read', async () => {
const res = await runRoute(configGetHandlers, {
headers: { 'x-auth-mode': 'ok', 'x-role-mode': 'deny' },
});
expect(res.statusCode).toBe(403);
});
it('returns 403 for authenticated non-admin signal config update', async () => {
const res = await runRoute(configPutHandlers, {
headers: { 'x-auth-mode': 'ok', 'x-role-mode': 'deny' },
params: { signalName: 'post_likes' },
body: { weight: 2.1 },
});
expect(res.statusCode).toBe(403);
});
it('returns 200 for admin signal config read', async () => {
const res = await runRoute(configGetHandlers, {
headers: { 'x-auth-mode': 'ok', 'x-role-mode': 'allow' },
});
expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
});
it('returns 200 for admin signal config update', async () => {
const res = await runRoute(configPutHandlers, {
headers: { 'x-auth-mode': 'ok', 'x-role-mode': 'allow' },
params: { signalName: 'post_likes' },
body: { weight: 2.1 },
});
expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
});
});