diff --git a/src/db/file/pushes.ts b/src/db/file/pushes.ts index 006a8be9b..00f134759 100644 --- a/src/db/file/pushes.ts +++ b/src/db/file/pushes.ts @@ -49,10 +49,34 @@ const defaultPushQuery: Partial = { type: 'push', }; +const pushListProjection = { + _id: 0, + id: 1, + allowPush: 1, + authorised: 1, + blocked: 1, + blockedMessage: 1, + branch: 1, + canceled: 1, + commitData: 1, + commitFrom: 1, + commitTo: 1, + error: 1, + method: 1, + project: 1, + rejected: 1, + repo: 1, + repoName: 1, + timestamp: 1, + type: 1, + url: 1, +}; + export const getPushes = (query: Partial): Promise => { if (!query) query = defaultPushQuery; return new Promise((resolve, reject) => { db.find(query) + .projection(pushListProjection) .sort({ timestamp: -1 }) .exec((err, docs) => { // ignore for code coverage as neDB rarely returns errors even for an invalid query diff --git a/src/service/routes/index.ts b/src/service/routes/index.ts index 80d6c315d..38ebe96bf 100644 --- a/src/service/routes/index.ts +++ b/src/service/routes/index.ts @@ -23,6 +23,7 @@ import users from './users'; import healthcheck from './healthcheck'; import config from './config'; import { jwtAuthHandler } from '../passport/jwtAuthHandler'; +import { ensureAuthenticated } from './middleware'; import { Proxy } from '../../proxy'; const routes = (proxy: Proxy) => { @@ -30,9 +31,9 @@ const routes = (proxy: Proxy) => { router.use('/api', home); router.use('/api/auth', auth.router); router.use('/api/v1/healthcheck', healthcheck); - router.use('/api/v1/push', jwtAuthHandler(), push); - router.use('/api/v1/repo', jwtAuthHandler(), repo(proxy)); - router.use('/api/v1/user', jwtAuthHandler(), users); + router.use('/api/v1/push', jwtAuthHandler(), ensureAuthenticated, push); + router.use('/api/v1/repo', jwtAuthHandler(), ensureAuthenticated, repo(proxy)); + router.use('/api/v1/user', jwtAuthHandler(), ensureAuthenticated, users); router.use('/api/v1/config', config); return router; }; diff --git a/src/service/routes/middleware.ts b/src/service/routes/middleware.ts new file mode 100644 index 000000000..7a8028b6f --- /dev/null +++ b/src/service/routes/middleware.ts @@ -0,0 +1,30 @@ +/** + * Copyright 2026 GitProxy Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Request, Response, NextFunction } from 'express'; + +/** + * Reject unauthenticated requests. Accepts either a passport session + * (req.isAuthenticated()) or a request that a prior auth handler (e.g. JWT) + * has populated with req.user. + */ +export const ensureAuthenticated = (req: Request, res: Response, next: NextFunction): void => { + const sessionAuthed = typeof req.isAuthenticated === 'function' && req.isAuthenticated(); + if (sessionAuthed || req.user) { + return next(); + } + res.status(401).send({ message: 'Authentication required' }); +}; diff --git a/src/ui/views/Login/Login.tsx b/src/ui/views/Login/Login.tsx index 93d4fb720..47bfd6d3b 100644 --- a/src/ui/views/Login/Login.tsx +++ b/src/ui/views/Login/Login.tsx @@ -28,7 +28,7 @@ import CardBody from '../../components/Card/CardBody'; import CardFooter from '../../components/Card/CardFooter'; import axios, { AxiosError } from 'axios'; import logo from '../../assets/img/git-proxy.png'; -import { Badge, CircularProgress, FormLabel, Snackbar } from '@material-ui/core'; +import { CircularProgress, FormLabel, Snackbar } from '@material-ui/core'; import { useAuth } from '../../auth/AuthProvider'; import { getBaseUrl } from '../../services/apiConfig'; import { getAxiosConfig, processAuthError } from '../../services/auth'; @@ -225,18 +225,6 @@ const Login: React.FC = () => { )} -
- - - View our open source activity feed or{' '} - scroll through projects we contribute to - -
diff --git a/test/services/routes/middleware.test.ts b/test/services/routes/middleware.test.ts new file mode 100644 index 000000000..6ad580e14 --- /dev/null +++ b/test/services/routes/middleware.test.ts @@ -0,0 +1,90 @@ +/** + * Copyright 2026 GitProxy Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, it, expect, vi } from 'vitest'; +import express, { Express, Request, Response, NextFunction } from 'express'; +import request from 'supertest'; +import rateLimit from 'express-rate-limit'; +import { ensureAuthenticated } from '../../../src/service/routes/middleware'; +import { jwtAuthHandler } from '../../../src/service/passport/jwtAuthHandler'; +import usersRouter from '../../../src/service/routes/users'; + +describe('ensureAuthenticated', () => { + const buildRes = () => { + const res = {} as Response; + res.status = vi.fn().mockReturnValue(res); + res.send = vi.fn().mockReturnValue(res); + return res; + }; + + it('calls next() for a passport session authenticated request', () => { + const req = { isAuthenticated: () => true } as unknown as Request; + const res = buildRes(); + const next = vi.fn() as unknown as NextFunction; + + ensureAuthenticated(req, res, next); + + expect(next).toHaveBeenCalledOnce(); + expect(res.status).not.toHaveBeenCalled(); + }); + + it('calls next() for a request populated with req.user (e.g. JWT)', () => { + const req = { + isAuthenticated: () => false, + user: { username: 'api-client' }, + } as unknown as Request; + const res = buildRes(); + const next = vi.fn() as unknown as NextFunction; + + ensureAuthenticated(req, res, next); + + expect(next).toHaveBeenCalledOnce(); + expect(res.status).not.toHaveBeenCalled(); + }); + + it('responds 401 when there is no session and no req.user', () => { + const req = { isAuthenticated: () => false } as unknown as Request; + const res = buildRes(); + const next = vi.fn() as unknown as NextFunction; + + ensureAuthenticated(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.send).toHaveBeenCalledWith({ message: 'Authentication required' }); + }); +}); + +describe('GET /api/v1/user authentication', () => { + let app: Express; + + // Mirror the mount in src/service/routes/index.ts (jwtAuthHandler then ensureAuthenticated). + const buildApp = (): Express => { + const a = express(); + a.use(rateLimit({ windowMs: 60 * 1000, limit: 100 })); + a.use(express.json()); + a.use('/api/v1/user', jwtAuthHandler(), ensureAuthenticated, usersRouter); + return a; + }; + + it('returns 401 when unauthenticated', async () => { + app = buildApp(); + const res = await request(app).get('/api/v1/user'); + + expect(res.status).toBe(401); + expect(res.body.message).toBe('Authentication required'); + }); +}); diff --git a/test/testDb.test.ts b/test/testDb.test.ts index 91fdb6eca..5cbfb3556 100644 --- a/test/testDb.test.ts +++ b/test/testDb.test.ts @@ -582,10 +582,22 @@ describe('Database clients', () => { }); it('should be able to create a push', async () => { + await db.writeAudit(TEST_PUSH); + const push = await db.getPush(TEST_PUSH.id); + const cleanPush = cleanResponseData(TEST_PUSH, push!); + expect(cleanPush).toEqual(TEST_PUSH); + }, 20000); + + it('should omit steps, user details and attestation when listing pushes', async () => { await db.writeAudit(TEST_PUSH); const pushes = await db.getPushes({}); - const cleanPushes = cleanResponseData(TEST_PUSH, pushes); - expect(cleanPushes).toContainEqual(TEST_PUSH); + const push = pushes.find((p) => p.id === TEST_PUSH.id); + expect(push).toBeDefined(); + expect(push).toHaveProperty('repo', TEST_PUSH.repo); + expect(push).not.toHaveProperty('steps'); + expect(push).not.toHaveProperty('user'); + expect(push).not.toHaveProperty('userEmail'); + expect(push).not.toHaveProperty('attestation'); }, 20000); it('should be able to delete a push', async () => { diff --git a/test/testPush.test.ts b/test/testPush.test.ts index 8bf85788d..f9d486571 100644 --- a/test/testPush.test.ts +++ b/test/testPush.test.ts @@ -294,7 +294,7 @@ describe('Push API', () => { .post(`/api/v1/push/${TEST_PUSH.id}/authorise`) .send({ reason: 'Testing approval' }); expect(res.status).toBe(401); - expect(res.body.message).toBe('Not logged in'); + expect(res.body.message).toBe('Authentication required'); }); it('should allow an authorizer to reject a push', async () => { @@ -457,7 +457,22 @@ describe('Push API', () => { .post(`/api/v1/push/${TEST_PUSH.id}/reject`) .send({ reason: 'Testing rejection' }); expect(res.status).toBe(401); - expect(res.body.message).toBe('Not logged in'); + expect(res.body.message).toBe('Authentication required'); + }); + + it('should return 401 if not logged in when listing pushes', async () => { + await db.writeAudit(TEST_PUSH); + const res = await request(app).get('/api/v1/push').query({ blocked: true }); + expect(res.status).toBe(401); + expect(res.body.message).toBe('Authentication required'); + expect(JSON.stringify(res.body)).not.toContain(TEST_PUSH.id); + }); + + it('should return 401 if not logged in when fetching a push by id', async () => { + await db.writeAudit(TEST_PUSH); + const res = await request(app).get(`/api/v1/push/${TEST_PUSH.id}`); + expect(res.status).toBe(401); + expect(res.body.message).toBe('Authentication required'); }); it('should fetch all pushes', async () => { @@ -470,9 +485,19 @@ describe('Push API', () => { const push = res.body.find((p: Action) => p.id === TEST_PUSH.id); expect(push).toBeDefined(); - // Check that all values in push are in TEST_PUSH, except for _id - expect(push).toMatchObject(TEST_PUSH); + expect(push.repo).toBe(TEST_PUSH.repo); expect(push.canceled).toBe(false); + expect(push).not.toHaveProperty('steps'); + expect(push).not.toHaveProperty('user'); + expect(push).not.toHaveProperty('userEmail'); + expect(push).not.toHaveProperty('attestation'); + + const detail = await request(app) + .get(`/api/v1/push/${TEST_PUSH.id}`) + .set('Cookie', `${cookie}`); + expect(detail.status).toBe(200); + // Check that all values in push are in TEST_PUSH, except for _id + expect(detail.body).toMatchObject(TEST_PUSH); }); it('should admit filter options when fetching pushes', async () => { @@ -536,6 +561,6 @@ describe('Push API', () => { .post(`/api/v1/push/${TEST_PUSH.id}/cancel`) .send({ reason: 'Testing rejection' }); expect(res.status).toBe(401); - expect(res.body.message).toBe('Not logged in'); + expect(res.body.message).toBe('Authentication required'); }); }); diff --git a/test/testRepoApi.test.ts b/test/testRepoApi.test.ts index 11e4cf6bf..0710f3b29 100644 --- a/test/testRepoApi.test.ts +++ b/test/testRepoApi.test.ts @@ -493,7 +493,7 @@ describe('repo routes - edge cases', () => { }); expect(res.status).toBe(401); - expect(res.body.message).toBe('You are not authorised to perform this action.'); + expect(res.body.message).toBe('Authentication required'); }); it('should return 400 when repo url is missing', async () => { @@ -534,7 +534,7 @@ describe('repo routes - edge cases', () => { .send({ username: 'testuser' }); expect(res.status).toBe(401); - expect(res.body.message).toBe('You are not authorised to perform this action.'); + expect(res.body.message).toBe('Authentication required'); }); it('should return 401 when non-admin user tries to add authorise user', async () => { @@ -553,7 +553,7 @@ describe('repo routes - edge cases', () => { .send({ username: 'testuser' }); expect(res.status).toBe(401); - expect(res.body.message).toBe('You are not authorised to perform this action.'); + expect(res.body.message).toBe('Authentication required'); }); describe('DELETE /api/v1/repo/:id/user/push/:username', () => { @@ -576,7 +576,7 @@ describe('repo routes - edge cases', () => { const res = await request(app).delete(`/api/v1/repo/${repoId}/user/push/testuser`).send(); expect(res.status).toBe(401); - expect(res.body.message).toBe('You are not authorised to perform this action.'); + expect(res.body.message).toBe('Authentication required'); }); it('should return 400 when trying to remove non-existent user', async () => { @@ -612,7 +612,7 @@ describe('repo routes - edge cases', () => { .send(); expect(res.status).toBe(401); - expect(res.body.message).toBe('You are not authorised to perform this action.'); + expect(res.body.message).toBe('Authentication required'); }); it('should return 400 when trying to remove non-existent user', async () => { @@ -641,7 +641,7 @@ describe('repo routes - edge cases', () => { const res = await request(app).delete(`/api/v1/repo/${repoId}/delete`).send(); expect(res.status).toBe(401); - expect(res.body.message).toBe('You are not authorised to perform this action.'); + expect(res.body.message).toBe('Authentication required'); }); });