-
-
Notifications
You must be signed in to change notification settings - Fork 209
Expand file tree
/
Copy pathTenantRepoAccessContract.mjs
More file actions
331 lines (286 loc) · 10.5 KB
/
TenantRepoAccessContract.mjs
File metadata and controls
331 lines (286 loc) · 10.5 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import path from 'path';
/**
* @summary Normalizes and guards tenant repo-access config entries for server-side KB ingestion.
*
* The tenant repo-sync lane (#11731) intentionally separates clean repository identity from
* credential material. A tenant config entry may name a `credentialRef`, but `cloneUrl` and
* `repoSlug` must stay safe for graph persistence, logs, and telemetry. Git credentials are
* injected later by the Git mirror worker (#11788), not stored in the Knowledge Base config node.
*
* @see https://github.com/neomjs/neo/issues/11787
*/
const URL_WITH_USERINFO_RE = /^[a-z][a-z0-9+.-]*:\/\/[^/\s@]+@/iu;
const SCP_LIKE_USERINFO_RE = /^[^/\s@:]+@[^/\s@:]+:/u;
const SECRET_REPLACEMENT = '[REDACTED]';
/**
* @summary Creates a contract error with a stable code for callers and tests.
* @param {String} code Stable error code.
* @param {String} message Human-readable error message.
* @returns {Error}
* @private
*/
function createContractError(code, message) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* @summary Escapes a string for safe literal use inside a regular expression.
* @param {String} value String to escape.
* @returns {String}
* @private
*/
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
}
/**
* @summary Strips the terminal `.git` suffix and surrounding slashes from a repo identity segment.
* @param {String} value Repo identity candidate.
* @returns {String}
* @private
*/
function stripRepoSuffix(value) {
return value.replace(/^\/+/u, '').replace(/\/+$/u, '').replace(/\.git$/iu, '');
}
/**
* @summary Normalizes one path segment used in tenant repo mirror paths.
* @param {String} value Segment candidate.
* @param {String} code Stable error code.
* @param {String} label Human-readable segment label.
* @returns {String}
* @private
*/
function normalizeMirrorPathSegment(value, code, label) {
const segment = String(value || '').trim();
if (
!segment ||
segment === '.' ||
segment === '..' ||
segment.includes('/') ||
segment.includes('\\') ||
segment.includes('@') ||
segment.includes(':') ||
/\s/u.test(segment)
) {
throw createContractError(code, `Tenant repo mirror path requires a clean ${label}`);
}
return segment;
}
/**
* @summary Returns true when a clone URL embeds userinfo that could carry credentials.
* @param {String} cloneUrl Candidate clone URL.
* @returns {Boolean}
*/
export function hasCloneUrlUserInfo(cloneUrl) {
const value = String(cloneUrl || '').trim();
return URL_WITH_USERINFO_RE.test(value) || SCP_LIKE_USERINFO_RE.test(value);
}
/**
* @summary Throws when a clone URL contains credential-shaped material.
* @param {String} cloneUrl Candidate clone URL.
* @returns {String} Trimmed clone URL.
*/
export function assertCleanCloneUrl(cloneUrl) {
const value = String(cloneUrl || '').trim();
if (!value) {
throw createContractError(
'KB_TENANT_REPO_CLONE_URL_REQUIRED',
'Tenant repo config requires a non-empty cloneUrl'
);
}
if (hasCloneUrlUserInfo(value)) {
throw createContractError(
'KB_TENANT_REPO_CLONE_URL_CREDENTIALS',
'Tenant repo cloneUrl must not embed userinfo or credentials'
);
}
if (/[?#]/u.test(value)) {
throw createContractError(
'KB_TENANT_REPO_CLONE_URL_CREDENTIALS',
'Tenant repo cloneUrl must not include query strings or fragments'
);
}
return value;
}
/**
* @summary Derives a deterministic, credential-free repo slug from a clean clone URL.
*
* The output is `host/org/repo` for URL-style clone URLs, or `host/path` for clean scp-like
* clone strings. Caller-provided `repoSlug` values pass through {@link normalizeRepoSlug}
* instead; this helper only fills the omission case.
*
* @param {String} cloneUrl Clean clone URL.
* @returns {String}
*/
export function deriveRepoSlugFromCloneUrl(cloneUrl) {
const value = assertCleanCloneUrl(cloneUrl);
try {
const url = new URL(value);
if (!url.hostname || !url.pathname || url.pathname === '/') {
throw new Error('missing repo path');
}
return normalizeRepoSlug(`${url.hostname}/${stripRepoSuffix(url.pathname)}`);
} catch (error) {
const scpLike = value.match(/^([^/\s@:]+):(.+)$/u);
if (scpLike) {
return normalizeRepoSlug(`${scpLike[1]}/${stripRepoSuffix(scpLike[2])}`);
}
throw createContractError(
'KB_TENANT_REPO_CLONE_URL_INVALID',
'Tenant repo cloneUrl must be a clean URL or host:path git reference'
);
}
}
/**
* @summary Normalizes a repo slug while keeping it safe for graph persistence and logs.
* @param {String} repoSlug Repo slug candidate.
* @returns {String}
*/
export function normalizeRepoSlug(repoSlug) {
const value = stripRepoSuffix(String(repoSlug || '').trim());
if (!value) {
throw createContractError(
'KB_TENANT_REPO_SLUG_REQUIRED',
'Tenant repo config requires a repoSlug or derivable cloneUrl'
);
}
if (
value.includes('://') ||
value.includes('@') ||
value.includes(':') ||
value.includes('..') ||
value.startsWith('/') ||
value.includes('\\') ||
/[\s?#]/u.test(value)
) {
throw createContractError(
'KB_TENANT_REPO_SLUG_INVALID',
'Tenant repo repoSlug must be a clean repository identity'
);
}
return value;
}
/**
* @summary Normalizes one tenant repo-access config entry and enforces the no-secret boundary.
* @param {Object} entry Tenant repo-access config entry.
* @param {String} [entry.branchRef] Optional git ref (branch / tag / sha) to ingest from. When
* omitted the downstream envelope builder defaults to `'HEAD'` (= remote default branch).
* Useful for tenants whose canonical product-source-of-truth branch differs from the
* repo's default branch (e.g., trunk-based teams using `dev` as integration line and
* `main` as release-tag-only).
* @returns {{cloneUrl: String, credentialRef: String|Object, repoSlug: String, branchRef?: String}}
*/
export function normalizeTenantRepoEntry(entry = {}) {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
throw createContractError(
'KB_TENANT_REPO_ENTRY_INVALID',
'Tenant repo config entries must be objects'
);
}
const cloneUrl = assertCleanCloneUrl(entry.cloneUrl);
if (!entry.credentialRef) {
throw createContractError(
'KB_TENANT_REPO_CREDENTIAL_REF_REQUIRED',
'Tenant repo config entries require credentialRef'
);
}
if (Object.hasOwn(entry, 'branchRef') && (typeof entry.branchRef !== 'string' || entry.branchRef.trim() === '')) {
throw createContractError(
'KB_TENANT_REPO_ENTRY_INVALID',
'Tenant repo config branchRef must be a non-empty string when present'
);
}
return {
...entry,
cloneUrl,
credentialRef: entry.credentialRef,
repoSlug : entry.repoSlug ? normalizeRepoSlug(entry.repoSlug) : deriveRepoSlugFromCloneUrl(cloneUrl)
};
}
/**
* @summary Normalizes an optional `tenantRepos` config array.
* @param {Object} config Tenant KB config payload.
* @returns {Object}
*/
export function normalizeTenantRepoConfig(config = {}) {
if (!Object.hasOwn(config, 'tenantRepos')) {
return config;
}
if (!Array.isArray(config.tenantRepos)) {
throw createContractError(
'KB_TENANT_REPOS_INVALID',
'Tenant repo config tenantRepos must be an array'
);
}
return {
...config,
tenantRepos: config.tenantRepos.map(entry => normalizeTenantRepoEntry(entry))
};
}
/**
* @summary Derives the credential-free local mirror path for a tenant repo.
*
* This helper intentionally only maps already-normalized identity values to a filesystem path.
* Git clone/fetch lifecycle and credential injection remain owned by the Git mirror primitive (#11788).
*
* @param {Object} data
* @param {String} data.mirrorRoot Root directory for tenant repo mirrors.
* @param {String} data.tenantId Tenant id.
* @param {String} data.repoSlug Clean repo slug.
* @returns {String}
*/
export function deriveTenantRepoMirrorPath({mirrorRoot, tenantId, repoSlug} = {}) {
const root = String(mirrorRoot || '').trim();
if (!root) {
throw createContractError(
'KB_TENANT_REPO_MIRROR_ROOT_REQUIRED',
'Tenant repo mirror path requires mirrorRoot'
);
}
const tenantSegment = normalizeMirrorPathSegment(
tenantId,
'KB_TENANT_REPO_MIRROR_TENANT_INVALID',
'tenantId'
);
const repoSegments = normalizeRepoSlug(repoSlug)
.split('/')
.map(segment => normalizeMirrorPathSegment(
segment,
'KB_TENANT_REPO_MIRROR_REPO_INVALID',
'repoSlug segment'
));
return path.join(root, 'tenant-repos', tenantSegment, ...repoSegments);
}
/**
* @summary Redacts tenant repo credentials from strings or structured log payloads.
*
* This is deliberately small: it strips URL/scp-style userinfo and replaces explicit secret hints.
* The helper is for defensive log formatting; credential acquisition remains outside this module.
*
* @param {*} input String, array, object, or primitive to redact.
* @param {Object} [options]
* @param {String[]} [options.secretHints] Optional known secret values to replace.
* @returns {*} A redacted copy of `input`.
*/
export function redactTenantRepoSecrets(input, {secretHints = []} = {}) {
if (typeof input === 'string') {
let redacted = input
.replace(/([a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/giu, `$1${SECRET_REPLACEMENT}@`)
.replace(/(^|\s)([^/\s@:]+)@([^/\s@:]+:)/gu, `$1${SECRET_REPLACEMENT}@$3`);
for (const secret of secretHints) {
if (typeof secret === 'string' && secret.length > 0) {
redacted = redacted.replace(new RegExp(escapeRegExp(secret), 'gu'), SECRET_REPLACEMENT);
}
}
return redacted;
}
if (Array.isArray(input)) {
return input.map(item => redactTenantRepoSecrets(item, {secretHints}));
}
if (input && typeof input === 'object') {
return Object.fromEntries(
Object.entries(input).map(([key, value]) => [key, redactTenantRepoSecrets(value, {secretHints})])
);
}
return input;
}