@sfxcode/mongocamp-server-core 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -9
- package/dist/index.d.mts +166 -34
- package/dist/index.mjs +433 -120
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -437,6 +437,12 @@ function resolveTarget(source, target, defaultDatabase, systemPrefix) {
|
|
|
437
437
|
return resolved;
|
|
438
438
|
}
|
|
439
439
|
|
|
440
|
+
const consoleLogger = {
|
|
441
|
+
info: (message) => console.info(message),
|
|
442
|
+
warn: (message) => console.warn(message),
|
|
443
|
+
error: (message, error) => error === void 0 ? console.error(message) : console.error(message, error)
|
|
444
|
+
};
|
|
445
|
+
|
|
440
446
|
const DefaultJobGroup = "Default";
|
|
441
447
|
const DefaultJobPriority = 1;
|
|
442
448
|
const CleanUpTokenJobClass = "dev.mongocamp.server.jobs.CleanUpTokenJob";
|
|
@@ -456,11 +462,12 @@ function sameConfig(a, b) {
|
|
|
456
462
|
return a.className === b.className && a.cronExpression === b.cronExpression && a.description === b.description && a.priority === b.priority;
|
|
457
463
|
}
|
|
458
464
|
class JobScheduler {
|
|
459
|
-
constructor(database, events, handlers, options) {
|
|
465
|
+
constructor(database, events, handlers, options, logger = consoleLogger) {
|
|
460
466
|
this.database = database;
|
|
461
467
|
this.events = events;
|
|
462
468
|
this.handlers = handlers;
|
|
463
469
|
this.options = options;
|
|
470
|
+
this.logger = logger;
|
|
464
471
|
}
|
|
465
472
|
entries = /* @__PURE__ */ new Map();
|
|
466
473
|
timer;
|
|
@@ -474,7 +481,7 @@ class JobScheduler {
|
|
|
474
481
|
await this.refresh();
|
|
475
482
|
if (this.options.refresh !== false) {
|
|
476
483
|
this.timer = setInterval(() => {
|
|
477
|
-
this.refresh().catch((error) =>
|
|
484
|
+
this.refresh().catch((error) => this.logger.error("could not read the jobs", error));
|
|
478
485
|
}, this.options.refresh);
|
|
479
486
|
this.timer.unref?.();
|
|
480
487
|
}
|
|
@@ -525,7 +532,7 @@ class JobScheduler {
|
|
|
525
532
|
await handler({ config: entry.config, startedAt, manual });
|
|
526
533
|
} catch (error) {
|
|
527
534
|
failure = error;
|
|
528
|
-
|
|
535
|
+
this.logger.error(`job ${entry.config.name} in group ${entry.config.group} failed`, error);
|
|
529
536
|
}
|
|
530
537
|
this.events.publish("job:executed", {
|
|
531
538
|
jobName: entry.config.name,
|
|
@@ -559,6 +566,27 @@ class JobScheduler {
|
|
|
559
566
|
list() {
|
|
560
567
|
return [...this.entries.values()].sort((a, b) => a.config.group.localeCompare(b.config.group) || a.config.name.localeCompare(b.config.name)).map((entry) => this.information(entry));
|
|
561
568
|
}
|
|
569
|
+
/**
|
|
570
|
+
* Adds the handler of a class name at runtime (a host that gets the server after its start, e.g. a Nuxt application through
|
|
571
|
+
* `useMongocampCore()`). The stored jobs of that class are scheduled now; the returned function removes the handler again and stops them.
|
|
572
|
+
*/
|
|
573
|
+
registerHandler(className, handler) {
|
|
574
|
+
this.handlers.set(className, handler);
|
|
575
|
+
this.rescheduleClass(className);
|
|
576
|
+
return () => {
|
|
577
|
+
if (this.handlers.get(className) === handler) {
|
|
578
|
+
this.handlers.delete(className);
|
|
579
|
+
this.rescheduleClass(className);
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
rescheduleClass(className) {
|
|
584
|
+
for (const entry of [...this.entries.values()]) {
|
|
585
|
+
if (entry.config.className === className) {
|
|
586
|
+
this.schedule(entry.config, entry.lastRun);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
562
590
|
classes() {
|
|
563
591
|
return [...this.handlers.keys()].sort();
|
|
564
592
|
}
|
|
@@ -651,6 +679,7 @@ function toConfig(document) {
|
|
|
651
679
|
}
|
|
652
680
|
|
|
653
681
|
const QuartzCleanUpExpression = "0 0/5 * ? * * *";
|
|
682
|
+
const RemovedPluginSettings = ["PLUGINS_IGNORED", "PLUGINS_URLS", "PLUGINS_DIRECTORY", "PLUGINS_MODULES", "PLUGINS_MAVEN_REPOSITORIES", "HTTP_CLIENT_HEADERS"];
|
|
654
683
|
async function dropScalaLeftovers(database) {
|
|
655
684
|
const db = database.db();
|
|
656
685
|
const quartzPrefix = database.internalCollectionName("jobs_");
|
|
@@ -661,7 +690,8 @@ async function dropScalaLeftovers(database) {
|
|
|
661
690
|
const tokens = await db.collection(database.internalCollectionName("token_cache")).deleteMany({ token: { $not: /^[0-9a-f]{64}$/ } });
|
|
662
691
|
const { group, name } = CleanUpTokenJob;
|
|
663
692
|
const jobs = await db.collection(database.internalCollectionName("jobs")).updateOne({ group, name, cronExpression: QuartzCleanUpExpression }, { $set: { cronExpression: CleanUpTokenJob.cronExpression } });
|
|
664
|
-
|
|
693
|
+
const settings = await db.collection(database.internalCollectionName("configuration")).deleteMany({ key: { $in: RemovedPluginSettings } });
|
|
694
|
+
return { droppedCollections, removedTokenEntries: tokens.deletedCount, rewrittenJobs: jobs.modifiedCount, removedSettings: settings.deletedCount };
|
|
665
695
|
}
|
|
666
696
|
|
|
667
697
|
const instantPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|([+-])(\d{2}):(\d{2}))$/;
|
|
@@ -720,12 +750,6 @@ const ConfigKeys = {
|
|
|
720
750
|
ServerInterface: "SERVER_INTERFACE",
|
|
721
751
|
ServerPort: "SERVER_PORT",
|
|
722
752
|
AggregationStagesDenied: "AGGREGATION_STAGES_DENIED",
|
|
723
|
-
PluginsIgnored: "PLUGINS_IGNORED",
|
|
724
|
-
PluginsDirectory: "PLUGINS_DIRECTORY",
|
|
725
|
-
PluginsUrls: "PLUGINS_URLS",
|
|
726
|
-
PluginsModules: "PLUGINS_MODULES",
|
|
727
|
-
PluginsMavenRepositories: "PLUGINS_MAVEN_REPOSITORIES",
|
|
728
|
-
HttpClientHeaders: "HTTP_CLIENT_HEADERS",
|
|
729
753
|
AuthHandler: "AUTH_HANDLER",
|
|
730
754
|
AuthSecret: "AUTH_SECRET",
|
|
731
755
|
AuthApiKeyLength: "AUTH_APIKEYLENGTH",
|
|
@@ -738,6 +762,8 @@ const ConfigKeys = {
|
|
|
738
762
|
FilterTimeZone: "FILTER_TIME_ZONE",
|
|
739
763
|
// new in 2.0.0: drop what the Scala server left in the database at the start (`system/scala-leftovers.ts`)
|
|
740
764
|
MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS",
|
|
765
|
+
// new in 2.1.0: whether this instance runs the jobs on their schedule (not persistent: a stored value would switch every instance)
|
|
766
|
+
JobsEnabled: "JOBS_ENABLED",
|
|
741
767
|
AuthPrefix: "AUTH_PREFIX",
|
|
742
768
|
AuthBearer: "AUTH_BEARER",
|
|
743
769
|
AuthBasic: "AUTH_BASIC",
|
|
@@ -770,6 +796,8 @@ const ConfigKeys = {
|
|
|
770
796
|
MetricsMongoDbCommand: "METRICS_MONGODB_COMMAND",
|
|
771
797
|
MetricsMongoDbConnectionPool: "METRICS_MONGODB_CONNECTIONPOOL",
|
|
772
798
|
LoggingMetricsStep: "LOGGING_METRICS_MONGODB_STEP",
|
|
799
|
+
// 2.1.0: the snapshots of the Node runtime; LOGGING_METRICS_MONGODB_JVM is its deprecated alias (removed in 3.0)
|
|
800
|
+
LoggingMetricsRuntime: "LOGGING_METRICS_MONGODB_RUNTIME",
|
|
773
801
|
LoggingMetricsJvm: "LOGGING_METRICS_MONGODB_JVM",
|
|
774
802
|
LoggingMetricsSystem: "LOGGING_METRICS_MONGODB_SYSTEM",
|
|
775
803
|
LoggingMetricsMongo: "LOGGING_METRICS_MONGODB_MONGO",
|
|
@@ -791,12 +819,6 @@ const configDefinitions = [
|
|
|
791
819
|
define(K.ServerInterface, "String", "0.0.0.0", restart),
|
|
792
820
|
define(K.ServerPort, "Long", 8080, restart),
|
|
793
821
|
define(K.AggregationStagesDenied, "List[String]", ["$function", "$accumulator", "$where", "$out", "$merge", "$currentOp", "$listSessions", "$collStats", "$indexStats"]),
|
|
794
|
-
define(K.PluginsIgnored, "List[String]", [], restart),
|
|
795
|
-
define(K.PluginsUrls, "List[String]", [], restart),
|
|
796
|
-
define(K.PluginsDirectory, "String", "/opt/mongocamp/plugins", restart),
|
|
797
|
-
define(K.PluginsModules, "List[String]", [], restart),
|
|
798
|
-
define(K.PluginsMavenRepositories, "List[String]", [], restart),
|
|
799
|
-
define(K.HttpClientHeaders, "String", "{}"),
|
|
800
822
|
define(K.AuthHandler, "String", "mongo", restart),
|
|
801
823
|
// the Scala server registers a random secret (not the `secret_key` of reference.conf); it is persisted, so it survives restarts
|
|
802
824
|
define(K.AuthSecret, "String", () => randomAlphanumeric$1(32)),
|
|
@@ -804,10 +826,12 @@ const configDefinitions = [
|
|
|
804
826
|
define(K.AuthCacheDb, "Boolean", true),
|
|
805
827
|
define(K.AuthExpiringDuration, "Duration", 6 * 36e5),
|
|
806
828
|
define(K.AuthRefreshGraceDuration, "Duration", 6e4),
|
|
807
|
-
|
|
829
|
+
// 2.1.0: 403 by default, a user who only lacks a grant keeps the session (401 clears it in the clients); 401 stays configurable
|
|
830
|
+
define(K.AuthGrantDeniedStatus, "Long", 403),
|
|
808
831
|
define(K.ImportMaxBytes, "Long", 1073741824),
|
|
809
832
|
define(K.FilterTimeZone, "String", "UTC"),
|
|
810
833
|
define(K.MigrationDropScalaLeftovers, "Boolean", false, nonPersistent),
|
|
834
|
+
define(K.JobsEnabled, "Boolean", true, nonPersistent),
|
|
811
835
|
define(K.AuthBearer, "Boolean", true, restart),
|
|
812
836
|
define(K.AuthBasic, "Boolean", true, restart),
|
|
813
837
|
define(K.AuthToken, "Boolean", true, restart),
|
|
@@ -830,6 +854,7 @@ const configDefinitions = [
|
|
|
830
854
|
define(K.MetricsMongoDbCommand, "Boolean", false, restart),
|
|
831
855
|
define(K.MetricsMongoDbConnectionPool, "Boolean", false, restart),
|
|
832
856
|
define(K.LoggingMetricsStep, "Duration", 60 * 6e4, restart),
|
|
857
|
+
define(K.LoggingMetricsRuntime, "Boolean", false, restart),
|
|
833
858
|
define(K.LoggingMetricsJvm, "Boolean", false, restart),
|
|
834
859
|
define(K.LoggingMetricsSystem, "Boolean", false, restart),
|
|
835
860
|
define(K.LoggingMetricsMongo, "Boolean", false, restart),
|
|
@@ -967,7 +992,8 @@ async function verifyNothing(password) {
|
|
|
967
992
|
}
|
|
968
993
|
|
|
969
994
|
const AuthErrors = {
|
|
970
|
-
|
|
995
|
+
// 2.1.0: names the user (the Scala text had an empty name)
|
|
996
|
+
userNotFound: (userId) => new MongocampError(`user ${userId} does not exist`, 404),
|
|
971
997
|
userOrPassword: () => new MongocampError("user or password does not exists", 401),
|
|
972
998
|
apiKey: () => new MongocampError("apiKey not valid", 401),
|
|
973
999
|
badConfiguration: () => new MongocampError("Authentication method not configured correctly", 501, 5001)
|
|
@@ -975,7 +1001,7 @@ const AuthErrors = {
|
|
|
975
1001
|
async function findUser(holder, userId) {
|
|
976
1002
|
const user = await holder.findUserOption(userId);
|
|
977
1003
|
if (!user) {
|
|
978
|
-
throw AuthErrors.userNotFound();
|
|
1004
|
+
throw AuthErrors.userNotFound(userId);
|
|
979
1005
|
}
|
|
980
1006
|
return user;
|
|
981
1007
|
}
|
|
@@ -1017,7 +1043,7 @@ class MongoAuthHolder {
|
|
|
1017
1043
|
return this.database.db().collection(this.database.internalCollectionName("roles"));
|
|
1018
1044
|
}
|
|
1019
1045
|
/** Creates the indexes and, for an empty user collection, the user `admin` with a random password that is printed once. */
|
|
1020
|
-
async createIndicesAndInitData(log = console.
|
|
1046
|
+
async createIndicesAndInitData(log = console.info, warn = console.warn) {
|
|
1021
1047
|
if (await this.users.countDocuments({}, { limit: 1 }) === 0) {
|
|
1022
1048
|
const password = randomAlphanumeric(10);
|
|
1023
1049
|
await this.users.insertOne({ userId: "admin", password: await hashPassword(password), apiKey: null, roles: ["adminRole"] });
|
|
@@ -1035,7 +1061,7 @@ class MongoAuthHolder {
|
|
|
1035
1061
|
}
|
|
1036
1062
|
await this.users.createIndex({ userId: 1 }, { unique: true });
|
|
1037
1063
|
await this.rolesCollection.createIndex({ name: 1 }, { unique: true });
|
|
1038
|
-
await this.createApiKeyIndex();
|
|
1064
|
+
await this.createApiKeyIndex(warn);
|
|
1039
1065
|
}
|
|
1040
1066
|
/**
|
|
1041
1067
|
* Unique index for the api-key lookup, partial on string values (users without a key store `null`). A database in which two users share
|
|
@@ -1395,9 +1421,11 @@ class AuthService {
|
|
|
1395
1421
|
tokens;
|
|
1396
1422
|
/** Key: SHA-256 of user and password; value: the stored hash that was verified, valid while the user still has it. */
|
|
1397
1423
|
basicCache = /* @__PURE__ */ new Map();
|
|
1398
|
-
|
|
1424
|
+
/** The user of a request once it is authenticated, for the fields of its wide event (`userOf`). */
|
|
1425
|
+
requestUsers = /* @__PURE__ */ new WeakMap();
|
|
1426
|
+
async initialize(logger = consoleLogger) {
|
|
1399
1427
|
if (this.holder instanceof MongoAuthHolder) {
|
|
1400
|
-
await this.holder.createIndicesAndInitData();
|
|
1428
|
+
await this.holder.createIndicesAndInitData((message) => logger.info(message), (message) => logger.warn(message));
|
|
1401
1429
|
}
|
|
1402
1430
|
await this.tokens.createIndexes();
|
|
1403
1431
|
}
|
|
@@ -1444,11 +1472,16 @@ class AuthService {
|
|
|
1444
1472
|
/** The logged in user of a request with the current roles. */
|
|
1445
1473
|
async authenticate(request) {
|
|
1446
1474
|
const user = await this.authenticateUser(readCredentials(request));
|
|
1475
|
+
this.requestUsers.set(request, user.userId);
|
|
1447
1476
|
return new AuthorizedUser(user, await this.holder.findRoles(user.roles));
|
|
1448
1477
|
}
|
|
1478
|
+
/** The id of the user a request was authenticated as, `undefined` before (or without) the authentication. */
|
|
1479
|
+
userOf(request) {
|
|
1480
|
+
return this.requestUsers.get(request);
|
|
1481
|
+
}
|
|
1449
1482
|
/** The error for a logged in user without the grant for a request; the status is `AUTH_GRANT_DENIED_STATUS` (403) or 401. */
|
|
1450
1483
|
grantDenied(message) {
|
|
1451
|
-
const status = this.config.number(ConfigKeys.AuthGrantDeniedStatus) ===
|
|
1484
|
+
const status = this.config.number(ConfigKeys.AuthGrantDeniedStatus) === 401 ? 401 : 403;
|
|
1452
1485
|
return new MongocampError(message, status, ErrorCodes.unauthorizedUser);
|
|
1453
1486
|
}
|
|
1454
1487
|
async requireAdmin(request) {
|
|
@@ -1927,6 +1960,7 @@ class EventBus {
|
|
|
1927
1960
|
hooks = createHooks();
|
|
1928
1961
|
listeners = /* @__PURE__ */ new Map();
|
|
1929
1962
|
observers = /* @__PURE__ */ new Set();
|
|
1963
|
+
targets = /* @__PURE__ */ new Set();
|
|
1930
1964
|
/** Registers a listener; the returned function removes it. */
|
|
1931
1965
|
on(name, listener) {
|
|
1932
1966
|
this.listeners.set(name, (this.listeners.get(name) ?? 0) + 1);
|
|
@@ -1947,9 +1981,25 @@ class EventBus {
|
|
|
1947
1981
|
this.observers.delete(observer);
|
|
1948
1982
|
};
|
|
1949
1983
|
}
|
|
1984
|
+
/** Sends the events to a hook system of the host (`forwardToNitro`); the returned function stops it. */
|
|
1985
|
+
forward(target) {
|
|
1986
|
+
this.targets.add(target);
|
|
1987
|
+
return () => {
|
|
1988
|
+
this.targets.delete(target);
|
|
1989
|
+
};
|
|
1990
|
+
}
|
|
1991
|
+
targetsFor(name) {
|
|
1992
|
+
return [...this.targets].filter((target) => {
|
|
1993
|
+
try {
|
|
1994
|
+
return target.listens(name);
|
|
1995
|
+
} catch {
|
|
1996
|
+
return true;
|
|
1997
|
+
}
|
|
1998
|
+
});
|
|
1999
|
+
}
|
|
1950
2000
|
/** Whether anybody listens, so that an expensive payload (old values of documents) is only read when needed. */
|
|
1951
2001
|
has(name) {
|
|
1952
|
-
return (this.listeners.get(name) ?? 0) > 0;
|
|
2002
|
+
return (this.listeners.get(name) ?? 0) > 0 || this.targetsFor(name).length > 0;
|
|
1953
2003
|
}
|
|
1954
2004
|
/** Sends an event without waiting for the listeners; a failure of a listener is logged. */
|
|
1955
2005
|
publish(name, payload) {
|
|
@@ -1960,10 +2010,21 @@ class EventBus {
|
|
|
1960
2010
|
this.log(`an observer failed for event <${name}>`, error);
|
|
1961
2011
|
}
|
|
1962
2012
|
}
|
|
1963
|
-
|
|
2013
|
+
const targets = this.targetsFor(name);
|
|
2014
|
+
if ((this.listeners.get(name) ?? 0) === 0 && targets.length === 0) {
|
|
1964
2015
|
return;
|
|
1965
2016
|
}
|
|
1966
2017
|
const event = { ...payload, id: randomUUID(), eventDate: /* @__PURE__ */ new Date(), name };
|
|
2018
|
+
for (const target of targets) {
|
|
2019
|
+
try {
|
|
2020
|
+
Promise.resolve(target.call(name, event)).catch((error) => this.log(`a hook failed for event <${name}>`, error));
|
|
2021
|
+
} catch (error) {
|
|
2022
|
+
this.log(`a hook failed for event <${name}>`, error);
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
if ((this.listeners.get(name) ?? 0) === 0) {
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
1967
2028
|
try {
|
|
1968
2029
|
const result = this.hooks.callHook(name, event);
|
|
1969
2030
|
Promise.resolve(result).catch((error) => this.log(`could not publish event <${name}>`, error));
|
|
@@ -2032,6 +2093,53 @@ function withCommonHeaders(response, request, config, version, requestId) {
|
|
|
2032
2093
|
}
|
|
2033
2094
|
}
|
|
2034
2095
|
|
|
2096
|
+
const resourcePattern = /^\/mongodb\/(collections|buckets|databases)\/([^/]+)/;
|
|
2097
|
+
function decoded(segment) {
|
|
2098
|
+
try {
|
|
2099
|
+
return decodeURIComponent(segment);
|
|
2100
|
+
} catch {
|
|
2101
|
+
return segment;
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
function requestFields(request, response, fields, user) {
|
|
2105
|
+
const result = { requestId: fields.requestId, operation: fields.methodName, controller: fields.controller };
|
|
2106
|
+
if (user) {
|
|
2107
|
+
result.user = user;
|
|
2108
|
+
}
|
|
2109
|
+
const match = resourcePattern.exec(new URL(request.url).pathname);
|
|
2110
|
+
if (match && match[2] !== "info") {
|
|
2111
|
+
const name = decoded(match[2]);
|
|
2112
|
+
if (match[1] === "collections") {
|
|
2113
|
+
result.collection = name;
|
|
2114
|
+
} else if (match[1] === "buckets") {
|
|
2115
|
+
result.bucket = name;
|
|
2116
|
+
} else if (match[2] !== "infos") {
|
|
2117
|
+
result.database = name;
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
const rows = Number.parseInt(response.headers.get(PaginationHeaders.countRows) ?? "", 10);
|
|
2121
|
+
if (Number.isFinite(rows)) {
|
|
2122
|
+
result.rows = rows;
|
|
2123
|
+
}
|
|
2124
|
+
if (response.status >= 400) {
|
|
2125
|
+
const code = response.headers.get(ErrorHeaders.code);
|
|
2126
|
+
const message = response.headers.get(ErrorHeaders.message);
|
|
2127
|
+
if (code) {
|
|
2128
|
+
result.errorCode = code;
|
|
2129
|
+
}
|
|
2130
|
+
if (message) {
|
|
2131
|
+
result.errorMessage = message;
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
return result;
|
|
2135
|
+
}
|
|
2136
|
+
function addRequestFields(log, request, response, fields, user) {
|
|
2137
|
+
try {
|
|
2138
|
+
log.set({ mongocamp: requestFields(request, response, fields, user) });
|
|
2139
|
+
} catch {
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2035
2143
|
const operations = [
|
|
2036
2144
|
["POST", "/auth/login", "login", "Auth", "Login User"],
|
|
2037
2145
|
["POST", "/auth/logout", "logout", "Auth", "Logout User"],
|
|
@@ -2234,6 +2342,16 @@ function optionalBoolean(body, field) {
|
|
|
2234
2342
|
}
|
|
2235
2343
|
return value;
|
|
2236
2344
|
}
|
|
2345
|
+
function optionalInteger$1(body, field) {
|
|
2346
|
+
const value = body[field];
|
|
2347
|
+
if (value === void 0 || value === null) {
|
|
2348
|
+
return void 0;
|
|
2349
|
+
}
|
|
2350
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) {
|
|
2351
|
+
fail(field);
|
|
2352
|
+
}
|
|
2353
|
+
return value;
|
|
2354
|
+
}
|
|
2237
2355
|
function stringList(value, field) {
|
|
2238
2356
|
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
|
|
2239
2357
|
fail(field);
|
|
@@ -3151,7 +3269,7 @@ function searchMap(query, negated, settings) {
|
|
|
3151
3269
|
appendRange(negated, result, query, settings);
|
|
3152
3270
|
break;
|
|
3153
3271
|
case "term":
|
|
3154
|
-
appendTerm(negated, result, query.field, query.text, settings);
|
|
3272
|
+
appendTerm(negated, result, query.field, query.text, settings, query.quoted === true);
|
|
3155
3273
|
break;
|
|
3156
3274
|
case "prefix":
|
|
3157
3275
|
appendPrefix(negated, result, query.field, query.text, settings.caseInsensitive);
|
|
@@ -3199,10 +3317,16 @@ function appendRange(negated, result, query, settings) {
|
|
|
3199
3317
|
result[field] = { $exists: !negated };
|
|
3200
3318
|
return;
|
|
3201
3319
|
}
|
|
3320
|
+
const nextDay = upper !== null && query.includeUpper ? dayAfter(upper) : void 0;
|
|
3321
|
+
const upperDate = nextDay !== void 0 && convert(upper) instanceof Date ? convert(nextDay) : void 0;
|
|
3202
3322
|
const rangeSearch = (convert2) => {
|
|
3203
3323
|
const range = {};
|
|
3204
3324
|
if (upper !== null) {
|
|
3205
|
-
|
|
3325
|
+
if (upperDate instanceof Date && convert2(upper) instanceof Date) {
|
|
3326
|
+
range.$lt = upperDate;
|
|
3327
|
+
} else {
|
|
3328
|
+
range[query.includeUpper ? "$lte" : "$lt"] = convert2(upper);
|
|
3329
|
+
}
|
|
3206
3330
|
}
|
|
3207
3331
|
if (lower !== null) {
|
|
3208
3332
|
range[query.includeLower ? "$gte" : "$gt"] = convert2(lower);
|
|
@@ -3224,12 +3348,20 @@ function appendRange(negated, result, query, settings) {
|
|
|
3224
3348
|
result[field] = inRange;
|
|
3225
3349
|
}
|
|
3226
3350
|
}
|
|
3227
|
-
function
|
|
3351
|
+
function dayAfter(text) {
|
|
3352
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
|
|
3353
|
+
if (!match) {
|
|
3354
|
+
return void 0;
|
|
3355
|
+
}
|
|
3356
|
+
const next = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]) + 1));
|
|
3357
|
+
return next.toISOString().slice(0, 10);
|
|
3358
|
+
}
|
|
3359
|
+
function appendTerm(negated, result, field, termText, settings, quoted = false) {
|
|
3228
3360
|
if (containsWildcard(termText)) {
|
|
3229
3361
|
appendWildcard(negated, result, field, termText, settings.caseInsensitive);
|
|
3230
3362
|
return;
|
|
3231
3363
|
}
|
|
3232
|
-
const both = settings.both;
|
|
3364
|
+
const both = settings.both || quoted;
|
|
3233
3365
|
const text = termText.includes("*") ? unescape(termText) : termText;
|
|
3234
3366
|
const value = convertTermValue(text, settings.timeZone);
|
|
3235
3367
|
const operator = negated ? "$ne" : "$eq";
|
|
@@ -3244,7 +3376,9 @@ function appendPrefix(negated, result, field, prefix, caseInsensitive) {
|
|
|
3244
3376
|
result[field] = { $exists: !negated };
|
|
3245
3377
|
return;
|
|
3246
3378
|
}
|
|
3247
|
-
|
|
3379
|
+
const regex = anchoredRegex(`${literalToRegex(prefix)}(.*?)`, caseInsensitive);
|
|
3380
|
+
Object.assign(result, textOrNumberMatch(negated, field, regex, prefix));
|
|
3381
|
+
addObjectIdText(negated, result, field, prefix, regex);
|
|
3248
3382
|
}
|
|
3249
3383
|
function appendWildcard(negated, result, field, text, caseInsensitive) {
|
|
3250
3384
|
if (text === "*") {
|
|
@@ -3252,7 +3386,20 @@ function appendWildcard(negated, result, field, text, caseInsensitive) {
|
|
|
3252
3386
|
return;
|
|
3253
3387
|
}
|
|
3254
3388
|
const literals = wildcardTokens(text).filter((token) => token.literal || token.char !== "*" && token.char !== "?").map((token) => token.char).join("");
|
|
3255
|
-
|
|
3389
|
+
const regex = anchoredRegex(wildcardToRegex(text), caseInsensitive);
|
|
3390
|
+
Object.assign(result, textOrNumberMatch(negated, field, regex, literals));
|
|
3391
|
+
addObjectIdText(negated, result, field, literals, regex);
|
|
3392
|
+
}
|
|
3393
|
+
function addObjectIdText(negated, result, field, literals, regex) {
|
|
3394
|
+
if (field !== "_id" || !/^[\da-f]+$/i.test(literals)) {
|
|
3395
|
+
return;
|
|
3396
|
+
}
|
|
3397
|
+
const objectIdMatch = { $expr: { $and: [{ $eq: [{ $type: "$_id" }, "objectId"] }, { $regexMatch: { input: { $toString: "$_id" }, regex: regex.$regex, options: "i" } }] } };
|
|
3398
|
+
const textFilter = { ...result };
|
|
3399
|
+
for (const key of Object.keys(result)) {
|
|
3400
|
+
Reflect.deleteProperty(result, key);
|
|
3401
|
+
}
|
|
3402
|
+
Object.assign(result, negated ? { $and: [textFilter, { $nor: [objectIdMatch] }] } : { $or: [textFilter, objectIdMatch] });
|
|
3256
3403
|
}
|
|
3257
3404
|
function couldBeNumberText(literals) {
|
|
3258
3405
|
return /^[\d.e+-]*$/i.test(literals) && /\d/.test(literals);
|
|
@@ -3799,11 +3946,8 @@ class Parser {
|
|
|
3799
3946
|
return { type: "range", field, lower: null, upper: bound, includeLower: true, includeUpper: true };
|
|
3800
3947
|
}
|
|
3801
3948
|
}
|
|
3802
|
-
if (quoted && text.includes("*")) {
|
|
3803
|
-
return { type: "wildcard", field, text: escapeChars(text, "\\?") };
|
|
3804
|
-
}
|
|
3805
3949
|
if (quoted) {
|
|
3806
|
-
return { type: "term", field, text };
|
|
3950
|
+
return { type: "term", field, text: text.includes("*") ? escapeChars(text, "\\*?") : text, quoted: true };
|
|
3807
3951
|
}
|
|
3808
3952
|
const terms = tokenize(text).map((token) => this.termQuery(field, token.term));
|
|
3809
3953
|
if (terms.length === 0) {
|
|
@@ -3960,7 +4104,7 @@ function registerAdminRoutes(app, context) {
|
|
|
3960
4104
|
const userId = pathParam(event, "userId");
|
|
3961
4105
|
const deleted = await holder.deleteUser(userId);
|
|
3962
4106
|
if (!deleted) {
|
|
3963
|
-
throw AuthErrors.userNotFound();
|
|
4107
|
+
throw AuthErrors.userNotFound(userId);
|
|
3964
4108
|
}
|
|
3965
4109
|
await auth.tokens.invalidateUserTokens(userId);
|
|
3966
4110
|
events.publish("user:delete", { user: admin.user, deletedUser: userId });
|
|
@@ -4475,6 +4619,35 @@ function pagedPipeline(pipeline, skip, rows) {
|
|
|
4475
4619
|
return [...pipeline, ...skip > 0 ? [{ $skip: skip }] : [], { $limit: rows }];
|
|
4476
4620
|
}
|
|
4477
4621
|
|
|
4622
|
+
const SecretUserFields = ["password"];
|
|
4623
|
+
function secretFieldsOf(database, collection) {
|
|
4624
|
+
const name = parseCollectionName(collection);
|
|
4625
|
+
const defaultDatabase = database.db().databaseName;
|
|
4626
|
+
const inDefault = name.database === void 0 || name.database === defaultDatabase;
|
|
4627
|
+
return inDefault && name.name === database.internalCollectionName("users") ? SecretUserFields : [];
|
|
4628
|
+
}
|
|
4629
|
+
function withoutSecrets(document, fields) {
|
|
4630
|
+
if (fields.length === 0 || !fields.some((field) => field in document)) {
|
|
4631
|
+
return document;
|
|
4632
|
+
}
|
|
4633
|
+
return Object.fromEntries(Object.entries(document).filter(([key]) => !fields.includes(key)));
|
|
4634
|
+
}
|
|
4635
|
+
function referencesSecret(value, fields) {
|
|
4636
|
+
if (fields.length === 0) {
|
|
4637
|
+
return false;
|
|
4638
|
+
}
|
|
4639
|
+
if (typeof value === "string") {
|
|
4640
|
+
return fields.some((field) => value === `$${field}` || value.startsWith(`$${field}.`));
|
|
4641
|
+
}
|
|
4642
|
+
if (Array.isArray(value)) {
|
|
4643
|
+
return value.some((entry) => referencesSecret(entry, fields));
|
|
4644
|
+
}
|
|
4645
|
+
if (value !== null && typeof value === "object") {
|
|
4646
|
+
return Object.values(value).some((entry) => referencesSecret(entry, fields));
|
|
4647
|
+
}
|
|
4648
|
+
return false;
|
|
4649
|
+
}
|
|
4650
|
+
|
|
4478
4651
|
function readAggregateRequest(body) {
|
|
4479
4652
|
const object = asObject(body);
|
|
4480
4653
|
if (!Array.isArray(object.pipeline)) {
|
|
@@ -4487,7 +4660,7 @@ function readAggregateRequest(body) {
|
|
|
4487
4660
|
}
|
|
4488
4661
|
return { stage: stage.stage, value: decodeAny(stage.value) };
|
|
4489
4662
|
});
|
|
4490
|
-
return { pipeline, allowDiskUse: optionalBoolean(object, "allowDiskUse") ?? false };
|
|
4663
|
+
return { pipeline, allowDiskUse: optionalBoolean(object, "allowDiskUse") ?? false, filter: optionalString(object, "filter") };
|
|
4491
4664
|
}
|
|
4492
4665
|
function registerAggregationRoutes(app, context) {
|
|
4493
4666
|
const { auth, database, config } = context;
|
|
@@ -4499,26 +4672,39 @@ function registerAggregationRoutes(app, context) {
|
|
|
4499
4672
|
const mode = parseExtendedJsonMode(params.get("extendedJson")) ?? DefaultExtendedJsonMode;
|
|
4500
4673
|
const paging = readPaging(params);
|
|
4501
4674
|
const count = readCountMode(params);
|
|
4502
|
-
const matchFilter = filterParameter(params.get("filter"), filterOptions(params, config));
|
|
4503
4675
|
const request = readAggregateRequest(await readJson(event));
|
|
4676
|
+
const queryFilter = params.get("filter");
|
|
4677
|
+
if (queryFilter !== null && queryFilter.trim() !== "" && request.filter !== void 0 && request.filter.trim() !== "") {
|
|
4678
|
+
throw MongocampError.badRequest("send the filter in the query or in the body, not in both", ErrorCodes.ambiguousFilter);
|
|
4679
|
+
}
|
|
4680
|
+
const matchFilter = request.filter !== void 0 ? bodyFilter(request.filter, filterOptions(params, config)) : filterParameter(queryFilter, filterOptions(params, config));
|
|
4504
4681
|
checkPipeline(user, collection, request.pipeline, config.list(ConfigKeys.AggregationStagesDenied));
|
|
4505
4682
|
const prefix = [];
|
|
4506
4683
|
if (Object.keys(matchFilter).length > 0) {
|
|
4507
4684
|
checkMatchBefore(request.pipeline);
|
|
4508
4685
|
prefix.push({ $match: convertFields(matchFilter) });
|
|
4509
4686
|
}
|
|
4687
|
+
const secrets = secretFieldsOf(database, collection);
|
|
4688
|
+
if (secrets.length > 0) {
|
|
4689
|
+
prefix.unshift({ $unset: [...secrets] });
|
|
4690
|
+
}
|
|
4510
4691
|
const pipeline = [...prefix, ...toBsonPipeline(request.pipeline)];
|
|
4511
4692
|
const { documents, info } = await paginatedAggregation(collectionOf(database, collection), pipeline, request.allowDiskUse, paging, count);
|
|
4512
|
-
return jsonResponse(documents.map((document) => documentToJson(document, mode)), { headers: paginationHeaders(info) });
|
|
4693
|
+
return jsonResponse(documents.map((document) => withoutSecrets(documentToJson(document, mode), secrets)), { headers: paginationHeaders(info) });
|
|
4513
4694
|
});
|
|
4514
4695
|
app.post("/mongodb/collections/:collectionName/distinct/:field", async (event) => {
|
|
4515
4696
|
const collection = collectionParam(event);
|
|
4516
4697
|
await auth.requireCollection(event.req, collection, "read");
|
|
4517
|
-
const
|
|
4698
|
+
const fieldName = pathParam(event, "field");
|
|
4699
|
+
if (secretFieldsOf(database, collection).some((secret) => fieldName === secret || fieldName.startsWith(`${secret}.`))) {
|
|
4700
|
+
throw MongocampError.badRequest(`the field ${fieldName} of the users collection cannot be read`);
|
|
4701
|
+
}
|
|
4702
|
+
const field = `$${fieldName}`;
|
|
4518
4703
|
const pipeline = [{ $group: { _id: field, field: { $first: field } } }];
|
|
4519
4704
|
const params = queryParams(event);
|
|
4520
4705
|
const { documents, info } = await paginatedAggregation(collectionOf(database, collection), pipeline, true, readPaging(params), readCountMode(params));
|
|
4521
|
-
|
|
4706
|
+
const mode = parseExtendedJsonMode(params.get("extendedJson"));
|
|
4707
|
+
return jsonResponse(documents.map((document) => mode === void 0 || mode === "plain" ? legacyValue(document.field) : documentToJson({ v: document.field }, mode).v), { headers: paginationHeaders(info) });
|
|
4522
4708
|
});
|
|
4523
4709
|
}
|
|
4524
4710
|
|
|
@@ -13369,19 +13555,49 @@ function exportCursor(collection, query) {
|
|
|
13369
13555
|
}
|
|
13370
13556
|
return cursor;
|
|
13371
13557
|
}
|
|
13372
|
-
async function* converted(cursor, mode) {
|
|
13558
|
+
async function* converted(cursor, mode, secrets = []) {
|
|
13373
13559
|
for await (const document of cursor) {
|
|
13374
|
-
yield documentToJson(document, mode);
|
|
13560
|
+
yield withoutSecrets(documentToJson(document, mode), secrets);
|
|
13375
13561
|
}
|
|
13376
13562
|
}
|
|
13377
|
-
function
|
|
13563
|
+
function endMarker(format, count) {
|
|
13564
|
+
if (format === "ndjson") {
|
|
13565
|
+
return `${stringifyJson({ $end: true, count })}
|
|
13566
|
+
`;
|
|
13567
|
+
}
|
|
13568
|
+
return format === "csv" ? `# end ${count}\r
|
|
13569
|
+
` : "";
|
|
13570
|
+
}
|
|
13571
|
+
function errorMarker(format, error) {
|
|
13572
|
+
const message = removeInternalNames(error instanceof Error ? error.message : String(error));
|
|
13573
|
+
if (format === "ndjson") {
|
|
13574
|
+
return `${stringifyJson({ $error: message })}
|
|
13575
|
+
`;
|
|
13576
|
+
}
|
|
13577
|
+
return format === "csv" ? `# error ${message.replaceAll(/[\r\n]+/g, " ")}\r
|
|
13578
|
+
` : "";
|
|
13579
|
+
}
|
|
13580
|
+
function exportStream(cursor, format, columns, options = {}) {
|
|
13378
13581
|
const encoder = new TextEncoder();
|
|
13379
|
-
|
|
13582
|
+
let count = 0;
|
|
13583
|
+
async function* counted() {
|
|
13584
|
+
for await (const document of converted(cursor, options.mode, options.secrets)) {
|
|
13585
|
+
count++;
|
|
13586
|
+
yield document;
|
|
13587
|
+
}
|
|
13588
|
+
}
|
|
13589
|
+
const pieces = renderExport(format, counted(), columns);
|
|
13380
13590
|
return new ReadableStream({
|
|
13381
13591
|
async pull(controller) {
|
|
13382
13592
|
try {
|
|
13383
13593
|
const { value, done } = await pieces.next();
|
|
13384
13594
|
if (done) {
|
|
13595
|
+
if (options.trailer) {
|
|
13596
|
+
const marker = endMarker(format, count);
|
|
13597
|
+
if (marker) {
|
|
13598
|
+
controller.enqueue(encoder.encode(marker));
|
|
13599
|
+
}
|
|
13600
|
+
}
|
|
13385
13601
|
controller.close();
|
|
13386
13602
|
await cursor.close();
|
|
13387
13603
|
} else {
|
|
@@ -13390,7 +13606,15 @@ function exportStream(cursor, format, columns, mode) {
|
|
|
13390
13606
|
} catch (error) {
|
|
13391
13607
|
await cursor.close().catch(() => {
|
|
13392
13608
|
});
|
|
13393
|
-
|
|
13609
|
+
if (options.trailer) {
|
|
13610
|
+
const marker = errorMarker(format, error);
|
|
13611
|
+
if (marker) {
|
|
13612
|
+
controller.enqueue(encoder.encode(marker));
|
|
13613
|
+
}
|
|
13614
|
+
controller.close();
|
|
13615
|
+
} else {
|
|
13616
|
+
controller.error(error);
|
|
13617
|
+
}
|
|
13394
13618
|
}
|
|
13395
13619
|
},
|
|
13396
13620
|
async cancel() {
|
|
@@ -13574,8 +13798,8 @@ function requireMatched(count) {
|
|
|
13574
13798
|
throw MongocampError.notFound("could not find document");
|
|
13575
13799
|
}
|
|
13576
13800
|
}
|
|
13577
|
-
function pageResponse(page) {
|
|
13578
|
-
return jsonResponse(page.items, { headers: paginationHeaders(page.info) });
|
|
13801
|
+
function pageResponse(page, secrets = []) {
|
|
13802
|
+
return jsonResponse(page.items.map((item) => withoutSecrets(item, secrets)), { headers: paginationHeaders(page.info) });
|
|
13579
13803
|
}
|
|
13580
13804
|
function extendedJsonMode(params) {
|
|
13581
13805
|
return parseExtendedJsonMode(params.get("extendedJson")) ?? DefaultExtendedJsonMode;
|
|
@@ -13661,7 +13885,7 @@ function registerDocumentRoutes(app, context) {
|
|
|
13661
13885
|
sort: sortFromList(params.getAll("sort")),
|
|
13662
13886
|
projection: projectionFromList(params.getAll("projection"))
|
|
13663
13887
|
};
|
|
13664
|
-
return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), extendedJsonMode(params), readCountMode(params)));
|
|
13888
|
+
return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), extendedJsonMode(params), readCountMode(params)), secretFieldsOf(database, collection));
|
|
13665
13889
|
});
|
|
13666
13890
|
app.get(`${base}/count`, async (event) => {
|
|
13667
13891
|
const collection = collectionParam(event);
|
|
@@ -13670,6 +13894,14 @@ function registerDocumentRoutes(app, context) {
|
|
|
13670
13894
|
const filter = convertFields(filterParameter(params.get("filter"), filterOptions(params, config)));
|
|
13671
13895
|
return jsonResponse({ count: await collectionOf(database, collection).countDocuments(filter) });
|
|
13672
13896
|
});
|
|
13897
|
+
app.post(`${base}/count`, async (event) => {
|
|
13898
|
+
const collection = collectionParam(event);
|
|
13899
|
+
await auth.requireCollection(event.req, collection, "read");
|
|
13900
|
+
const params = queryParams(event);
|
|
13901
|
+
const body = asObject(await readJson(event));
|
|
13902
|
+
const filter = convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config)));
|
|
13903
|
+
return jsonResponse({ count: await collectionOf(database, collection).countDocuments(filter) });
|
|
13904
|
+
});
|
|
13673
13905
|
app.post(`${base}/search`, async (event) => {
|
|
13674
13906
|
const collection = collectionParam(event);
|
|
13675
13907
|
await auth.requireCollection(event.req, collection, "read");
|
|
@@ -13681,7 +13913,7 @@ function registerDocumentRoutes(app, context) {
|
|
|
13681
13913
|
sort: sortFromList(stringListField(body, "sort")),
|
|
13682
13914
|
projection: projectionFromList(stringListField(body, "projection"))
|
|
13683
13915
|
};
|
|
13684
|
-
return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)));
|
|
13916
|
+
return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)), secretFieldsOf(database, collection));
|
|
13685
13917
|
});
|
|
13686
13918
|
app.post(base, async (event) => {
|
|
13687
13919
|
const collection = collectionParam(event);
|
|
@@ -13694,7 +13926,10 @@ function registerDocumentRoutes(app, context) {
|
|
|
13694
13926
|
sort: mapField(body, "sort", true),
|
|
13695
13927
|
projection: mapField(body, "projection", true)
|
|
13696
13928
|
};
|
|
13697
|
-
|
|
13929
|
+
if (referencesSecret(request.projection, secretFieldsOf(database, collection))) {
|
|
13930
|
+
throw MongocampError.badRequest("the projection must not read the password of the users collection");
|
|
13931
|
+
}
|
|
13932
|
+
return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)), secretFieldsOf(database, collection));
|
|
13698
13933
|
});
|
|
13699
13934
|
app.put(base, async (event) => {
|
|
13700
13935
|
const collection = collectionParam(event);
|
|
@@ -13711,7 +13946,7 @@ function registerDocumentRoutes(app, context) {
|
|
|
13711
13946
|
if (!document) {
|
|
13712
13947
|
throw MongocampError.notFound("could not find document");
|
|
13713
13948
|
}
|
|
13714
|
-
return jsonResponse(documentToJson(document, mode));
|
|
13949
|
+
return jsonResponse(withoutSecrets(documentToJson(document, mode), secretFieldsOf(database, collection)));
|
|
13715
13950
|
});
|
|
13716
13951
|
app.delete(`${base}/:documentId`, async (event) => {
|
|
13717
13952
|
const collection = collectionParam(event);
|
|
@@ -13742,37 +13977,54 @@ function registerDocumentRoutes(app, context) {
|
|
|
13742
13977
|
requireMatched(result.matchedCount);
|
|
13743
13978
|
return updated(user, collection, updateResponse(result, id), old.slice(0, 1));
|
|
13744
13979
|
});
|
|
13745
|
-
|
|
13746
|
-
const collection = collectionParam(event);
|
|
13747
|
-
await auth.requireCollection(event.req, collection, "read");
|
|
13748
|
-
const params = queryParams(event);
|
|
13980
|
+
const exportResponse = async (collection, params, request) => {
|
|
13749
13981
|
const format = parseExportFormat(params.get("format"));
|
|
13750
13982
|
const mode = parseExtendedJsonMode(params.get("extendedJson")) ?? (format === "csv" ? "plain" : DefaultExtendedJsonMode);
|
|
13751
|
-
|
|
13752
|
-
if (limit !== void 0 && limit <= 0) {
|
|
13983
|
+
if (request.limit !== void 0 && request.limit <= 0) {
|
|
13753
13984
|
throw MongocampError.badRequest("limit has to be greater than 0");
|
|
13754
13985
|
}
|
|
13755
|
-
const projectionFields = params.getAll("projection");
|
|
13756
13986
|
const query = {
|
|
13757
|
-
filter: convertFields(
|
|
13758
|
-
sort: sortFromList(
|
|
13759
|
-
projection: projectionFromList(
|
|
13760
|
-
limit
|
|
13987
|
+
filter: convertFields(request.filter),
|
|
13988
|
+
sort: sortFromList(request.sort),
|
|
13989
|
+
projection: projectionFromList(request.projection),
|
|
13990
|
+
limit: request.limit
|
|
13761
13991
|
};
|
|
13762
13992
|
const target = collectionOf(database, collection);
|
|
13993
|
+
const secrets = secretFieldsOf(database, collection);
|
|
13763
13994
|
let columns = [];
|
|
13764
13995
|
if (format === "csv") {
|
|
13765
|
-
columns =
|
|
13766
|
-
if (
|
|
13996
|
+
columns = request.projection.length > 0 ? request.projection : await columnNames(target, ColumnSample);
|
|
13997
|
+
if (request.projection.length === 0 && columns.includes("_id")) {
|
|
13767
13998
|
columns = ["_id", ...columns.filter((column) => column !== "_id")];
|
|
13768
13999
|
}
|
|
14000
|
+
columns = columns.filter((column) => !secrets.includes(column));
|
|
13769
14001
|
}
|
|
13770
|
-
|
|
14002
|
+
const trailer = booleanQuery(params, "trailer", false);
|
|
14003
|
+
return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer }), {
|
|
13771
14004
|
headers: {
|
|
13772
14005
|
"content-type": "text/plain; charset=UTF-8",
|
|
13773
14006
|
"content-disposition": `attachment; filename="${exportFileName(collection, format)}"`
|
|
13774
14007
|
}
|
|
13775
14008
|
});
|
|
14009
|
+
};
|
|
14010
|
+
app.get(`${base}/export`, async (event) => {
|
|
14011
|
+
const collection = collectionParam(event);
|
|
14012
|
+
await auth.requireCollection(event.req, collection, "read");
|
|
14013
|
+
const params = queryParams(event);
|
|
14014
|
+
const filter = filterParameter(params.get("filter"), filterOptions(params, config));
|
|
14015
|
+
return exportResponse(collection, params, { filter, sort: params.getAll("sort"), projection: params.getAll("projection"), limit: intQuery(params, "limit") });
|
|
14016
|
+
});
|
|
14017
|
+
app.post(`${base}/export`, async (event) => {
|
|
14018
|
+
const collection = collectionParam(event);
|
|
14019
|
+
await auth.requireCollection(event.req, collection, "read");
|
|
14020
|
+
const params = queryParams(event);
|
|
14021
|
+
const body = asObject(await readJson(event));
|
|
14022
|
+
return exportResponse(collection, params, {
|
|
14023
|
+
filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config)),
|
|
14024
|
+
sort: stringListField(body, "sort"),
|
|
14025
|
+
projection: stringListField(body, "projection"),
|
|
14026
|
+
limit: optionalInteger$1(body, "limit")
|
|
14027
|
+
});
|
|
13776
14028
|
});
|
|
13777
14029
|
app.post(`${base}/import`, async (event) => {
|
|
13778
14030
|
const collection = collectionParam(event);
|
|
@@ -14258,26 +14510,38 @@ function registerJobRoutes(app, context) {
|
|
|
14258
14510
|
}
|
|
14259
14511
|
|
|
14260
14512
|
function registerMonitoringRoutes(app, context) {
|
|
14261
|
-
const
|
|
14262
|
-
|
|
14263
|
-
|
|
14264
|
-
|
|
14265
|
-
|
|
14513
|
+
const enabled = () => {
|
|
14514
|
+
if (!context.metrics) {
|
|
14515
|
+
throw MongocampError.notFound("Not Found");
|
|
14516
|
+
}
|
|
14517
|
+
return context.metrics;
|
|
14518
|
+
};
|
|
14519
|
+
const paths = { runtime: "runtime", system: "system", mongodb: "mongodb", events: "events" };
|
|
14266
14520
|
for (const [path, category] of Object.entries(paths)) {
|
|
14267
14521
|
app.get(`/system/monitoring/${path}`, async (event) => {
|
|
14522
|
+
const metrics = enabled();
|
|
14268
14523
|
await context.auth.requireAdmin(event.req);
|
|
14269
14524
|
return jsonResponse(await metrics.json(category));
|
|
14270
14525
|
});
|
|
14271
14526
|
}
|
|
14527
|
+
app.get("/system/monitoring/jvm", async (event) => {
|
|
14528
|
+
const metrics = enabled();
|
|
14529
|
+
await context.auth.requireAdmin(event.req);
|
|
14530
|
+
const response = jsonResponse(await metrics.json("runtime"));
|
|
14531
|
+
response.headers.set("deprecation", "true");
|
|
14532
|
+
response.headers.set("link", '</system/monitoring/runtime>; rel="successor-version"');
|
|
14533
|
+
return response;
|
|
14534
|
+
});
|
|
14272
14535
|
app.get("/system/monitoring/prometheus", async (event) => {
|
|
14536
|
+
const metrics = enabled();
|
|
14273
14537
|
await context.auth.requireAdmin(event.req);
|
|
14274
14538
|
const { text, contentType } = await metrics.prometheus();
|
|
14275
14539
|
return new Response(text, { headers: { "content-type": contentType } });
|
|
14276
14540
|
});
|
|
14277
14541
|
}
|
|
14278
14542
|
|
|
14279
|
-
const MetricCategories = ["
|
|
14280
|
-
const MonitoringCollections = {
|
|
14543
|
+
const MetricCategories = ["runtime", "system", "mongodb", "events"];
|
|
14544
|
+
const MonitoringCollections = { runtime: "monitoring_runtime", system: "monitoring_system", mongodb: "monitoring_mongo_db", events: "monitoring_event" };
|
|
14281
14545
|
const baseUnitOf = (name) => name.endsWith("_seconds") || name.endsWith("_seconds_total") ? "seconds" : name.endsWith("_bytes") || name.endsWith("_bytes_total") ? "bytes" : "";
|
|
14282
14546
|
function labelsOf(value, without = []) {
|
|
14283
14547
|
return Object.fromEntries(Object.entries(value.labels ?? {}).filter(([key]) => !without.includes(key)).map(([key, entry]) => [key, String(entry)]));
|
|
@@ -14509,7 +14773,7 @@ class MongocampMetrics {
|
|
|
14509
14773
|
}
|
|
14510
14774
|
async json(category) {
|
|
14511
14775
|
switch (category) {
|
|
14512
|
-
case "
|
|
14776
|
+
case "runtime":
|
|
14513
14777
|
return toMetrics((await this.runtime.getMetricsAsJSON()).filter((entry) => entry.name.startsWith("nodejs_")));
|
|
14514
14778
|
case "system":
|
|
14515
14779
|
return toMetrics((await this.runtime.getMetricsAsJSON()).filter((entry) => !entry.name.startsWith("nodejs_")));
|
|
@@ -14526,8 +14790,7 @@ class MongocampMetrics {
|
|
|
14526
14790
|
/** Writes a snapshot of the enabled categories every `LOGGING_METRICS_MONGODB_STEP`. */
|
|
14527
14791
|
startPersistence() {
|
|
14528
14792
|
const { config } = this.context;
|
|
14529
|
-
const enabled = MetricCategories.filter((category) => config.boolean({
|
|
14530
|
-
jvm: ConfigKeys.LoggingMetricsJvm,
|
|
14793
|
+
const enabled = MetricCategories.filter((category) => category === "runtime" ? config.boolean(ConfigKeys.LoggingMetricsRuntime) || config.boolean(ConfigKeys.LoggingMetricsJvm) : config.boolean({
|
|
14531
14794
|
system: ConfigKeys.LoggingMetricsSystem,
|
|
14532
14795
|
mongodb: ConfigKeys.LoggingMetricsMongo,
|
|
14533
14796
|
events: ConfigKeys.LoggingMetricsEvent
|
|
@@ -14537,7 +14800,7 @@ class MongocampMetrics {
|
|
|
14537
14800
|
}
|
|
14538
14801
|
this.timer = setInterval(() => {
|
|
14539
14802
|
for (const category of enabled) {
|
|
14540
|
-
this.persist(category).catch((error) =>
|
|
14803
|
+
this.persist(category).catch((error) => this.context.logger.error(`could not write the metrics ${category}`, error));
|
|
14541
14804
|
}
|
|
14542
14805
|
}, Math.max(config.number(ConfigKeys.LoggingMetricsStep), 100));
|
|
14543
14806
|
this.timer.unref?.();
|
|
@@ -14579,7 +14842,7 @@ function requestLogEntry(fields, date, application, containerName = hostname())
|
|
|
14579
14842
|
};
|
|
14580
14843
|
}
|
|
14581
14844
|
async function enableRequestLogging(context) {
|
|
14582
|
-
const { database, events, version } = context;
|
|
14845
|
+
const { database, events, version, logger } = context;
|
|
14583
14846
|
const collection = database.db().collection(database.internalCollectionName("request_logging"));
|
|
14584
14847
|
await collection.createIndex({ requestId: 1 });
|
|
14585
14848
|
const inserts = /* @__PURE__ */ new Map();
|
|
@@ -14590,7 +14853,7 @@ async function enableRequestLogging(context) {
|
|
|
14590
14853
|
return write;
|
|
14591
14854
|
};
|
|
14592
14855
|
const removeStart = events.on("http:requestStart", (event) => {
|
|
14593
|
-
const insert = track(collection.insertOne(requestLogEntry(event, event.eventDate, version)).catch((error) =>
|
|
14856
|
+
const insert = track(collection.insertOne(requestLogEntry(event, event.eventDate, version)).catch((error) => logger.error("could not log the request", error)));
|
|
14594
14857
|
inserts.set(event.requestId, insert);
|
|
14595
14858
|
});
|
|
14596
14859
|
const removeCompleted = events.on("http:requestCompleted", async (event) => {
|
|
@@ -14608,6 +14871,24 @@ async function enableRequestLogging(context) {
|
|
|
14608
14871
|
};
|
|
14609
14872
|
}
|
|
14610
14873
|
|
|
14874
|
+
function requestLogging() {
|
|
14875
|
+
return { name: "requestLogging", setup: (context) => enableRequestLogging(context) };
|
|
14876
|
+
}
|
|
14877
|
+
function metrics() {
|
|
14878
|
+
return {
|
|
14879
|
+
name: "metrics",
|
|
14880
|
+
setup: (context) => {
|
|
14881
|
+
const created = new MongocampMetrics(context);
|
|
14882
|
+
context.metrics = created;
|
|
14883
|
+
created.startPersistence();
|
|
14884
|
+
return () => {
|
|
14885
|
+
created.close();
|
|
14886
|
+
context.metrics = void 0;
|
|
14887
|
+
};
|
|
14888
|
+
}
|
|
14889
|
+
};
|
|
14890
|
+
}
|
|
14891
|
+
|
|
14611
14892
|
function registerInformationRoutes(app, context) {
|
|
14612
14893
|
app.get("/version", () => jsonResponse({
|
|
14613
14894
|
name: context.version.name,
|
|
@@ -14728,7 +15009,7 @@ async function systemStats(admin) {
|
|
|
14728
15009
|
function capabilityLimits(config) {
|
|
14729
15010
|
return {
|
|
14730
15011
|
importMaxBytes: config.number(ConfigKeys.ImportMaxBytes),
|
|
14731
|
-
grantDeniedStatus: config.number(ConfigKeys.AuthGrantDeniedStatus) ===
|
|
15012
|
+
grantDeniedStatus: config.number(ConfigKeys.AuthGrantDeniedStatus) === 401 ? 401 : 403
|
|
14732
15013
|
};
|
|
14733
15014
|
}
|
|
14734
15015
|
async function capabilities(config, serverVersion, info) {
|
|
@@ -14761,9 +15042,6 @@ function registerConfigurationRoutes(app, context) {
|
|
|
14761
15042
|
return [definition.key, SecretKeys.has(definition.key) && value !== null && value !== "" ? SecretMask : value];
|
|
14762
15043
|
}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
14763
15044
|
return jsonResponse({
|
|
14764
|
-
routesPlugins: context.routeGroups,
|
|
14765
|
-
filePlugins: ["GridFsFileAdapter"],
|
|
14766
|
-
ignoredPlugins: config.list(ConfigKeys.PluginsIgnored),
|
|
14767
15045
|
configurations: values
|
|
14768
15046
|
});
|
|
14769
15047
|
});
|
|
@@ -14838,38 +15116,46 @@ const defaultVersion = {
|
|
|
14838
15116
|
builtAt: /* @__PURE__ */ new Date()
|
|
14839
15117
|
};
|
|
14840
15118
|
const routeGroups = [
|
|
14841
|
-
|
|
14842
|
-
|
|
14843
|
-
|
|
14844
|
-
|
|
14845
|
-
|
|
14846
|
-
|
|
14847
|
-
|
|
14848
|
-
|
|
14849
|
-
|
|
14850
|
-
|
|
14851
|
-
|
|
14852
|
-
|
|
14853
|
-
|
|
14854
|
-
|
|
15119
|
+
registerInformationRoutes,
|
|
15120
|
+
registerAuthRoutes,
|
|
15121
|
+
registerAdminRoutes,
|
|
15122
|
+
registerConfigurationRoutes,
|
|
15123
|
+
registerSystemRoutes,
|
|
15124
|
+
registerJobRoutes,
|
|
15125
|
+
registerMonitoringRoutes,
|
|
15126
|
+
registerDocsRoutes,
|
|
15127
|
+
registerDatabaseRoutes,
|
|
15128
|
+
registerCollectionRoutes,
|
|
15129
|
+
registerAggregationRoutes,
|
|
15130
|
+
registerDocumentRoutes,
|
|
15131
|
+
registerIndexRoutes,
|
|
15132
|
+
registerBucketRoutes
|
|
14855
15133
|
];
|
|
14856
15134
|
function createApp(context) {
|
|
14857
15135
|
const app = new H3({
|
|
14858
15136
|
// errors are answered and logged (5xx) by toErrorResponse
|
|
14859
15137
|
silent: true,
|
|
14860
|
-
onError: (error) => toErrorResponse(error)
|
|
15138
|
+
onError: (error) => toErrorResponse(error, errorLogger(context.logger))
|
|
14861
15139
|
});
|
|
14862
|
-
for (const
|
|
15140
|
+
for (const register of routeGroups) {
|
|
14863
15141
|
register(app, context);
|
|
14864
15142
|
}
|
|
14865
15143
|
return app;
|
|
14866
15144
|
}
|
|
15145
|
+
function errorLogger(logger) {
|
|
15146
|
+
return (error, status) => {
|
|
15147
|
+
if (status >= 500) {
|
|
15148
|
+
logger.error("[mongocamp]", error);
|
|
15149
|
+
}
|
|
15150
|
+
};
|
|
15151
|
+
}
|
|
14867
15152
|
async function createMongocampServer(options = {}) {
|
|
14868
15153
|
const config = new ConfigStore({ env: options.env, values: options.config });
|
|
14869
15154
|
const database = new MongocampDatabase(config, options);
|
|
14870
15155
|
await database.connect();
|
|
14871
15156
|
const version = { ...defaultVersion, ...options.version };
|
|
14872
|
-
const
|
|
15157
|
+
const logger = options.logger ?? consoleLogger;
|
|
15158
|
+
const events = new EventBus((message, error) => logger.error(message, error));
|
|
14873
15159
|
for (const [name, listener] of Object.entries(options.on ?? {})) {
|
|
14874
15160
|
events.on(name, listener);
|
|
14875
15161
|
}
|
|
@@ -14882,14 +15168,14 @@ async function createMongocampServer(options = {}) {
|
|
|
14882
15168
|
}],
|
|
14883
15169
|
...Object.entries(jobOptions.handlers ?? {})
|
|
14884
15170
|
]);
|
|
14885
|
-
const jobs = new JobScheduler(database, events, handlers, { enabled: jobOptions.enabled ?? true, refresh: jobOptions.refresh ?? 6e4 });
|
|
15171
|
+
const jobs = new JobScheduler(database, events, handlers, { enabled: (jobOptions.enabled ?? true) && config.boolean(ConfigKeys.JobsEnabled), refresh: jobOptions.refresh ?? 6e4 }, logger);
|
|
14886
15172
|
try {
|
|
14887
15173
|
await configurations.initialize(options.configRefresh ?? void 0);
|
|
14888
15174
|
if (config.boolean(ConfigKeys.MigrationDropScalaLeftovers)) {
|
|
14889
15175
|
const leftovers = await dropScalaLeftovers(database);
|
|
14890
|
-
|
|
15176
|
+
logger.info(`[mongocamp] Scala leftovers: dropped ${leftovers.droppedCollections.length} Quartz collections (${leftovers.droppedCollections.join(", ") || "-"}), removed ${leftovers.removedTokenEntries} token entries, rewrote ${leftovers.rewrittenJobs} job expressions, removed ${leftovers.removedSettings} plugin settings`);
|
|
14891
15177
|
}
|
|
14892
|
-
await auth.initialize();
|
|
15178
|
+
await auth.initialize(logger);
|
|
14893
15179
|
await jobs.initialize();
|
|
14894
15180
|
} catch (error) {
|
|
14895
15181
|
jobs.close();
|
|
@@ -14899,6 +15185,7 @@ async function createMongocampServer(options = {}) {
|
|
|
14899
15185
|
}
|
|
14900
15186
|
const context = {
|
|
14901
15187
|
config,
|
|
15188
|
+
logger,
|
|
14902
15189
|
database,
|
|
14903
15190
|
version,
|
|
14904
15191
|
auth,
|
|
@@ -14906,19 +15193,25 @@ async function createMongocampServer(options = {}) {
|
|
|
14906
15193
|
events,
|
|
14907
15194
|
jobs,
|
|
14908
15195
|
systemInfo: buildInfoCache(database.db()),
|
|
14909
|
-
shutdown: options.shutdown
|
|
14910
|
-
routeGroups: routeGroups.map(([name]) => name)
|
|
15196
|
+
shutdown: options.shutdown
|
|
14911
15197
|
};
|
|
14912
15198
|
const cleanups = [];
|
|
14913
|
-
|
|
14914
|
-
|
|
14915
|
-
|
|
15199
|
+
const used = /* @__PURE__ */ new Set();
|
|
15200
|
+
const use = async (feature) => {
|
|
15201
|
+
if (used.has(feature.name)) {
|
|
15202
|
+
return;
|
|
14916
15203
|
}
|
|
14917
|
-
|
|
14918
|
-
|
|
14919
|
-
|
|
14920
|
-
|
|
14921
|
-
|
|
15204
|
+
used.add(feature.name);
|
|
15205
|
+
cleanups.push(await feature.setup(context));
|
|
15206
|
+
};
|
|
15207
|
+
try {
|
|
15208
|
+
if (options.featureSwitches !== false) {
|
|
15209
|
+
for (const [key, feature] of [[ConfigKeys.RequestLoggingEnabled, requestLogging()], [ConfigKeys.MetricsEnabled, metrics()]]) {
|
|
15210
|
+
if (config.boolean(key)) {
|
|
15211
|
+
logger.warn(`[mongocamp] ${key} is deprecated for embedding hosts (removed in 3.0): add the feature with server.use(${feature.name}()), e.g. in a Nitro plugin on mongocamp:ready`);
|
|
15212
|
+
await use(feature);
|
|
15213
|
+
}
|
|
15214
|
+
}
|
|
14922
15215
|
}
|
|
14923
15216
|
} catch (error) {
|
|
14924
15217
|
await Promise.allSettled(cleanups.map((cleanup) => cleanup()));
|
|
@@ -14927,23 +15220,24 @@ async function createMongocampServer(options = {}) {
|
|
|
14927
15220
|
await database.close();
|
|
14928
15221
|
throw error;
|
|
14929
15222
|
}
|
|
14930
|
-
const routeGroupNames = routeGroups.filter(([name]) => name !== "MetricsRoutes" || context.metrics).map(([name]) => name);
|
|
14931
|
-
context.routeGroups = routeGroupNames;
|
|
14932
15223
|
const app = createApp(context);
|
|
14933
15224
|
const requestEvents = new RequestEvents(events, auth);
|
|
14934
|
-
const fetch = async (request) => {
|
|
15225
|
+
const fetch = async (request, fetchOptions = {}) => {
|
|
14935
15226
|
if (request.method === "OPTIONS") {
|
|
14936
15227
|
return preflightResponse(request, config);
|
|
14937
15228
|
}
|
|
14938
|
-
const requestId = newRequestId();
|
|
15229
|
+
const requestId = fetchOptions.requestId || newRequestId();
|
|
14939
15230
|
const start = await requestEvents.started(request, requestId);
|
|
14940
15231
|
let response;
|
|
14941
15232
|
try {
|
|
14942
15233
|
response = await app.fetch(request);
|
|
14943
15234
|
} catch (error) {
|
|
14944
|
-
response = toErrorResponse(error);
|
|
15235
|
+
response = toErrorResponse(error, errorLogger(logger));
|
|
14945
15236
|
}
|
|
14946
15237
|
requestEvents.completed(start, response);
|
|
15238
|
+
if (fetchOptions.log) {
|
|
15239
|
+
addRequestFields(fetchOptions.log, request, response, start.fields, auth.userOf(request));
|
|
15240
|
+
}
|
|
14947
15241
|
return withCommonHeaders(response, request, config, context.version, requestId);
|
|
14948
15242
|
};
|
|
14949
15243
|
events.publish("server:started", {});
|
|
@@ -14951,6 +15245,8 @@ async function createMongocampServer(options = {}) {
|
|
|
14951
15245
|
fetch,
|
|
14952
15246
|
context,
|
|
14953
15247
|
events,
|
|
15248
|
+
registerJobHandler: (className, handler) => jobs.registerHandler(className, handler),
|
|
15249
|
+
use,
|
|
14954
15250
|
routes: () => app["~routes"].filter((route) => route.route && route.method).map((route) => `${route.method} ${route.route}`),
|
|
14955
15251
|
close: async () => {
|
|
14956
15252
|
await Promise.allSettled(cleanups.map((cleanup) => cleanup()));
|
|
@@ -14961,4 +15257,21 @@ async function createMongocampServer(options = {}) {
|
|
|
14961
15257
|
};
|
|
14962
15258
|
}
|
|
14963
15259
|
|
|
14964
|
-
|
|
15260
|
+
const HookPrefix = "mongocamp:";
|
|
15261
|
+
function listens(hooks, name) {
|
|
15262
|
+
const table = hooks._hooks;
|
|
15263
|
+
return table === void 0 || (table[name]?.length ?? 0) > 0;
|
|
15264
|
+
}
|
|
15265
|
+
function forwardEventsToHooks(server, hooks) {
|
|
15266
|
+
return server.events.forward({
|
|
15267
|
+
listens: (name) => listens(hooks, `${HookPrefix}${name}`),
|
|
15268
|
+
call: (name, event) => hooks.callHook(`${HookPrefix}${name}`, event)
|
|
15269
|
+
});
|
|
15270
|
+
}
|
|
15271
|
+
async function connectHooks(server, hooks) {
|
|
15272
|
+
const stop = forwardEventsToHooks(server, hooks);
|
|
15273
|
+
await hooks.callHook(`${HookPrefix}ready`, server);
|
|
15274
|
+
return stop;
|
|
15275
|
+
}
|
|
15276
|
+
|
|
15277
|
+
export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, forwardEventsToHooks, luceneQueryToFilter, luceneToFilter, metrics, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, requestFields, requestLogging, stringifyJson };
|