diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5db95b114..ed9b4ff5a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,6 +82,8 @@ jobs: - name: Run cypress test uses: cypress-io/github-action@4c06c48f3ffea349b7189aa06dfcda47a9fa7b92 # v7.1.8 + env: + GIT_PROXY_ADMIN_PASSWORD: admin with: # skip the action's internal npm ci — dependencies are already installed above install: false diff --git a/cypress/e2e/repo.cy.js b/cypress/e2e/repo.cy.js index a69372848..4b634865a 100644 --- a/cypress/e2e/repo.cy.js +++ b/cypress/e2e/repo.cy.js @@ -37,8 +37,14 @@ describe('Repo', () => { }); describe('Regular users', () => { + before(() => { + cy.login('admin', 'admin'); + cy.createUser('user', 'user1234', 'user@place.com', 'user'); + cy.logout(); + }); + beforeEach(() => { - cy.login('user', 'user'); + cy.login('user', 'user1234'); cy.visit('/dashboard/repo'); }); diff --git a/docker-compose.yml b/docker-compose.yml index b947fd688..768ac72f9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -18,6 +18,8 @@ services: - git-network environment: - NODE_ENV=test + # Test-only initial admin password. Never use a fixed password in production. + - GIT_PROXY_ADMIN_PASSWORD=admin - CONFIG_FILE=/app/test-e2e.proxy.config.json - GIT_PROXY_UI_PORT=8081 - GIT_PROXY_SERVER_PORT=8000 diff --git a/docs/Architecture.md b/docs/Architecture.md index 7f49ebe62..67a055ba4 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -122,10 +122,9 @@ Currently, three different authentication methods are provided for interacting w Default username/password auth method. Note that this authentication method does not allow adding users directly from the UI (`/api/auth/create-user` must be used instead). -Default accounts are provided for testing: +On first start, GitProxy creates a single admin account with username `admin`. Its password is read from the `GIT_PROXY_ADMIN_PASSWORD` environment variable if set; otherwise a random password is generated and printed once to the server log. No other accounts are created. -- Admin: Username: `admin`, Password: `admin` -- User: Username: `user`, Password: `user` +Users can change their own password with `POST /api/auth/change-password` (body: `{"currentPassword": "...", "newPassword": "..."}`, minimum 8 characters). A warning is logged at startup if the `admin` or `user` accounts still have the well-known default passwords seeded by older versions. #### ActiveDirectory diff --git a/src/service/passport/local.ts b/src/service/passport/local.ts index d925b3c66..7ae12e0ec 100644 --- a/src/service/passport/local.ts +++ b/src/service/passport/local.ts @@ -15,6 +15,7 @@ */ import bcrypt from 'bcryptjs'; +import crypto from 'crypto'; import { IVerifyOptions, Strategy as LocalStrategy } from 'passport-local'; import type { PassportStatic } from 'passport'; import * as db from '../../db'; @@ -70,23 +71,61 @@ export const configure = async (passport: PassportStatic): Promise crypto.randomBytes(18).toString('base64url'); + +const warnOnLegacyDefaultCredentials = async () => { + for (const { username, password } of LEGACY_DEFAULT_CREDENTIALS) { + const user = await db.findUser(username); + if (user?.password && (await bcrypt.compare(password, user.password))) { + console.warn( + `WARNING: user "${username}" still has the well-known default password. ` + + 'Change it immediately via POST /api/auth/change-password or delete the account.', + ); + } + } +}; + /** - * Create the default admin and regular test users. + * Bootstrap the initial admin user on first start. + * + * The password is taken from the GIT_PROXY_ADMIN_PASSWORD environment variable if set, + * otherwise a random password is generated and printed once to the log. */ export const createDefaultAdmin = async () => { - const createIfNotExists = async ( - username: string, - password: string, - email: string, - type: string, - isAdmin: boolean, - ) => { - const user = await db.findUser(username); - if (!user) { - await db.createUser(username, password, email, type, isAdmin); + const existingAdmin = await db.findUser(DEFAULT_ADMIN_USERNAME); + if (!existingAdmin) { + const envPassword = process.env[ADMIN_PASSWORD_ENV_VAR]; + const password = envPassword || generatePassword(); + await db.createUser(DEFAULT_ADMIN_USERNAME, password, DEFAULT_ADMIN_EMAIL, 'none', true); + + if (envPassword) { + console.log( + `Created initial admin user "${DEFAULT_ADMIN_USERNAME}" with the password from ${ADMIN_PASSWORD_ENV_VAR}.`, + ); + } else { + console.log( + [ + '========================================================================', + `Created initial admin user "${DEFAULT_ADMIN_USERNAME}" with a generated password:`, + ` ${password}`, + 'This password will not be shown again. Change it after first login via', + 'POST /api/auth/change-password.', + '========================================================================', + ].join('\n'), + ); } - }; + } - await createIfNotExists('admin', 'admin', 'admin@place.com', 'none', true); - await createIfNotExists('user', 'user', 'user@place.com', 'none', false); + await warnOnLegacyDefaultCredentials(); }; diff --git a/src/service/routes/auth.ts b/src/service/routes/auth.ts index a03c80480..f27ef7d2b 100644 --- a/src/service/routes/auth.ts +++ b/src/service/routes/auth.ts @@ -15,6 +15,7 @@ */ import express, { Request, Response, NextFunction } from 'express'; +import bcrypt from 'bcryptjs'; import { getPassport, authStrategies } from '../passport'; import { getAuthMethods } from '../../config'; @@ -48,6 +49,10 @@ router.get('/', (_req: Request, res: Response) => { action: 'post', uri: '/api/auth/logout', }, + changePassword: { + action: 'post', + uri: '/api/auth/change-password', + }, }); }); @@ -235,6 +240,78 @@ router.post('/gitAccount', async (req: Request, res: Response) => { } }); +const MIN_PASSWORD_LENGTH = 8; +// bcrypt silently ignores input beyond 72 bytes +const MAX_PASSWORD_BYTES = 72; + +router.post('/change-password', async (req: Request, res: Response) => { + if (!req.user) { + res.status(401).send({ message: 'Not logged in' }).end(); + return; + } + + try { + const { currentPassword, newPassword } = req.body ?? {}; + + if (typeof currentPassword !== 'string' || typeof newPassword !== 'string') { + res + .status(400) + .send({ message: 'Missing required fields: currentPassword and newPassword are required' }) + .end(); + return; + } + + if (newPassword.length < MIN_PASSWORD_LENGTH) { + res + .status(400) + .send({ message: `New password must be at least ${MIN_PASSWORD_LENGTH} characters long` }) + .end(); + return; + } + + if (Buffer.byteLength(newPassword, 'utf8') > MAX_PASSWORD_BYTES) { + res + .status(400) + .send({ message: `New password must be at most ${MAX_PASSWORD_BYTES} bytes long` }) + .end(); + return; + } + + const user = await db.findUser((req.user as User).username); + if (!user) { + res.status(404).send({ message: 'User not found' }).end(); + return; + } + + if (!user.password) { + res + .status(400) + .send({ message: 'Password cannot be changed for users without a local password' }) + .end(); + return; + } + + if (!(await bcrypt.compare(currentPassword, user.password))) { + res.status(403).send({ message: 'Current password is incorrect' }).end(); + return; + } + + if (await bcrypt.compare(newPassword, user.password)) { + res + .status(400) + .send({ message: 'New password must be different from the current password' }) + .end(); + return; + } + + await db.updateUser({ username: user.username, password: await bcrypt.hash(newPassword, 10) }); + res.status(200).send({ message: 'Password changed successfully' }).end(); + } catch (error: unknown) { + const msg = handleErrorAndLog(error, 'Failed to change password'); + res.status(500).send({ message: msg }).end(); + } +}); + router.post('/create-user', async (req: Request, res: Response) => { if (!isAdminUser(req.user)) { res diff --git a/test/services/passport/local.test.ts b/test/services/passport/local.test.ts new file mode 100644 index 000000000..fb57ac875 --- /dev/null +++ b/test/services/passport/local.test.ts @@ -0,0 +1,127 @@ +/** + * 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, beforeEach, afterEach, vi } from 'vitest'; +import bcrypt from 'bcryptjs'; +import * as db from '../../../src/db'; +import { createDefaultAdmin, ADMIN_PASSWORD_ENV_VAR } from '../../../src/service/passport/local'; + +describe('createDefaultAdmin', () => { + const originalEnv = process.env[ADMIN_PASSWORD_ENV_VAR]; + let createUserSpy: ReturnType; + let logSpy: ReturnType; + let warnSpy: ReturnType; + + beforeEach(() => { + createUserSpy = vi.spyOn(db, 'createUser').mockResolvedValue(undefined); + logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + if (originalEnv === undefined) { + delete process.env[ADMIN_PASSWORD_ENV_VAR]; + } else { + process.env[ADMIN_PASSWORD_ENV_VAR] = originalEnv; + } + }); + + it('creates only the admin user with a random password when no env var is set', async () => { + delete process.env[ADMIN_PASSWORD_ENV_VAR]; + vi.spyOn(db, 'findUser').mockResolvedValue(null); + + await createDefaultAdmin(); + + expect(createUserSpy).toHaveBeenCalledTimes(1); + const [username, password, , , isAdmin] = createUserSpy.mock.calls[0]; + expect(username).toBe('admin'); + expect(isAdmin).toBe(true); + expect(password).not.toBe('admin'); + expect((password as string).length).toBeGreaterThanOrEqual(20); + expect(logSpy.mock.calls.flat().join('\n')).toContain(password as string); + }); + + it('generates a different password each time', async () => { + delete process.env[ADMIN_PASSWORD_ENV_VAR]; + vi.spyOn(db, 'findUser').mockResolvedValue(null); + + await createDefaultAdmin(); + await createDefaultAdmin(); + + expect(createUserSpy.mock.calls[0][1]).not.toBe(createUserSpy.mock.calls[1][1]); + }); + + it('uses GIT_PROXY_ADMIN_PASSWORD when set and does not log it', async () => { + process.env[ADMIN_PASSWORD_ENV_VAR] = 'from-env-secret'; + vi.spyOn(db, 'findUser').mockResolvedValue(null); + + await createDefaultAdmin(); + + expect(createUserSpy).toHaveBeenCalledTimes(1); + expect(createUserSpy.mock.calls[0][1]).toBe('from-env-secret'); + expect(logSpy.mock.calls.flat().join('\n')).not.toContain('from-env-secret'); + }); + + it('never creates a "user" account', async () => { + delete process.env[ADMIN_PASSWORD_ENV_VAR]; + vi.spyOn(db, 'findUser').mockResolvedValue(null); + + await createDefaultAdmin(); + + expect(createUserSpy.mock.calls.map((c) => c[0])).not.toContain('user'); + }); + + it('does not recreate or reset an existing admin', async () => { + const hash = await bcrypt.hash('a-strong-password', 4); + vi.spyOn(db, 'findUser').mockImplementation(async (username: string) => + username === 'admin' + ? { + username: 'admin', + password: hash, + email: 'admin@place.com', + gitAccount: 'none', + admin: true, + } + : null, + ); + + await createDefaultAdmin(); + + expect(createUserSpy).not.toHaveBeenCalled(); + expect(warnSpy).not.toHaveBeenCalled(); + }); + + it('warns when legacy default credentials are still in use', async () => { + const adminHash = await bcrypt.hash('admin', 4); + const userHash = await bcrypt.hash('user', 4); + vi.spyOn(db, 'findUser').mockImplementation(async (username: string) => { + if (username === 'admin') { + return { username, password: adminHash, email: 'a@x', gitAccount: 'none', admin: true }; + } + if (username === 'user') { + return { username, password: userHash, email: 'u@x', gitAccount: 'none', admin: false }; + } + return null; + }); + + await createDefaultAdmin(); + + const warnings = warnSpy.mock.calls.flat().join('\n'); + expect(warnings).toContain('"admin"'); + expect(warnings).toContain('"user"'); + }); +}); diff --git a/test/services/routes/auth.test.ts b/test/services/routes/auth.test.ts index 4008cf9ed..5f66ab9dc 100644 --- a/test/services/routes/auth.test.ts +++ b/test/services/routes/auth.test.ts @@ -16,6 +16,7 @@ import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'; import request from 'supertest'; +import bcrypt from 'bcryptjs'; import express, { Express, Request, Response } from 'express'; import authRoutes from '../../../src/service/routes/auth'; import * as db from '../../../src/db'; @@ -301,6 +302,10 @@ describe('Auth API', () => { action: 'post', uri: '/api/auth/logout', }, + changePassword: { + action: 'post', + uri: '/api/auth/change-password', + }, }); }); }); @@ -315,4 +320,102 @@ describe('Auth API', () => { }); }); }); + describe('POST /change-password', () => { + let hash: string; + let updateUserSpy: ReturnType; + + beforeEach(async () => { + hash = await bcrypt.hash('old-password', 4); + vi.spyOn(db, 'findUser').mockImplementation(async (username: string) => { + if (username === 'alice') { + return { + username: 'alice', + gitAccount: 'alice', + email: 'alice@example.com', + admin: false, + password: hash, + }; + } + if (username === 'oidc-user') { + return { + username: 'oidc-user', + gitAccount: 'oidc', + email: 'oidc@example.com', + admin: false, + password: null, + }; + } + return null; + }); + updateUserSpy = vi.spyOn(db, 'updateUser').mockResolvedValue(undefined); + }); + + it('should return 401 if not logged in', async () => { + const res = await request(newApp()) + .post('/auth/change-password') + .send({ currentPassword: 'old-password', newPassword: 'new-password' }); + expect(res.status).toBe(401); + expect(updateUserSpy).not.toHaveBeenCalled(); + }); + + it('should return 400 if fields are missing', async () => { + const res = await request(newApp('alice')) + .post('/auth/change-password') + .send({ newPassword: 'new-password' }); + expect(res.status).toBe(400); + expect(updateUserSpy).not.toHaveBeenCalled(); + }); + + it('should return 400 if the new password is too short', async () => { + const res = await request(newApp('alice')) + .post('/auth/change-password') + .send({ currentPassword: 'old-password', newPassword: 'short' }); + expect(res.status).toBe(400); + expect(updateUserSpy).not.toHaveBeenCalled(); + }); + + it('should return 400 if the new password exceeds the bcrypt 72-byte limit', async () => { + const res = await request(newApp('alice')) + .post('/auth/change-password') + .send({ currentPassword: 'old-password', newPassword: 'a'.repeat(73) }); + expect(res.status).toBe(400); + expect(updateUserSpy).not.toHaveBeenCalled(); + }); + + it('should return 403 if the current password is wrong', async () => { + const res = await request(newApp('alice')) + .post('/auth/change-password') + .send({ currentPassword: 'wrong-password', newPassword: 'new-password' }); + expect(res.status).toBe(403); + expect(updateUserSpy).not.toHaveBeenCalled(); + }); + + it('should return 400 for users without a local password', async () => { + const res = await request(newApp('oidc-user')) + .post('/auth/change-password') + .send({ currentPassword: '', newPassword: 'new-password' }); + expect(res.status).toBe(400); + expect(updateUserSpy).not.toHaveBeenCalled(); + }); + + it('should return 400 if the new password equals the current one', async () => { + const res = await request(newApp('alice')) + .post('/auth/change-password') + .send({ currentPassword: 'old-password', newPassword: 'old-password' }); + expect(res.status).toBe(400); + expect(updateUserSpy).not.toHaveBeenCalled(); + }); + + it('should store a bcrypt hash of the new password', async () => { + const res = await request(newApp('alice')) + .post('/auth/change-password') + .send({ currentPassword: 'old-password', newPassword: 'new-password' }); + expect(res.status).toBe(200); + expect(updateUserSpy).toHaveBeenCalledTimes(1); + const updated = updateUserSpy.mock.calls[0][0] as { username: string; password: string }; + expect(updated.username).toBe('alice'); + expect(updated.password).not.toBe('new-password'); + expect(await bcrypt.compare('new-password', updated.password)).toBe(true); + }); + }); }); diff --git a/vitest.config.integration.ts b/vitest.config.integration.ts index bbb4fa695..53d4437e9 100644 --- a/vitest.config.integration.ts +++ b/vitest.config.integration.ts @@ -31,6 +31,7 @@ export default defineConfig({ }, env: { NODE_ENV: 'test', + GIT_PROXY_ADMIN_PASSWORD: 'admin', RUN_MONGO_TESTS: 'true', CONFIG_FILE: path.resolve(__dirname, 'test-integration.proxy.config.json'), GIT_PROXY_MONGO_CONNECTION_STRING: 'mongodb://localhost:27017/git-proxy-test', diff --git a/vitest.config.ts b/vitest.config.ts index b3bd70313..8db2bdb8d 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -18,6 +18,9 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { + env: { + GIT_PROXY_ADMIN_PASSWORD: 'admin', + }, pool: 'forks', poolOptions: { forks: { diff --git a/website/docs/deployment.mdx b/website/docs/deployment.mdx index 5f45de0c1..fe7fcaa6e 100644 --- a/website/docs/deployment.mdx +++ b/website/docs/deployment.mdx @@ -80,6 +80,7 @@ git-proxy --config ./proxy.config.json ``` Expected output: + ``` Listening on 8000 Service Listening on 8080 @@ -100,6 +101,7 @@ git remote add proxy http://localhost:8000/my-org/my-repo.git ``` Or replace the existing origin: + ```bash git remote set-url origin http://localhost:8000/my-org/my-repo.git ``` @@ -113,6 +115,7 @@ git push proxy main ``` You should receive a message with a review URL: + ``` remote: GitProxy has received your push remote: Shareable Link @@ -122,11 +125,12 @@ remote: http://localhost:8080/dashboard/push/000000__b12557 ### 6. Approve the Push 1. Navigate to http://localhost:8080 in your browser -2. Log in with default credentials (**development only**): +2. Log in as the initial admin user: - Username: `admin` - - Password: `admin` + - Password: the generated password printed once in the GitProxy log on first start, or the value of `GIT_PROXY_ADMIN_PASSWORD` if you set it See the [Authentication](https://github.com/finos/git-proxy/blob/main/docs/Architecture.md#authentication) section of the architecture guide for more details. + 3. Review the push and approve it 4. Push again to forward to upstream: ```bash @@ -161,6 +165,7 @@ docker build -t git-proxy:local . The Dockerfile uses a multi-stage build with Node.js 22, installs `git` and `tini`, and runs as a non-root user (UID 1000). Ports 8000 (proxy) and 8080 (UI/API) are exposed. View logs: + ```bash docker logs -f git-proxy ``` @@ -169,16 +174,18 @@ docker logs -f git-proxy The following environment variables can be set at container runtime: -| Variable | Default | Description | -| ------------------------ | ------------ | -------------------------------------------------------- | -| `GIT_PROXY_SERVER_PORT` | `8000` | Proxy server port | -| `GIT_PROXY_UI_PORT` | `8080` | UI/API server port (HTTP) | -| `GIT_PROXY_HTTPS_UI_PORT`| `8444` | UI/API server port (HTTPS, active when `tls.enabled`) | -| `ALLOWED_ORIGINS` | (empty) | CORS allowed origins (comma-separated, or `*` for all) | -| `API_URL` | (empty) | API URL for the UI (leave empty for same-origin) | -| `NODE_ENV` | `production` | Node environment | +| Variable | Default | Description | +| -------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `GIT_PROXY_SERVER_PORT` | `8000` | Proxy server port | +| `GIT_PROXY_UI_PORT` | `8080` | UI/API server port (HTTP) | +| `GIT_PROXY_HTTPS_UI_PORT` | `8444` | UI/API server port (HTTPS, active when `tls.enabled`) | +| `ALLOWED_ORIGINS` | (empty) | CORS allowed origins (comma-separated, or `*` for all) | +| `API_URL` | (empty) | API URL for the UI (leave empty for same-origin) | +| `NODE_ENV` | `production` | Node environment | +| `GIT_PROXY_ADMIN_PASSWORD` | (empty) | Initial password for the `admin` user, used only on first start when no `admin` exists. If unset, a random password is generated and printed once to the log | Example with environment variables: + ```bash docker run -d \ --name git-proxy \ @@ -234,21 +241,25 @@ git push origin main GitProxy prompts for credentials on each push. To cache credentials: **macOS:** + ```bash git config --global credential.helper osxkeychain ``` **Windows:** + ```bash git config --global credential.helper manager ``` **Linux:** + ```bash git config --global credential.helper store ``` **Required credentials for pushing through GitProxy to GitHub:** + - GitHub username - Personal Access Token (PAT) with at minimum `public_repo` scope @@ -281,6 +292,7 @@ Switch from the default file-based database to MongoDB for production use: ``` **Recommendations:** + - Use MongoDB 6.0 or later - Enable authentication and TLS/SSL - Configure replica sets for high availability @@ -307,11 +319,13 @@ GitProxy does not currently ship with built-in metrics or structured logging. Re ### Backup **MongoDB:** + ```bash mongodump --uri="mongodb://localhost:27017/gitproxy" --out=/backup/$(date +%Y%m%d) ``` **File-based (NeDB):** + ```bash tar -czf gitproxy-backup-$(date +%Y%m%d).tar.gz ./.data ``` diff --git a/website/docs/quickstart/approve.mdx b/website/docs/quickstart/approve.mdx index ebcd59ced..7bd79011c 100644 --- a/website/docs/quickstart/approve.mdx +++ b/website/docs/quickstart/approve.mdx @@ -32,11 +32,11 @@ The `ID` for your push corresponds to the last part of the URL: #### 2. Authenticate with the API -Use the default & auto-generated GitProxy username & password credentials to obtain a cookie. The cookie value is saved to a file (`git-proxy-cookie`): +Use the `admin` account and the initial password printed in the GitProxy server log on first start (or the value of `GIT_PROXY_ADMIN_PASSWORD`, if set) to obtain a cookie. The cookie value is saved to a file (`git-proxy-cookie`): ```bash curl -H "Content-Type: application/json" -c git-proxy-cookie -X POST \ - -d '{"username":"admin","password":"admin"}' http://localhost:8080/auth/login + -d '{"username":"admin","password":""}' http://localhost:8080/auth/login ``` #### 3. Retrieve push with `ID` from database @@ -99,10 +99,10 @@ The `ID` for your push corresponds to the last part of the URL: #### 2. Authenticate with the CLI -Use the default & auto-generated GitProxy username & password credentials to authenticate and obtain a cookie. The cookie value is saved to a file (`git-proxy-cookie`): +Use the `admin` account and the initial password printed in the GitProxy server log on first start (or the value of `GIT_PROXY_ADMIN_PASSWORD`, if set) to authenticate and obtain a cookie. The cookie value is saved to a file (`git-proxy-cookie`): ```bash -$ npx -- @finos/git-proxy-cli login --username admin --password admin +$ npx -- @finos/git-proxy-cli login --username admin --password Login "admin" (admin): OK ```