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
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion cypress/e2e/repo.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions docs/Architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
67 changes: 53 additions & 14 deletions src/service/passport/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -70,23 +71,61 @@ export const configure = async (passport: PassportStatic): Promise<PassportStati
return passport;
};

export const ADMIN_PASSWORD_ENV_VAR = 'GIT_PROXY_ADMIN_PASSWORD';

const DEFAULT_ADMIN_USERNAME = 'admin';
const DEFAULT_ADMIN_EMAIL = 'admin@place.com';

// Credentials seeded by older versions of GitProxy. Warn loudly if any are still usable.
const LEGACY_DEFAULT_CREDENTIALS = [
{ username: 'admin', password: 'admin' },
{ username: 'user', password: 'user' },
];

const generatePassword = (): string => 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();
};
77 changes: 77 additions & 0 deletions src/service/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/

import express, { Request, Response, NextFunction } from 'express';
import bcrypt from 'bcryptjs';
import { getPassport, authStrategies } from '../passport';
import { getAuthMethods } from '../../config';

Expand Down Expand Up @@ -48,6 +49,10 @@ router.get('/', (_req: Request, res: Response) => {
action: 'post',
uri: '/api/auth/logout',
},
changePassword: {
action: 'post',
uri: '/api/auth/change-password',
},
});
});

Expand Down Expand Up @@ -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
Expand Down
127 changes: 127 additions & 0 deletions test/services/passport/local.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof vi.spyOn>;
let logSpy: ReturnType<typeof vi.spyOn>;
let warnSpy: ReturnType<typeof vi.spyOn>;

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"');
});
});
Loading
Loading