feat(config): put the operator-owned surfaces behind TREK_MANAGED (#1946)

* feat(config): put the operator-owned surfaces behind TREK_MANAGED

The switch landed last release with nothing behind it. This is what it turns
off, plus the four fixes that came out of walking every one of these surfaces.

Nothing here changes anything for an install that does not set the flag. That
is not a hope, it is what managed-inert.test.ts asserts: the mode stays off for
any unparseable value, no other variable can turn it on, every settings key
stays writable, and splitManagedKeys hands back the same object rather than a
copy so no write path can quietly diverge on self-hosted installs only.

WHAT THE MODE WITHHOLDS

Fourteen routes carry @ManagedForbidden: key validation, static MCP tokens, JWT
rotation, the OIDC admin pair, restore and auto-backup, plugin sideload and
reload, the Ollama model list and pull, and the SMTP test send. Each names the
reason it is not the instance admin's, and the reason is mandatory.

Eighteen settings keys are filtered instead of refused. SMTP, the OIDC toggles
and the WebAuthn pair share one handler with keys the admin does own, and the
llm_* family is reachable through per-user settings, the instance defaults and
the addon config alike, so a route-level refusal would be both too coarse and
incomplete. A locked key is skipped and reported as managed_keys; the rest of
the save goes through. Refusing the request would take the registration toggles
down with the SMTP block.

GET /api/auth/me/settings stops returning the three API keys in the clear. It
is the only endpoint that decrypts a stored credential back to the caller, which
is fine when the admin pasted it in and wrong when the operator supplied it.

Two multipart routes check in the handler rather than the guard: a guard throws
before the parser drains the body and the client gets an ECONNRESET instead of
the 403 (PROFILE-015). They still carry the marker so the boot gate sees them.

WHAT KEEPS IT FROM DRIFTING

validate-managed-routes.ts refuses to boot on a marking that is not on the
reviewed list, a list entry whose route lost its marking, or a marking with no
reason. The third case has no equivalent in the guard gate next door and is the
one that matters most: a blank reason destroys the only record of why a control
was taken away, and nothing recovers that later. It found two wrong entries in
my own list while I was writing this.

managed-keys.test.ts asserts that every key in ADMIN_SETTINGS_KEYS and
DEFAULTABLE_USER_SETTING_KEYS belongs to exactly one of two sets. A key added to
either list belongs to neither until somebody decides, and that is the failure
this prevents: the lists grow, the mode does not.

PLACES_API_BASE AND PLACES_API_KEY

The nine Places endpoints spell out googleapis.com, so an install that wants
those calls to leave through something of its own has no way to say so. One
variable, substituted where every call already funnels through. A second one
supplies the key, and when it is set the users table is not consulted at all —
a per-user key would route around whatever the endpoint counts, and those
columns are readable by any admin of the instance.

FOUR FIXES THAT ARE NOT ABOUT THE MODE

An admin setting somebody's password now bumps password_version and clears
their MCP tokens. An admin sets a password for one reason, and until now
verifyJwtAndLoadUser kept accepting every cookie the intruder already had: the
one action taken to lock them out was the one action that did not.

The four OIDC provider calls go through the SSRF guard. Three are worse than
they look — the token, userinfo and JWKS URLs come out of the discovery
response, so they are chosen by the other end, not by an admin. safeFetchLlm is
renamed safeFetchAdminConfigured and keeps its old name as an alias, because it
is the variant that allows loopback and LAN: a self-hoster with Authentik on
localhost:9000 must keep working. The token exchange follows no redirect at all,
since one would hand client_secret to a second host.

DELETE /api/admin/users/:id/mfa clears another account's TOTP. The passkey half
has existed since passkeys landed; the TOTP half never did, which left
"somebody on the trip lost their phone" with no answer short of an operator in
the database. Never for the caller themselves.

TREK_PLUGIN_PERMISSIONS=off refuses to boot when the install is centrally
administered. A warning is right for a machine its owner chose to trust; where
the person who set the flag and the people whose data is in the database are
not the same person, fail closed.

TEXTS

Four strings lose the phrase "self-hosted" because they describe somebody
else's software — an Ollama endpoint, an AirTrail instance, a service a plugin
talks to — and read better without it in both modes. The one string that
describes TREK itself keeps it, and the mode picks a second key instead, so
self-hosters lose nothing.

A grep gate in shared/ keeps the canonical locale honest, because the parity
check compares the file set and the top-level keys and never looks at a value:
re-wording a string is invisible to CI today, and so is putting it back.

* feat(maps): supply the map credential with the instance when centrally administered

MAPBOX_ACCESS_TOKEN joins PLACES_API_KEY as an operator-supplied value.
SettingsService injects it when the settings are read, and picks GL as the
provider if the reader is still on Leaflet, since a token is always present.

The key moves from the customer set to the locked set. It is the one locked key
whose value is public by design — a pk.* token has to reach the browser to be
useful — so this is not about secrecy: a per-user save landing on top of the
instance token would only break the map for that user. Both settings fields for
it go away with it.

* fix(auth): count the operator key when reporting whether Google features work

has_maps_key only looked at the users table, but getMapsKey prefers the
PLACES_API_KEY env over anything stored there. On an install that supplies the
key that way and has an empty column, every lookup worked while the client was
told there was no key and hid the search, the autocomplete and the place photos.

Found by walking the running instance rather than the code: the map came up,
the search box did not.

* feat(admin): hide the settings a centrally administered install cannot act on

A control that answers 403 is worse than no control: the AI section rendered the
refusal as "Request failed with status code 403", which tells an admin they broke
something rather than that the decision is not theirs.

So the surfaces go rather than being disabled in place:

- AI parsing and AirTrail leave the addon list, and the AI addon route now
  refuses outright. The endpoint, the model and what a document costs come with
  the instance, so there is no instance decision left — not even whether it runs.
- Immich and Synology Photos leave it too. Both connect to a server the reader
  runs at home, and there is no route from here to one.
- The SMTP block, the admin webhook and ntfy targets, and the passkey RP ID and
  origins follow the same rule: they configure something the operator owns, and
  a wrong RP ID on a shared parent domain reaches past this instance entirely.
- The About tab goes. It is about the project — what TREK is, where to file a
  bug, where to support it — and is aimed at the person running the software.
  The version and the link to the source move to the sidebar footer, on both the
  desktop page and the mobile twin, because AGPL 13 wants that offer wherever
  people reach the software over a network.
- The update check stops asking GitHub and reports nothing available.

Separately, the version footers lose the "self-hosted" suffix everywhere, not
just here. It read as a label on the software rather than on the install, and
the version alone says what it needs to.

* feat(config): refuse to boot centrally administered without an at-rest key

Measured on a running instance rather than assumed: with ENCRYPTION_KEY unset,
the at-rest key falls back to a file in the data volume, and backupService
bundles that file into every archive it builds. The archive is downloadable by
any instance admin, so the encryption ships with its own key in the same zip.

The skip in backupService already handles this — it only omits the file when the
key came from the env — but nothing made sure the env actually carried one.
Provisioning sets it; forgetting it was silent.

validateEnvAtBoot now carries a second kind of check next to the schema: cross-
field rules that only apply with the flag set, for combinations where every value
is individually valid and the result is wrong. Empty without the flag, so an
install that never asked to be centrally administered cannot meet it.

* feat(client): add an attachment point for install-specific screens

Two empty exports on the client, an empty module on the server, and the four
places that read them. Nothing here adds a route, a nav entry or an endpoint —
the arrays are empty and the module contributes nothing, which managed-ext.test
pins so it stays that way.

Read unconditionally, never behind a flag. On the server a conditional import
would tie the module graph to an environment variable, and the graph is built
once per app while the flag is read live; on the client an empty array costs
nothing to spread, so every build walks the same path instead of one build
walking a path nobody tests.

Anything attached here follows the same rules as the rest of src/nest and
src/components: a real module with a controller and a provider, bodies through
the Zod pipe, routes under the global guards, tests.

* test(shared): move the wording gate out of src so shared typechecks again

CI installs shared with its own dependencies only (npm ci --workspace shared),
so there is no @types/node and the `node:fs` import inside src/ failed to
compile. The tests passed the whole time — vitest supplies the module — which is
why this only showed up in the typecheck step.

The walk moves to scripts/, next to i18n-parity.mjs, and the spec imports it the
same way that one does. It also runs on its own now
(`node scripts/i18n-selfhost-wording.mjs`), which is what you want when CI names
a line you have to go find.

* test(server): repair the call sites typecheck:tests caught

tests/ sits outside the build tsconfig, so none of this showed up in a green
test run — which is exactly the gap `npm run typecheck:tests` exists to close.
Three kinds, all mine:

- Seven `import type` paths for RuntimeEnvService carried one `../` too many.
  Type-only imports are erased, so vitest never resolved them and nothing failed.
- VersionCheckJob and PluginsController grew a constructor parameter and eleven
  hand-wired `new` calls kept passing the old count. The argument arrived as
  undefined and no assertion happened to read it.
- ConditionContext grew `managed`, and the shared context object in the
  conditions suite did not.

The condition also had no test of its own, so it has one now: both directions,
since the registry uses `is: false` to keep a notice away and a notice that only
belongs on a centrally administered install would use `is: true`.
This commit is contained in:
Maurice
2026-08-15 16:42:27 +02:00
committed by GitHub
parent bfb3bcd63c
commit 3a0604b3f5
108 changed files with 1926 additions and 111 deletions
+1 -1
View File
@@ -75,7 +75,7 @@ describe('System-notices e2e (real auth guard + temp SQLite)', () => {
const res = await request(server).get('/api/system-notices/active').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual([notice]);
expect(mockGetActive).toHaveBeenCalledWith(1, expect.any(Function));
expect(mockGetActive).toHaveBeenCalledWith(1, expect.any(Function), false);
});
it('204 with no body on a successful dismiss', async () => {
@@ -111,6 +111,51 @@ describe('validateEnvAtBoot', () => {
});
});
describe('validateEnvAtBoot — centrally administered preconditions', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('MANAGED-BOOT-001: refuses TREK_MANAGED without ENCRYPTION_KEY', () => {
// The combination boots fine and is wrong: the at-rest key falls back to a
// file in the data volume, and backupService puts that file in every archive
// an instance admin can download.
vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ TREK_MANAGED: '1' })).toThrow(/1 problem/);
});
it('MANAGED-BOOT-002: names the variable, so the fix does not need the source', () => {
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ TREK_MANAGED: 'true' })).toThrow();
expect(err.mock.calls[0][0]).toMatch(/ENCRYPTION_KEY/);
});
it('MANAGED-BOOT-003: passes once the key is supplied', () => {
expect(() =>
validateEnvAtBoot({ TREK_MANAGED: '1', ENCRYPTION_KEY: 'a'.repeat(64) }),
).not.toThrow();
});
it('MANAGED-BOOT-004: inert without the switch — a self-hoster keeps the file-based key', () => {
// The whole point of the check is that it cannot reach anyone who did not
// ask to be centrally administered.
expect(() => validateEnvAtBoot({})).not.toThrow();
expect(() => validateEnvAtBoot({ TREK_MANAGED: 'off' })).not.toThrow();
expect(() => validateEnvAtBoot({ TREK_MANAGED: 'false' })).not.toThrow();
});
it('MANAGED-BOOT-005: reports alongside schema problems rather than instead of them', () => {
// Both kinds land in one report: fixing the env should take one pass, not a
// restart per problem.
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ TREK_MANAGED: '1', PORT: 'not-a-port' })).toThrow(
/2 problems/,
);
expect(err.mock.calls[0][0]).toMatch(/PORT/);
expect(err.mock.calls[0][0]).toMatch(/ENCRYPTION_KEY/);
});
});
describe('readEnv', () => {
it('reads process.env live — a runtime mutation is visible on the next call', () => {
const before = process.env.DEMO_MODE;
@@ -11,6 +11,7 @@ import type { SettingsService } from '../../../src/nest/settings/settings.servic
import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { User } from '../../../src/types';
import { expectRegisteredController } from '../../helpers/module-providers';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
const user = { id: 1, role: 'admin' } as User;
const req = { headers: {}, socket: {} } as never;
@@ -22,7 +23,7 @@ function controller(over: Partial<SettingsService> = {}) {
setAdminUserDefaults: vi.fn(),
...over,
} as unknown as SettingsService;
return { c: new AdminDefaultUserSettingsController(settings, { writeAudit } as unknown as AuditService), settings };
return { c: new AdminDefaultUserSettingsController(settings, { writeAudit } as unknown as AuditService, { isManaged: () => false } as unknown as RuntimeEnvService), settings };
}
const thrown = (run: () => unknown) => {
+7 -3
View File
@@ -31,20 +31,24 @@ beforeEach(() => vi.clearAllMocks());
describe('VersionCheckJob', () => {
it('AJOB-001 — registers the daily 9 AM cron, with no boot log (parity)', () => {
const registrar = registrarStub();
new VersionCheckJob({} as AdminService, registrar as unknown as CronRegistrarService).onApplicationBootstrap();
new VersionCheckJob({} as AdminService, registrar as unknown as CronRegistrarService, { isManaged: () => false } as unknown as RuntimeEnvService).onApplicationBootstrap();
expect(registrar.register).toHaveBeenCalledWith('version-check', '0 9 * * *', expect.any(Function));
expect(logMock.logInfo).not.toHaveBeenCalled();
});
it('AJOB-002 — does not register under the test gate', () => {
const registrar = registrarStub(false);
new VersionCheckJob({} as AdminService, registrar as unknown as CronRegistrarService).onApplicationBootstrap();
new VersionCheckJob({} as AdminService, registrar as unknown as CronRegistrarService, { isManaged: () => false } as unknown as RuntimeEnvService).onApplicationBootstrap();
expect(registrar.register).not.toHaveBeenCalled();
});
it('AJOB-003 — a throwing check is contained to the Version check log line', async () => {
const admin = { checkAndNotifyVersion: vi.fn().mockRejectedValue(new Error('github down')) } as unknown as AdminService;
const job = new VersionCheckJob(admin, registrarStub() as unknown as CronRegistrarService);
const job = new VersionCheckJob(
admin,
registrarStub() as unknown as CronRegistrarService,
{ isManaged: () => false } as unknown as RuntimeEnvService,
);
await expect(job.tick()).resolves.toBeUndefined();
expect(logMock.logError).toHaveBeenCalledWith('Version check: github down');
});
+111 -2
View File
@@ -56,7 +56,7 @@ vi.mock('../../../src/demo/demo-reset', () => ({
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin, createInviteToken } from '../../helpers/factories';
import { createUser, createUserWithMfa, createAdmin, createInviteToken } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
@@ -76,6 +76,7 @@ import { NotificationsService } from '../../../src/nest/notifications/notificati
import { AdminService } from '../../../src/nest/admin/admin.service';
import { VersionCheckJob } from '../../../src/nest/admin/version-check.job';
import type { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { __clearVersionCacheForTests } from '../../../src/nest/admin/admin.helpers';
import { makeNotificationsService, makeNotificationPreferencesService } from '../../helpers/notifications';
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
@@ -485,6 +486,7 @@ describe('updateAddon', () => {
describe('version-check job', () => {
const registrarStub = { isEnabled: () => true, register: vi.fn(() => true), unregister: vi.fn() } as unknown as CronRegistrarService;
const envStub = { isManaged: () => false } as unknown as RuntimeEnvService;
it('VCJOB-001 — the cron tick notifies and shares the module-scoped version cache with the route', async () => {
createAdmin(testDb);
@@ -496,7 +498,7 @@ describe('version-check job', () => {
});
vi.stubGlobal('fetch', fetchMock);
await new VersionCheckJob(svc, registrarStub).tick();
await new VersionCheckJob(svc, registrarStub, envStub).tick();
const notified = testDb
.prepare('SELECT value FROM app_settings WHERE key = ?')
@@ -527,3 +529,110 @@ describe('admin quirk fixes (post-fold)', () => {
});
// ── What an admin password reset ends, and what an ordinary edit must not ─────
const pv = (id: number): number =>
(testDb.prepare('SELECT password_version FROM users WHERE id = ?').get(id) as { password_version: number | null })
?.password_version ?? 0;
const mcpTokenCount = (id: number): number =>
(testDb.prepare('SELECT COUNT(*) AS n FROM mcp_tokens WHERE user_id = ?').get(id) as { n: number }).n;
describe('admin password reset revokes what an intruder already holds', () => {
it('ADMIN-SVC-080 — setting a password bumps password_version, so existing cookies stop working', () => {
// An admin sets somebody else's password for one reason: the account is
// believed compromised. Without the bump, verifyJwtAndLoadUser keeps
// accepting every cookie the intruder holds, and the one action taken to
// lock them out is the one action that did not.
const { user } = createUser(testDb);
const before = pv(user.id);
updateUser(String(user.id), { password: 'ANewStrongPass123!' });
expect(pv(user.id)).toBe(before + 1);
});
it('ADMIN-SVC-081 — and clears the MCP tokens, which the version bump does not reach', () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, 'hash', 'trek_ab', 'cli')").run(user.id);
updateUser(String(user.id), { password: 'ANewStrongPass123!' });
expect(mcpTokenCount(user.id)).toBe(0);
});
it('ADMIN-SVC-082 — renaming a user touches neither, so an ordinary edit stays ordinary', () => {
const { user } = createUser(testDb);
const before = pv(user.id);
testDb.prepare("INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, 'hash', 'trek_ab', 'cli')").run(user.id);
updateUser(String(user.id), { username: 'renamed' });
expect(pv(user.id)).toBe(before);
expect(mcpTokenCount(user.id)).toBe(1);
});
});
describe('resetUserMfa', () => {
it('ADMIN-SVC-083 — clears the three columns disableMfa clears, so both paths leave one state', () => {
// The passkey half has existed since passkeys landed; TOTP never had an
// answer, which left "somebody on the trip lost their phone" with no way out
// short of an operator reaching into the database.
const admin = createAdmin(testDb);
const { user } = createUserWithMfa(testDb);
const result = svc.resetUserMfa(String(user.id), admin.user.id) as { success?: boolean; email?: string };
expect(result.success).toBe(true);
expect(result.email).toBe(user.email);
const row = testDb
.prepare('SELECT mfa_enabled, mfa_secret, mfa_backup_codes FROM users WHERE id = ?')
.get(user.id) as { mfa_enabled: number; mfa_secret: string | null; mfa_backup_codes: string | null };
expect(row.mfa_enabled).toBe(0);
expect(row.mfa_secret).toBeNull();
expect(row.mfa_backup_codes).toBeNull();
});
it('ADMIN-SVC-084 — refuses to strip the callers own second factor', () => {
// Reachable from a stolen admin session otherwise, and it would take the
// second factor off the very account that session came from. The
// self-service path in Settings asks for the current password.
const admin = createAdmin(testDb);
const result = svc.resetUserMfa(String(admin.user.id), admin.user.id) as { error?: string; status?: number };
expect(result.status).toBe(400);
expect(result.error).toMatch(/your own/i);
});
it('ADMIN-SVC-085 — 404 for a user that is not there', () => {
const admin = createAdmin(testDb);
expect(svc.resetUserMfa('99999', admin.user.id) as { status?: number }).toMatchObject({ status: 404 });
});
});
describe('checkVersion on a centrally administered install', () => {
afterEach(() => {
vi.unstubAllEnvs();
__clearVersionCacheForTests();
});
it('ADMIN-SVC-086 — answers "up to date" without asking GitHub', () => {
// Answered rather than refused: the admin page calls this on open, and a 403
// would put an error where a quiet surface belongs. The operator decides when
// this instance upgrades, so from inside it there is nothing available.
const fetchSpy = vi.fn();
vi.stubGlobal('fetch', fetchSpy);
vi.stubEnv('TREK_MANAGED', 'true');
vi.stubEnv('APP_VERSION', '3.4.1');
return checkVersion().then((info) => {
expect(info.update_available).toBe(false);
expect(info.latest).toBe('3.4.1');
expect(info.current).toBe('3.4.1');
expect(fetchSpy).not.toHaveBeenCalled();
});
});
});
@@ -29,6 +29,7 @@ import type { AutoBackupJob } from '../../../src/nest/backup/auto-backup.job';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import * as backupSvc from '../../../src/nest/backup/backup.impl';
import type { User } from '../../../src/types';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
const user = { id: 1, role: 'admin', email: 'a@example.test' } as User;
const req = { ip: '1.2.3.4', headers: {} } as Request;
@@ -42,7 +43,7 @@ const audit = { writeAudit } as unknown as AuditService;
function job(o: Partial<AutoBackupJob> = {}): AutoBackupJob {
return { getAutoSettings: vi.fn(), updateAutoSettings: vi.fn(), start: vi.fn(), ...o } as unknown as AutoBackupJob;
}
const bc = (s: BackupService, j: AutoBackupJob = job()) => new BackupController(s, audit, j);
const bc = (s: BackupService, j: AutoBackupJob = job()) => new BackupController(s, audit, j, { isManaged: () => false } as unknown as RuntimeEnvService);
function svc(o: Partial<BackupService> = {}): BackupService {
return {
@@ -24,10 +24,11 @@ vi.mock('../../../../src/nest/llm-parse/router/extraction-router', () => ({ rout
import { LlmParseService } from '../../../../src/nest/llm-parse/llm-parse.service';
import type { LlmConfigResolver } from '../../../../src/nest/llm-parse/llm-config.resolver';
import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
const cfg = (over: Record<string, unknown> = {}) => ({ provider: 'openai', model: 'm', multimodal: false, ...over });
const llmConfigStub = { resolve: resolveLlmConfig } as unknown as LlmConfigResolver;
const svc = () => new LlmParseService(llmConfigStub);
const svc = () => new LlmParseService(llmConfigStub, { isManaged: () => false } as unknown as RuntimeEnvService);
const file = (name: string, body = 'Flight AB123') => ({ buffer: Buffer.from(body), originalName: name });
beforeEach(() => {
@@ -0,0 +1,36 @@
/**
* The extension point is empty here, and adds nothing to the app.
*
* The value of this test is not that an empty module is empty. It is that the
* emptiness is checked at all: this is the seam where an install can attach its
* own screens, and the promise made to everyone else is that the public build
* carries none of them. A stray controller or provider slipping in would be
* invisible in review and obvious only to whoever it shipped to.
*/
import { describe, it, expect } from 'vitest';
import { MODULE_METADATA } from '@nestjs/common/constants';
import { Test } from '@nestjs/testing';
import { ManagedExtModule } from '../../../src/nest/managed/managed-ext.module';
const meta = (key: string): unknown[] => (Reflect.getMetadata(key, ManagedExtModule) as unknown[]) ?? [];
describe('ManagedExtModule', () => {
it('MANAGED-EXT-001: contributes no controllers, providers, imports or exports', () => {
expect({
controllers: meta(MODULE_METADATA.CONTROLLERS),
providers: meta(MODULE_METADATA.PROVIDERS),
imports: meta(MODULE_METADATA.IMPORTS),
exports: meta(MODULE_METADATA.EXPORTS),
}).toEqual({ controllers: [], providers: [], imports: [], exports: [] });
});
it('MANAGED-EXT-002: compiles as a module, so app.module can import it unconditionally', async () => {
// Unconditionally on purpose: a conditional import would tie the module graph
// to an env var, and the graph is built once per app while TREK_MANAGED is
// read live. An empty module costs nothing, so the flag never reaches here.
const built = await Test.createTestingModule({ imports: [ManagedExtModule] }).compile();
expect(built.get(ManagedExtModule, { strict: false })).toBeInstanceOf(ManagedExtModule);
await built.close();
});
});
@@ -0,0 +1,74 @@
/**
* With TREK_MANAGED unset, nothing in this feature does anything.
*
* That is the promise the whole design rests on: the same image runs on a
* self-hosted install and on a centrally administered one, and the first must
* not be able to tell the second exists. Every other test here checks that the
* mode works; this one checks that its absence is total.
*
* Written as its own file rather than a case in each suite on purpose. Spread
* across eight files the question "does this change anything for a self-hoster"
* has eight partial answers; here it has one.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import {
splitManagedKeys,
isManagedBlocked,
MANAGED_LOCKED_SETTING_KEYS,
} from '../../../src/nest/common/managed';
import { deriveMaps, deriveManaged } from '../../../src/app-config/derive';
const env = new RuntimeEnvService();
afterEach(() => {
delete process.env.TREK_MANAGED;
delete process.env.PLACES_API_BASE;
delete process.env.PLACES_API_KEY;
});
describe('a self-hosted install', () => {
it('MANAGED-INERT-001: is not managed, and no other variable can make it so', () => {
// Only TREK_MANAGED decides. Setting the operator plumbing without it must
// not flip the mode, or an operator half-way through a migration would take
// settings away from admins without meaning to.
process.env.PLACES_API_BASE = 'https://places.example.test';
process.env.PLACES_API_KEY = 'operator-key';
expect(env.isManaged()).toBe(false);
expect(isManagedBlocked(env)).toBe(false);
});
it('MANAGED-INERT-002: keeps every settings key writable', () => {
const body = Object.fromEntries(MANAGED_LOCKED_SETTING_KEYS.map((k) => [k, 'x']));
const { allowed, blocked } = splitManagedKeys(body, env.isManaged());
expect(blocked).toEqual([]);
expect(allowed).toEqual(body);
});
it('MANAGED-INERT-003: is the same object, not a copy, so no write path can diverge', () => {
// splitManagedKeys returns the body itself when the mode is off. If it ever
// started cloning, a caller mutating `allowed` would silently stop working
// on self-hosted installs only, which is the hardest kind of bug to find.
const body = { smtp_host: 'mail.example.test' };
expect(splitManagedKeys(body, false).allowed).toBe(body);
});
it('MANAGED-INERT-004: leaves the Places calls pointing at Google with the stored key', () => {
const maps = deriveMaps({});
expect(maps.placesApiBase).toBeUndefined();
expect(maps.placesApiKey).toBeUndefined();
});
it('MANAGED-INERT-005: treats an unparseable flag as off, never as on', () => {
// Fail closed in the direction that matters here: the failure mode of a typo
// must be "the admin keeps their settings", not "the admin quietly loses them".
for (const value of ['', ' ', 'maybe', 'TRUE_ISH', '2', 'null', 'undefined']) {
expect(deriveManaged({ TREK_MANAGED: value }).enabled, `TREK_MANAGED=${value}`).toBe(false);
}
});
});
+121
View File
@@ -0,0 +1,121 @@
/**
* Who owns which setting, pinned.
*
* The lists grow and the mode does not: that is how this kind of switch drifts.
* A key added to ADMIN_SETTINGS_KEYS or DEFAULTABLE_USER_SETTING_KEYS belongs to
* neither set until somebody decides, and MANAGED-KEYS-001 is what makes that
* decision unavoidable rather than optional.
*
* Deliberately an assignment test, not an equality test. Pinning the locked list
* alone would pass forever while new keys quietly defaulted to "the admin may
* set it", which is the failure this is here to prevent.
*/
import { describe, it, expect } from 'vitest';
import { ADMIN_SETTINGS_KEYS } from '../../../src/nest/auth/auth.helpers';
import { DEFAULTABLE_USER_SETTING_KEYS } from '../../../src/nest/settings/settings.service';
import {
MANAGED_LOCKED_SETTING_KEYS,
MANAGED_LOCKED_PROFILE_KEYS,
MANAGED_CUSTOMER_KEYS,
isManagedLockedKey,
splitManagedKeys,
} from '../../../src/nest/common/managed';
const SOURCE_KEYS: string[] = [...ADMIN_SETTINGS_KEYS, ...DEFAULTABLE_USER_SETTING_KEYS];
const locked = new Set<string>(MANAGED_LOCKED_SETTING_KEYS);
const customer = new Set<string>(MANAGED_CUSTOMER_KEYS);
describe('managed key assignment', () => {
it('MANAGED-KEYS-001: every key from both source lists is assigned to exactly one set', () => {
const unassigned = SOURCE_KEYS.filter((k) => !locked.has(k) && !customer.has(k));
const both = SOURCE_KEYS.filter((k) => locked.has(k) && customer.has(k));
// Both in one assertion so the failure message names the offending key.
expect({ unassigned, both }).toEqual({ unassigned: [], both: [] });
});
it('MANAGED-KEYS-002: no customer entry outlives the key it describes', () => {
expect(MANAGED_CUSTOMER_KEYS.filter((k) => !SOURCE_KEYS.includes(k))).toEqual([]);
});
it('MANAGED-KEYS-003: the only locked names outside both source lists are the users columns', () => {
expect(MANAGED_LOCKED_SETTING_KEYS.filter((k) => !SOURCE_KEYS.includes(k)).slice().sort()).toEqual(
[...MANAGED_LOCKED_PROFILE_KEYS].sort(),
);
});
it('MANAGED-KEYS-004: neither set repeats itself', () => {
expect(locked.size).toBe(MANAGED_LOCKED_SETTING_KEYS.length);
expect(customer.size).toBe(MANAGED_CUSTOMER_KEYS.length);
});
it('MANAGED-KEYS-005: the locked list is pinned verbatim', () => {
expect([...MANAGED_LOCKED_SETTING_KEYS]).toEqual([
'llm_api_key',
'llm_base_url',
'llm_model',
'llm_multimodal',
'llm_provider',
'mapbox_access_token',
'maps_api_key',
'oidc_login',
'oidc_registration',
'openweather_api_key',
'smtp_from',
'smtp_host',
'smtp_pass',
'smtp_port',
'smtp_skip_tls_verify',
'smtp_user',
'unsplash_api_key',
'webauthn_origins',
'webauthn_rp_id',
]);
});
it("MANAGED-KEYS-006: mapbox_access_token is the operator's, and reaches the browser by design", () => {
// The one locked key whose value is meant to be public: a managed instance
// ships the operator's pk.* token, injected when settings are read. Locked so
// a per-user save cannot land on top of it and break that user's map.
expect(isManagedLockedKey('mapbox_access_token')).toBe(true);
expect(customer.has('mapbox_access_token')).toBe(false);
});
});
describe('splitManagedKeys', () => {
it('MANAGED-KEYS-007: hands the body back untouched on a self-hosted install', () => {
const body = { smtp_host: 'mail.example.test', allow_registration: 'true' };
expect(splitManagedKeys(body, false)).toEqual({ allowed: body, blocked: [] });
});
it('MANAGED-KEYS-008: keeps the customer keys and reports the locked ones', () => {
// The admin settings tab saves SMTP and the registration toggles in one
// request. Refusing the request would take the toggles down with the SMTP.
const { allowed, blocked } = splitManagedKeys(
{ smtp_host: 'mail.example.test', smtp_pass: 'hunter2', allow_registration: 'true' },
true,
);
expect(allowed).toEqual({ allow_registration: 'true' });
expect(blocked).toEqual(['smtp_host', 'smtp_pass']);
});
it('MANAGED-KEYS-009: reports blocked names sorted, so a response body is stable', () => {
const { blocked } = splitManagedKeys(
{ webauthn_rp_id: 'x', llm_api_key: 'y', smtp_from: 'z' },
true,
);
expect(blocked).toEqual(['llm_api_key', 'smtp_from', 'webauthn_rp_id']);
});
it('MANAGED-KEYS-010: an unknown key is not the filter’s business', () => {
// Whatever rejects unknown keys today keeps rejecting them; this only ever
// removes names it was told to remove.
const { allowed, blocked } = splitManagedKeys({ not_a_setting: '1' }, true);
expect(allowed).toEqual({ not_a_setting: '1' });
expect(blocked).toEqual([]);
});
});
+13 -2
View File
@@ -16,9 +16,11 @@ import { ManagedGuard } from '../../../src/nest/common/managed.guard';
import { MANAGED_FORBIDDEN, MANAGED_FORBIDDEN_ERROR } from '../../../src/nest/common/managed';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
function makeGuard(managed: boolean, marked: boolean) {
function makeGuard(managed: boolean, marked: boolean, enforcedInHandler = false) {
const getAllAndOverride = vi.fn((key: string) =>
key === MANAGED_FORBIDDEN && marked ? { reason: 'the operator holds this' } : undefined,
key === MANAGED_FORBIDDEN && marked
? { reason: 'the operator holds this', enforcedInHandler }
: undefined,
);
const guard = new ManagedGuard(
{ isManaged: () => managed } as unknown as RuntimeEnvService,
@@ -70,6 +72,15 @@ describe('ManagedGuard', () => {
expect(getAllAndOverride).not.toHaveBeenCalled();
});
it('MANAGED-GUARD-006: lets a handler-enforced marking through, so multipart still parses', () => {
// The route is marked and the mode is on, and it still passes: a guard that
// threw here would leave the upload body unread and the client would see an
// ECONNRESET instead of the 403 (PROFILE-015). The handler does the refusing.
const { guard } = makeGuard(true, true, true);
expect(guard.canActivate(ctx)).toBe(true);
});
it('MANAGED-GUARD-005: asks for the decorator on handler and controller, not for a path', () => {
const { guard, getAllAndOverride } = makeGuard(true, false);
guard.canActivate(ctx);
+13 -1
View File
@@ -81,6 +81,18 @@ describe('ManagedForbidden', () => {
}
const meta = Reflect.getMetadata(MANAGED_FORBIDDEN, Controller.prototype.handler);
expect(meta).toEqual({ reason: 'the operator holds this credential' });
expect(meta).toEqual({ reason: 'the operator holds this credential', enforcedInHandler: false });
});
it('MANAGED-009: a multipart route stays in the inventory while refusing in its handler', () => {
class Controller {
@ManagedForbidden('restoring a backup replaces state the operator owns', { enforcedInHandler: true })
upload() {}
}
const meta = Reflect.getMetadata(MANAGED_FORBIDDEN, Controller.prototype.upload);
expect(meta.enforcedInHandler).toBe(true);
// The reason is still mandatory: the boot gate refuses an empty one.
expect(meta.reason).not.toBe('');
});
});
+52
View File
@@ -0,0 +1,52 @@
/**
* The four OIDC provider calls go through the SSRF guard.
*
* Three of them are worse than they look: `discover` fetches a URL an admin
* configured, but the token, userinfo and JWKS URLs come out of the RESPONSE to
* that first call. They are chosen by the other end, not by anyone here, and
* until now all four went to a bare `fetch`.
*
* Deliberately a separate file. oidc.service.test.ts stubs global fetch and
* mocks the guard away so it can test OIDC logic; that is the right trade there
* and it is also exactly why the guard needs pinning somewhere it is not mocked.
*
* safeFetchAdminConfigured rather than safeFetch: a self-hoster running Authentik
* on http://localhost:9000 must keep working, so loopback and LAN stay allowed
* while link-local and the cloud-metadata range never are.
*/
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
const SOURCE = readFileSync(
join(__dirname, '../../../src/nest/oidc/oidc.service.ts'),
'utf8',
);
describe('OIDC outbound calls', () => {
it('OIDC-SSRF-001: no bare fetch( is left in the service', () => {
// A grep, and that is the point: the failure this prevents is somebody adding
// a fifth provider call next year with the same `await fetch(...)` the other
// four used to have. A behavioural test would only cover the four that exist.
const bare = SOURCE.split('\n')
.map((line, i) => ({ line: line.trim(), n: i + 1 }))
.filter(({ line }) => /\bawait fetch\(|[^.\w]fetch\(/.test(line) && !line.startsWith('*'));
expect(bare.map((b) => `${b.n}: ${b.line.slice(0, 70)}`)).toEqual([]);
});
it('OIDC-SSRF-002: all four calls name the guard', () => {
const guarded = SOURCE.match(/safeFetchAdminConfigured\(/g) ?? [];
// discover, exchangeCodeForToken, getUserInfo, fetchJwks.
expect(guarded).toHaveLength(4);
});
it('OIDC-SSRF-003: the token exchange follows no redirect at all', () => {
// A redirect there would hand client_secret to a second host, and the
// platform default is to follow. The third argument is the hop budget.
const tokenCall = /safeFetchAdminConfigured\(\s*doc\.token_endpoint[\s\S]*?\}\s*,\s*0\s*\)/.test(SOURCE);
expect(tokenCall).toBe(true);
});
});
@@ -63,6 +63,18 @@ vi.mock('../../../src/nest/common/crypto/apiKeyCrypto', () => ({
}));
vi.mock('../../../src/nest/auth/ephemeral-tokens', () => ({ createEphemeralToken: vi.fn() }));
vi.mock('../../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn() }));
// The four provider calls go through the SSRF guard now (link-local and the
// cloud-metadata range are refused, every redirect hop re-checked). These tests
// exercise OIDC logic, not the guard, so the guard delegates to whatever fetch
// the case stubbed — and OIDC-SVC-SSRF-001 below pins that it is really there.
vi.mock('../../../src/utils/ssrfGuard', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../src/utils/ssrfGuard')>();
return {
...actual,
safeFetchAdminConfigured: vi.fn((url: string, init?: RequestInit) => fetch(url, init)),
};
});
const { getAppUrlMock } = vi.hoisted(() => ({ getAppUrlMock: vi.fn() }));
vi.mock('../../../src/app-config', async (importOriginal) => {
@@ -4,6 +4,7 @@ import { HttpException } from '@nestjs/common';
import { SettingsController } from '../../../src/nest/settings/settings.controller';
import type { SettingsService } from '../../../src/nest/settings/settings.service';
import type { User } from '../../../src/types';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
const user = { id: 1, role: 'user', email: 'u@example.test' } as User;
@@ -24,7 +25,7 @@ beforeEach(() => vi.clearAllMocks());
describe('SettingsController', () => {
it('GET / returns the settings', () => {
expect(new SettingsController(svc({ getUserSettings: vi.fn().mockReturnValue({ theme: 'dark' }) } as Partial<SettingsService>)).list(user)).toEqual({ settings: { theme: 'dark' } });
expect(new SettingsController(svc({ getUserSettings: vi.fn().mockReturnValue({ theme: 'dark' }) } as Partial<SettingsService>), { isManaged: () => false } as unknown as RuntimeEnvService).list(user)).toEqual({ settings: { theme: 'dark' } });
});
// The 400-without-a-key path moved to the global ZodValidationPipe (via
@@ -32,14 +33,14 @@ describe('SettingsController', () => {
it('PUT / no-ops on the masked sentinel without writing', () => {
const upsertSetting = vi.fn();
const c = new SettingsController(svc({ upsertSetting } as Partial<SettingsService>));
const c = new SettingsController(svc({ upsertSetting } as Partial<SettingsService>), { isManaged: () => false } as unknown as RuntimeEnvService);
expect(c.upsert(user, { key: 'immich_api_key', value: '••••••••' })).toEqual({ success: true, key: 'immich_api_key', unchanged: true });
expect(upsertSetting).not.toHaveBeenCalled();
});
it('PUT / writes a real value', () => {
const upsertSetting = vi.fn();
const c = new SettingsController(svc({ upsertSetting } as Partial<SettingsService>));
const c = new SettingsController(svc({ upsertSetting } as Partial<SettingsService>), { isManaged: () => false } as unknown as RuntimeEnvService);
expect(c.upsert(user, { key: 'theme', value: 'dark' })).toEqual({ success: true, key: 'theme', value: 'dark' });
expect(upsertSetting).toHaveBeenCalledWith(1, 'theme', 'dark');
});
@@ -48,7 +49,7 @@ describe('SettingsController', () => {
// The 400-without-an-object path moved to the global ZodValidationPipe
// (via SettingsBulkDto) — pinned by the settings e2e, not reachable here.
vi.spyOn(console, 'error').mockImplementation(() => {});
expect(thrown(() => new SettingsController(svc({ bulkUpsertSettings: vi.fn(() => { throw new Error('db'); }) } as Partial<SettingsService>)).bulk(user, { settings: { a: 1 } }))).toEqual({ status: 500, body: { error: 'Error saving settings' } });
expect(new SettingsController(svc({ bulkUpsertSettings: vi.fn().mockReturnValue(3) } as Partial<SettingsService>)).bulk(user, { settings: { a: 1, b: 2, c: 3 } })).toEqual({ success: true, updated: 3 });
expect(thrown(() => new SettingsController(svc({ bulkUpsertSettings: vi.fn(() => { throw new Error('db'); }) } as Partial<SettingsService>), { isManaged: () => false } as unknown as RuntimeEnvService).bulk(user, { settings: { a: 1 } }))).toEqual({ status: 500, body: { error: 'Error saving settings' } });
expect(new SettingsController(svc({ bulkUpsertSettings: vi.fn().mockReturnValue(3) } as Partial<SettingsService>), { isManaged: () => false } as unknown as RuntimeEnvService).bulk(user, { settings: { a: 1, b: 2, c: 3 } })).toEqual({ success: true, updated: 3 });
});
});
@@ -16,9 +16,10 @@ vi.mock('../../../src/systemNotices/service', () => ({
import { SystemNoticesService } from '../../../src/nest/system-notices/system-notices.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
const isAddonEnabled = vi.fn((id: string) => id === 'journey');
const svc = new SystemNoticesService({ isAddonEnabled } as unknown as AddonsService);
const svc = new SystemNoticesService({ isAddonEnabled } as unknown as AddonsService, { isManaged: () => false } as unknown as RuntimeEnvService);
beforeEach(() => {
mockGetActive.mockReset();
@@ -30,7 +31,7 @@ describe('SystemNoticesService', () => {
it('getActiveFor threads a live addonEnabled check over the injected AddonsService', () => {
mockGetActive.mockReturnValue([]);
svc.getActiveFor(7);
expect(mockGetActive).toHaveBeenCalledWith(7, expect.any(Function));
expect(mockGetActive).toHaveBeenCalledWith(7, expect.any(Function), false);
const addonEnabled = mockGetActive.mock.calls[0][1] as (id: string) => boolean;
expect(addonEnabled('journey')).toBe(true);
expect(addonEnabled('vacay')).toBe(false);
@@ -51,10 +52,10 @@ describe('SystemNoticesService', () => {
vi.resetModules();
vi.doMock('../../../src/nest/addons/addons.service', () => ({ AddonsService: undefined }));
const { SystemNoticesService: Reloaded } = await import('../../../src/nest/system-notices/system-notices.service');
const inst = new Reloaded({ isAddonEnabled } as unknown as AddonsService);
const inst = new Reloaded({ isAddonEnabled } as unknown as AddonsService, { isManaged: () => false } as unknown as RuntimeEnvService);
mockGetActive.mockReturnValue([]);
inst.getActiveFor(1);
expect(mockGetActive).toHaveBeenCalledWith(1, expect.any(Function));
expect(mockGetActive).toHaveBeenCalledWith(1, expect.any(Function), false);
vi.doUnmock('../../../src/nest/addons/addons.service');
});
});
@@ -0,0 +1,169 @@
/**
* The boot gate for the managed surface
* (src/nest/common/validate-managed-routes.ts).
*
* Same ratchet shape as the anonymous-route gate next door, with one case it
* does not have: a marker without a reason. That one matters most. An unlisted
* or stale entry is a bookkeeping error somebody notices at the next boot, but a
* blank reason destroys the only record of WHY a control was taken away from a
* customer, and nothing recovers that afterwards.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { Controller, Get, Post } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import type { INestApplication } from '@nestjs/common';
import { ManagedForbidden } from '../../../src/nest/common/managed';
import {
collectManagedRoutes,
validateManagedRoutes,
} from '../../../src/nest/common/validate-managed-routes';
@Controller('managed-gate/plain')
class PlainController {
@Get()
list() {
return [];
}
}
@Controller('managed-gate/marked')
class MarkedController {
@ManagedForbidden('the operator supplies this credential')
@Get('key')
key() {
return {};
}
@ManagedForbidden('replacing state the operator owns', { enforcedInHandler: true })
@Post('upload')
upload() {
return {};
}
@Get('untouched')
untouched() {
return {};
}
}
@Controller('managed-gate/blank')
class BlankReasonController {
@ManagedForbidden(' ')
@Get()
vague() {
return {};
}
}
/** A whole controller marked at class level: every route below inherits it. */
@ManagedForbidden('this entire surface belongs to the operator')
@Controller('managed-gate/whole')
class WholeController {
@Get('a')
a() {
return {};
}
@Get('b')
b() {
return {};
}
}
async function buildApp(controllers: unknown[]): Promise<INestApplication> {
const moduleRef = await Test.createTestingModule({
controllers: controllers as never[],
}).compile();
return moduleRef.createNestApplication();
}
describe('collectManagedRoutes', () => {
let markedApp: INestApplication;
let wholeApp: INestApplication;
beforeAll(async () => {
markedApp = await buildApp([PlainController, MarkedController]);
wholeApp = await buildApp([WholeController]);
});
afterAll(async () => {
await Promise.all([markedApp.close(), wholeApp.close()]);
});
it('MANAGED-BOOT-001: inventories the marked routes and leaves the rest alone', () => {
const entries = collectManagedRoutes(markedApp);
expect(entries.map((e) => e.id)).toEqual([
'MarkedController.key',
'MarkedController.upload',
]);
});
it('MANAGED-BOOT-002: carries the reason and the handler-enforced flag through', () => {
const entries = collectManagedRoutes(markedApp);
expect(entries[0]).toEqual({
id: 'MarkedController.key',
reason: 'the operator supplies this credential',
enforcedInHandler: false,
});
expect(entries[1].enforcedInHandler).toBe(true);
});
it('MANAGED-BOOT-003: a class-level marking covers every route under it', () => {
const entries = collectManagedRoutes(wholeApp);
expect(entries.map((e) => e.id)).toEqual(['WholeController.a', 'WholeController.b']);
expect(entries.every((e) => e.reason === 'this entire surface belongs to the operator')).toBe(true);
});
});
describe('validateManagedRoutes (fail-closed boot gate)', () => {
let markedApp: INestApplication;
let blankApp: INestApplication;
let plainApp: INestApplication;
beforeAll(async () => {
markedApp = await buildApp([PlainController, MarkedController]);
blankApp = await buildApp([BlankReasonController]);
plainApp = await buildApp([PlainController]);
});
afterAll(async () => {
await Promise.all([markedApp.close(), blankApp.close(), plainApp.close()]);
});
it('MANAGED-BOOT-004: passes when the list matches the markings', () => {
expect(() =>
validateManagedRoutes(markedApp, ['MarkedController.key', 'MarkedController.upload']),
).not.toThrow();
});
it('MANAGED-BOOT-005: throws naming a marking nobody put on the list', () => {
expect(() => validateManagedRoutes(markedApp, ['MarkedController.key'])).toThrow(
/MarkedController\.upload/,
);
});
it('MANAGED-BOOT-006: throws on a stale entry, so the list cannot rot', () => {
expect(() => validateManagedRoutes(plainApp, ['MarkedController.key'])).toThrow(
/no longer marked/,
);
});
it('MANAGED-BOOT-007: throws when a marking has no reason', () => {
expect(() => validateManagedRoutes(blankApp, ['BlankReasonController.vague'])).toThrow(
/without a reason/,
);
});
it('MANAGED-BOOT-008: an install with no markings and an empty list is fine', () => {
expect(() => validateManagedRoutes(plainApp, [])).not.toThrow();
});
it('MANAGED-BOOT-009: the failure explains what an entry costs a customer', () => {
// The message is the only thing a reviewer sees at 2am, so it says what the
// list means rather than just which line is wrong.
expect(() => validateManagedRoutes(markedApp, [])).toThrow(/withholds from its own admin/);
});
});
@@ -20,6 +20,7 @@ import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.s
import { PluginRegistryService, RegistryError } from '../../../src/nest/plugins/registry/registry.service';
import { PluginsService } from '../../../src/nest/plugins/plugins.service';
import { TrekExceptionFilter } from '../../../src/nest/common/trek-exception.filter';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
const ADMIN = { id: 1 } as { id: number };
const REQ = { headers: {}, socket: {} } as never;
@@ -52,7 +53,7 @@ beforeEach(() => {
process.env.TREK_PLUGINS_ENABLED = 'true';
runtime = { update: vi.fn(), retrust: vi.fn() } as unknown as PluginRuntimeService;
registry = { install: vi.fn() } as unknown as PluginRegistryService;
controller = new PluginsController({} as PluginsService, runtime, registry);
controller = new PluginsController({} as PluginsService, runtime, registry, { isManaged: () => false } as unknown as RuntimeEnvService);
});
describe('signature refusal codes survive to the client', () => {
@@ -8,9 +8,10 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { HttpException } from '@nestjs/common';
import { PluginsController } from '../../../src/nest/plugins/plugins.controller';
import { PluginConsentRequired } from '../../../src/nest/plugins/plugin-runtime.service';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const ctrl = (runtime: any) => new PluginsController({} as any, runtime, {} as any);
const ctrl = (runtime: any) => new PluginsController({} as any, runtime, {} as any, { isManaged: () => false } as unknown as RuntimeEnvService);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const status = async (p: Promise<any>): Promise<number> =>
p.then(() => -1, (e) => (e instanceof HttpException ? e.getStatus() : 0));
@@ -24,6 +24,7 @@ import { AddonsService } from '../../../src/nest/addons/addons.service';
import { PluginsService } from '../../../src/nest/plugins/plugins.service';
import { PluginsController } from '../../../src/nest/plugins/plugins.controller';
import { PluginsFeedController } from '../../../src/nest/plugins/plugins-feed.controller';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
beforeEach(() => {
testDb.exec('DELETE FROM plugins');
@@ -130,7 +131,7 @@ describe('PluginsService.list', () => {
it('controller delegates to the service', () => {
const svc = { list: vi.fn(() => ({ enabled: false, plugins: [] })) } as unknown as PluginsService;
const runtime = {} as unknown as import('../../../src/nest/plugins/plugin-runtime.service').PluginRuntimeService;
const res = new PluginsController(svc, runtime, {} as never).list();
const res = new PluginsController(svc, runtime, {} as never, { isManaged: () => false } as unknown as RuntimeEnvService).list();
expect(svc.list).toHaveBeenCalled();
expect(res).toEqual({ enabled: false, plugins: [] });
});
@@ -199,6 +200,9 @@ describe('PluginsController M2 endpoints', () => {
getInstanceConfig: vi.fn(() => ({ a: 1 })),
updateInstanceConfig: vi.fn(() => ({ a: 2 })),
} as unknown as PluginsService;
// None of the endpoints below carry the marker, so the ordinary install is the
// whole story here; the refusals have their own tests.
const envStub = { isManaged: () => false } as unknown as RuntimeEnvService;
beforeEach(() => {
(svc.getInstanceConfig as ReturnType<typeof vi.fn>).mockClear();
@@ -208,32 +212,32 @@ describe('PluginsController M2 endpoints', () => {
it('get/update config delegate to the service', () => {
const rt = { activate: vi.fn(), deactivate: vi.fn(), isActive: vi.fn() } as never;
const c = new PluginsController(svc, rt, {} as never);
const c = new PluginsController(svc, rt, {} as never, envStub);
expect(c.getConfig('x')).toEqual({ config: { a: 1 } });
expect(c.updateConfig('x', { a: 2 })).toEqual({ config: { a: 2 } });
});
it('activate spawns via the runtime when enabled', async () => {
const rt = { activate: vi.fn(async () => {}), isActive: vi.fn(() => true) } as never;
const out = await new PluginsController(svc, rt, {} as never).activate('x', {});
const out = await new PluginsController(svc, rt, {} as never, envStub).activate('x', {});
expect(out).toEqual({ status: 'active' });
});
it('activate is 503 when the runtime is disabled', async () => {
process.env.TREK_PLUGINS_ENABLED = 'false';
const rt = { activate: vi.fn(), isActive: vi.fn() } as never;
await expect(new PluginsController(svc, rt, {} as never).activate('x', {})).rejects.toMatchObject({ status: 503 });
await expect(new PluginsController(svc, rt, {} as never, envStub).activate('x', {})).rejects.toMatchObject({ status: 503 });
});
it('activate surfaces an activation error as 400', async () => {
const rt = { activate: vi.fn(async () => { throw new Error('bad code'); }), isActive: vi.fn(() => false) } as never;
await expect(new PluginsController(svc, rt, {} as never).activate('x', {})).rejects.toMatchObject({ status: 400 });
await expect(new PluginsController(svc, rt, {} as never, envStub).activate('x', {})).rejects.toMatchObject({ status: 400 });
});
it('deactivate stops the plugin (and cascades to dependents)', async () => {
const deactivateWithDependents = vi.fn(async () => ['x']);
const rt = { deactivateWithDependents } as never;
expect(await new PluginsController(svc, rt, {} as never).deactivate('x')).toEqual({ status: 'inactive' });
expect(await new PluginsController(svc, rt, {} as never, envStub).deactivate('x')).toEqual({ status: 'inactive' });
expect(deactivateWithDependents).toHaveBeenCalledWith('x');
});
});
@@ -28,6 +28,9 @@ const baseCtx = {
// Threaded in by the caller since the addons.bridge import left this module;
// false keeps every case below reading as it did.
addonEnabled: () => false,
// The ordinary install, so every case below is unaffected by the flag; the
// managed condition itself is exercised in its own describe block at the end.
managed: false,
};
describe('firstLogin', () => {
@@ -112,3 +115,18 @@ describe('addonEnabled', () => {
expect(evaluate(notice, baseCtx)).toBe(false);
});
});
describe('managed', () => {
it('matches on the value asked for, in both directions', () => {
// Both directions on purpose: the registry uses `is: false` to keep a notice
// away from a centrally administered install, and a notice that only ever
// shows there would use `is: true`.
const wantsSelfRun = noticeWith({ kind: 'managed', is: false });
const wantsManaged = noticeWith({ kind: 'managed', is: true });
expect(evaluate(wantsSelfRun, { ...baseCtx, managed: false })).toBe(true);
expect(evaluate(wantsSelfRun, { ...baseCtx, managed: true })).toBe(false);
expect(evaluate(wantsManaged, { ...baseCtx, managed: true })).toBe(true);
expect(evaluate(wantsManaged, { ...baseCtx, managed: false })).toBe(false);
});
});