Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions requests/Switcher API.postman_collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -6051,6 +6051,30 @@
},
"response": []
},
{
"name": "Configuration - MCP",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "graphql",
"graphql": {
"query": "query Configuration(\r\n $domain: String!, \r\n $group: String,\r\n $key: String,\r\n $environment: String) {\r\n configuration(domain: $domain, group: $group, key: $key, environment: $environment) {\r\n domain {\r\n id: _id\r\n version\r\n name\r\n activated\r\n }\r\n group {\r\n _id\r\n name\r\n activated\r\n }\r\n config {\r\n _id\r\n key\r\n activated\r\n components\r\n relay {\r\n type\r\n method\r\n endpoint\r\n description\r\n activated\r\n }\r\n }\r\n strategies {\r\n description\r\n strategy\r\n operation\r\n values\r\n activated\r\n }\r\n }\r\n}",
"variables": "{\r\n \"domain\": \"{{doaminid}}\",\r\n \"key\": \"{{switcher_key}}\",\r\n // \"group\": \"{{group}}\",\r\n \"environment\": \"{{environment}}\"\r\n}"
}
},
"url": {
"raw": "{{url}}/adm-graphql",
"host": [
"{{url}}"
],
"path": [
"adm-graphql"
]
}
},
"response": []
},
{
"name": "Permission - By Router Switcher",
"request": {
Expand Down
20 changes: 1 addition & 19 deletions src/api-docs/paths/path-oauth.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pathParameter, queryParameter } from '../schemas/common.js';
import { queryParameter } from '../schemas/common.js';
import { commonSchemaContent } from './common.js';

export default {
Expand Down Expand Up @@ -77,23 +77,5 @@ export default {
}
}
}
},
'/config/key/{key}': {
get: {
tags: ['Config'],
description: 'Get Config by key and domain name',
security: [{ bearerAuth: [] }],
parameters: [
pathParameter('key', 'Config key', true),
queryParameter('domain', 'Domain name', true),
queryParameter('environment', 'Environment name', false)
],
responses: {
200: {
description: 'Config',
content: commonSchemaContent('ConfigByKeyResponse')
}
}
}
}
};
22 changes: 0 additions & 22 deletions src/api-docs/schemas/oauth.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { config } from './config.js';

const oauthMetadata = {
type: 'object',
Expand Down Expand Up @@ -184,26 +183,5 @@ export default {
},
...oauthMetadata.properties
}
},
ConfigByKeyResponse: {
...config({
type: 'array',
description: 'The component IDs that can use the Swichter',
items: {
type: 'string'
}
}),
properties: {
...config({
type: 'array',
description: 'The component IDs that can use the Swichter',
items: {
type: 'string'
}
}).properties,
enabled: {
type: 'boolean'
}
}
}
};
8 changes: 0 additions & 8 deletions src/middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,6 @@ export async function auth(req, res, next) {
* falling through to the other strategy. If neither strategy succeeds
* (and it wasn't an expiry), the request fails with a generic 401
* `Please authenticate.`.
*
* Use `authAny` only for routes that must be reachable by both
* switcher-management (JWT) **and** MCP/OAuth clients - as of this
* writing: `GET /domain`, `GET /domain/collaboration`, `GET /environment`,
* `GET /config/key/:key`, and `/adm-graphql` (OAuth tokens limited to the
* `configuration` query via `restrictOAuthGraphQL`). Don't default new routes to `authAny`;
* keep using plain `auth` unless the route is a deliberate MCP tool
* target (see `docs/copilot/switcher-mcp/MCP_DEVELOPMENT.md`).
*/
export async function authAny(req, res, next) {
const token = getBearerToken(req);
Expand Down
25 changes: 1 addition & 24 deletions src/routers/config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express from 'express';
import { body, check, query } from 'express-validator';
import { relayOptions } from '../models/config.js';
import { auth, authAny } from '../middleware/auth.js';
import { auth } from '../middleware/auth.js';
import { ActionTypes, RouterTypes } from '../models/permission.js';
import { responseException } from '../exceptions/index.js';
import {
Expand All @@ -13,7 +13,6 @@ import { getHistory, deleteHistory } from '../services/history.js';
import { getGroupConfigById } from '../services/group-config.js';
import { SwitcherKeys } from '../external/switcher-api-facade.js';
import { getFields } from './common/index.js';
import { EnvType } from '../models/environment.js';

const router = new express.Router();

Expand Down Expand Up @@ -66,28 +65,6 @@ router.get('/config', auth, [
}
});

router.get('/config/key/:key', authAny, [
check('key').isLength({ min: 3, max: 50 }),
query('domain').isString(),
query('environment').optional().isString()
], validate, async (req, res) => {
try {
let config = await Services.getConfigByKey(
req.params.key, req.query.domain, req.query.environment, true);
config = await verifyOwnership(req.admin, config, config.domain, ActionTypes.READ, RouterTypes.CONFIG, true);

const environment = req.query.environment || EnvType.DEFAULT;
const response = config.toJSON();
response.enabled = config.activated?.has(environment) ?
config.activated.get(environment) === true :
config.activated?.get(EnvType.DEFAULT) === true;

res.send(response);
} catch (e) {
responseException(res, e, 500);
}
});

// GET /config/ID?resolveComponents=true
router.get('/config/:id', auth, [
check('id').isMongoId()
Expand Down
35 changes: 0 additions & 35 deletions src/services/config.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { response } from './common.js';
import { Config } from '../models/config.js';
import Domain from '../models/domain.js';
import { formatInput, verifyOwnership, checkEnvironmentStatusRemoval } from '../helpers/index.js';
import { ActionTypes, RouterTypes } from '../models/permission.js';
import { getDomainById, updateDomainVersion } from './domain.js';
import { getEnvironmentByName } from './environment.js';
import { getGroupConfigById } from './group-config.js';
import { checkSwitcher } from '../external/switcher-api-facade.js';
import { BadRequestError, NotFoundError } from '../exceptions/index.js';
Expand All @@ -28,39 +26,6 @@ export async function getConfigById(id, populateAdmin = false) {
return response(config, 'Config not found');
}

export async function getConfigByKey(key, domainName, environmentName, populateAdmin = false) {
const formattedKey = formatInput(key, { toUpper: true, autoUnderscore: true });
const domain = await Domain.findOne({ name: domainName.toString() }).exec();

if (!domain) {
throw new Error('Domain not found');
}

if (environmentName) {
const environment = await getEnvironmentByName(domain._id, environmentName);

if (!environment) {
throw new Error('Environment not found');
}
}

let config = await Config.findOne({
key: formattedKey,
domain: domain._id.toString()
}).exec();

if (!config) {
throw new Error('Config not found');
}

if (populateAdmin) {
await config.populate({ path: 'admin', select: 'name' });
await config.populate({ path: 'configStrategy' });
}

return config;
}

export async function getConfig(where) {
const query = Config.findOne();

Expand Down
79 changes: 0 additions & 79 deletions tests/config.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,85 +200,6 @@ describe('Testing fetch configuration info', () => {
});
});

describe('Testing fetch configuration by key', () => {
beforeAll(setupDatabase);

test('CONFIG_SUITE - Should get Config by key', async () => {
const response = await request(app)
.get(`/config/key/${config1Document.key}?domain=Domain`)
.set('Authorization', `Bearer ${adminMasterAccountToken}`)
.send().expect(200);

expect(String(response.body._id)).toEqual(String(config1Document._id));
expect(response.body.key).toEqual(config1Document.key);
expect(response.body.enabled).toEqual(true);
});

test('CONFIG_SUITE - Should get Config by key - case insensitive', async () => {
const response = await request(app)
.get(`/config/key/${config1Document.key.toLowerCase()}?domain=Domain`)
.set('Authorization', `Bearer ${adminMasterAccountToken}`)
.send().expect(200);

expect(response.body.key).toEqual(config1Document.key);
});

test('CONFIG_SUITE - Should get Config by key - environment reflected in enabled flag', async () => {
const response = await request(app)
.get(`/config/key/${config1Document.key}?domain=Domain&environment=dev`)
.set('Authorization', `Bearer ${adminMasterAccountToken}`)
.send().expect(200);

// config1Document only has activation for the default environment
// therefore, the request should fall back to the default environment
expect(response.body.enabled).toEqual(true);
});

test('CONFIG_SUITE - Should NOT get Config by key - invalid key length', async () => {
const responseInvalidKey = await request(app)
.get('/config/key/AB?domain=Domain')
.set('Authorization', `Bearer ${adminMasterAccountToken}`)
.send().expect(422);

expect(responseInvalidKey.body.error).not.toBeNull();
});

test('CONFIG_SUITE - Should NOT get Config by key - domain not found', async () => {
const responseDomainNotFound = await request(app)
.get(`/config/key/${config1Document.key}?domain=UNKNOWN_DOMAIN`)
.set('Authorization', `Bearer ${adminMasterAccountToken}`)
.send().expect(500);

expect(responseDomainNotFound.body.error).not.toBeNull();
});

test('CONFIG_SUITE - Should NOT get Config by key - environment not found', async () => {
const responseEnvironmentNotFound = await request(app)
.get(`/config/key/${config1Document.key}?domain=Domain&environment=UNKNOWN_ENV`)
.set('Authorization', `Bearer ${adminMasterAccountToken}`)
.send().expect(500);

expect(responseEnvironmentNotFound.body.error).not.toBeNull();
});

test('CONFIG_SUITE - Should NOT get Config by key - key not found', async () => {
const responseKeyNotFound = await request(app)
.get('/config/key/UNKNOWN_CONFIG_KEY?domain=Domain')
.set('Authorization', `Bearer ${adminMasterAccountToken}`)
.send().expect(500);

expect(responseKeyNotFound.body.error).not.toBeNull();
});

test('CONFIG_SUITE - Should NOT get Config by key - unauthenticated', async () => {
const responseUnauthenticated = await request(app)
.get(`/config/key/${config1Document.key}?domain=Domain`)
.send().expect(401);

expect(responseUnauthenticated.body.error).not.toBeNull();
});
});

describe('Testing configuration deletion', () => {
beforeAll(setupDatabase);

Expand Down
10 changes: 0 additions & 10 deletions tests/oauth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -803,16 +803,6 @@ describe('Testing protected resource access using an OAuth access token', () =>
expect(response.body.length).toBeGreaterThan(0);
});

test('OAUTH_SUITE - Should get a Config by key using an OAuth access token', async () => {
const response = await request(app)
.get(`/config/key/${config1Document.key}?domain=Domain`)
.set('Authorization', `Bearer ${accessToken}`)
.send().expect(200);

expect(response.body.key).toEqual(config1Document.key);
expect(response.body.enabled).toEqual(true);
});

test('OAUTH_SUITE - Should query configuration on /adm-graphql using an OAuth access token', async () => {
const response = await request(app)
.post('/adm-graphql')
Expand Down