-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathindex.ts
More file actions
250 lines (223 loc) · 7.98 KB
/
index.ts
File metadata and controls
250 lines (223 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/**
* 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 { AuthorisedRepo } from '../config/generated/config';
import {
PaginatedResult,
PaginationOptions,
PushQuery,
Repo,
RepoQuery,
Sink,
User,
UserQuery,
} from './types';
import * as bcrypt from 'bcryptjs';
import * as config from '../config';
import * as mongo from './mongo';
import * as neDb from './file';
import { Action } from '../proxy/actions/Action';
import MongoDBStore from 'connect-mongo';
import { CompletedAttestation, Rejection } from '../proxy/processors/types';
import { processGitUrl } from '../proxy/routes/helper';
import { initializeFolders } from './file/helper';
let _sink: Sink | null = null;
/** The start function is before any attempt to use the DB adaptor and causes the configuration
* to be read. This allows the read of the config to be deferred, otherwise it will occur on
* import.
*/
const start = () => {
if (!_sink) {
if (config.getDatabase().type === 'mongo') {
console.log('Loading MongoDB database adaptor');
_sink = mongo;
} else if (config.getDatabase().type === 'fs') {
console.log('Loading neDB database adaptor');
initializeFolders();
_sink = neDb;
} else {
console.error(`Unsupported database type: ${config.getDatabase().type}`);
process.exit(1);
}
}
return _sink;
};
const isBlank = (str: string) => {
return !str || /^\s*$/.test(str);
};
export const createUser = async (
username: string,
password: string,
email: string,
gitAccount: string,
admin: boolean = false,
oidcId: string = '',
) => {
console.log(
`creating user
user=${username},
gitAccount=${gitAccount}
email=${email},
admin=${admin}
oidcId=${oidcId}`,
);
const data = {
username: username,
password: oidcId ? null : await bcrypt.hash(password, 10),
gitAccount: gitAccount,
email: email,
admin: admin,
};
if (isBlank(username)) {
const errorMessage = `username cannot be empty`;
throw new Error(errorMessage);
}
if (isBlank(gitAccount)) {
const errorMessage = `gitAccount cannot be empty`;
throw new Error(errorMessage);
}
if (isBlank(email)) {
const errorMessage = `email cannot be empty`;
throw new Error(errorMessage);
}
const sink = start();
const existingUser = await sink.findUser(username);
if (existingUser) {
const errorMessage = `user ${username} already exists`;
throw new Error(errorMessage);
}
const existingUserWithEmail = await sink.findUserByEmail(email);
if (existingUserWithEmail) {
const errorMessage = `A user with email ${email} already exists`;
throw new Error(errorMessage);
}
await sink.createUser(data);
};
export const createRepo = async (repo: AuthorisedRepo) => {
const toCreate = {
...repo,
users: {
canPush: [],
canAuthorise: [],
},
};
toCreate.name = repo.name.toLowerCase();
console.log(`creating new repo ${JSON.stringify(toCreate)}`);
// n.b. project name may be blank but not null for non-github and non-gitlab repos
if (!toCreate.project) {
toCreate.project = '';
}
if (isBlank(toCreate.name)) {
throw new Error('Repository name cannot be empty');
}
if (isBlank(toCreate.url)) {
throw new Error('URL cannot be empty');
}
return start().createRepo(toCreate) as Promise<Required<Repo>>;
};
export const isUserPushAllowed = async (url: string, user: string) => {
user = user.toLowerCase();
const repo = await getRepoByUrl(url);
if (!repo) {
return false;
}
return repo.users?.canPush.includes(user) || repo.users?.canAuthorise.includes(user);
};
export const canUserApproveRejectPush = async (id: string, user: string) => {
const action = await getPush(id);
if (!action) {
return false;
}
const theRepo = await start().getRepoByUrl(action.url);
if (theRepo?.users?.canAuthorise?.includes(user)) {
console.log(`user ${user} can approve/reject for repo ${action.url}`);
return true;
} else {
console.log(`user ${user} cannot approve/reject for repo ${action.url}`);
return false;
}
};
export const canUserCancelPush = async (id: string, user: string) => {
const action = await getPush(id);
if (!action) {
return false;
}
const isAllowed = await isUserPushAllowed(action.url, user);
if (isAllowed) {
return true;
} else {
return false;
}
};
export const getSessionStore = (): MongoDBStore | undefined => start().getSessionStore();
export const getPushes = (
query: Partial<PushQuery>,
pagination?: PaginationOptions,
): Promise<PaginatedResult<Action>> => start().getPushes(query, pagination);
export const writeAudit = (action: Action): Promise<void> => start().writeAudit(action);
export const getPush = (id: string): Promise<Action | null> => start().getPush(id);
export const deletePush = (id: string): Promise<void> => start().deletePush(id);
export const authorise = (
id: string,
attestation?: CompletedAttestation,
): Promise<{ message: string }> => start().authorise(id, attestation);
export const cancel = (id: string): Promise<{ message: string }> => start().cancel(id);
export const reject = (id: string, rejection: Rejection): Promise<{ message: string }> =>
start().reject(id, rejection);
export const getRepos = (
query?: Partial<RepoQuery>,
pagination?: PaginationOptions,
): Promise<PaginatedResult<Repo>> => start().getRepos(query, pagination);
export const getRepo = (name: string): Promise<Repo | null> => start().getRepo(name);
export const getRepoByUrl = (url: string): Promise<Repo | null> => start().getRepoByUrl(url);
export const getRepoById = (_id: string): Promise<Repo | null> => start().getRepoById(_id);
export const addUserCanPush = (_id: string, user: string): Promise<void> =>
start().addUserCanPush(_id, user);
export const addUserCanAuthorise = (_id: string, user: string): Promise<void> =>
start().addUserCanAuthorise(_id, user);
export const removeUserCanPush = (_id: string, user: string): Promise<void> =>
start().removeUserCanPush(_id, user);
export const removeUserCanAuthorise = (_id: string, user: string): Promise<void> =>
start().removeUserCanAuthorise(_id, user);
export const deleteRepo = (_id: string): Promise<void> => start().deleteRepo(_id);
export const findUser = (username: string): Promise<User | null> => start().findUser(username);
export const findUserByEmail = (email: string): Promise<User | null> =>
start().findUserByEmail(email);
export const findUserByOIDC = (oidcId: string): Promise<User | null> =>
start().findUserByOIDC(oidcId);
export const getUsers = (
query?: Partial<UserQuery>,
pagination?: PaginationOptions,
): Promise<PaginatedResult<User>> => start().getUsers(query, pagination);
export const deleteUser = (username: string): Promise<void> => start().deleteUser(username);
export const updateUser = (user: Partial<User>): Promise<void> => start().updateUser(user);
/**
* Collect the Set of all host (host and port if specified) that we
* will be proxying requests for, to be used to initialize the proxy.
*
* @return {string[]} an array of origins
*/
export const getAllProxiedHosts = async (): Promise<string[]> => {
const { data: repos } = await getRepos();
const origins = new Set<string>();
repos.forEach((repo) => {
const parsedUrl = processGitUrl(repo.url);
if (parsedUrl) {
origins.add(parsedUrl.host);
} // failures are logged by parsing util fn
});
return Array.from(origins);
};
export type { PaginatedResult, PaginationOptions, PushQuery, Repo, Sink, User } from './types';