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
2 changes: 1 addition & 1 deletion .github/workflows/master.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ jobs:
SWITCHER_API_LOGGER: false

- name: SonarCloud Scan
uses: sonarsource/sonarqube-scan-action@v8.4.1
uses: sonarsource/sonarqube-scan-action@v8.5.1
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
if: env.SONAR_TOKEN != ''
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/sonar.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ jobs:
SWITCHER_API_LOGGER: false

- name: SonarCloud Scan
uses: sonarsource/sonarqube-scan-action@v8.4.1
uses: sonarsource/sonarqube-scan-action@v8.5.1
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
if: env.SONAR_TOKEN != ''
Expand Down
80 changes: 17 additions & 63 deletions npm-shrinkwrap.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"jsonwebtoken": "^9.0.3",
"moment": "^2.31.0",
"mongodb": "^7.9.1",
"mongoose": "^9.12.3",
"mongoose": "^9.13.0",
"passport": "^0.7.0",
"@node-saml/passport-saml": "^5.1.1",
"pino": "^10.4.0",
Expand Down
4 changes: 2 additions & 2 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import oauthRouter from './routers/oauth.js';
import slackRouter from './routers/slack.js';
import gitOpsRouter from './routers/gitops.js';
import schema from './aggregator/schema.js';
import { auth, resourcesAuth, slackAuth, gitopsAuth } from './middleware/auth.js';
import { authAny, restrictOAuthGraphQL, resourcesAuth, slackAuth, gitopsAuth } from './middleware/auth.js';
import { DEFAULT_RATE_LIMIT, defaultLimiter } from './middleware/limiter.js';
import { createServer } from './app-server.js';

Expand Down Expand Up @@ -88,7 +88,7 @@ const handler = (req, res, next) =>
createHandler({ schema, context: req })(req, res, next);

// Admin: Aggregator API
app.use('/adm-graphql', auth, defaultLimiter, handler);
app.use('/adm-graphql', authAny, restrictOAuthGraphQL(['configuration']), defaultLimiter, handler);
// Slack: Aggregator API
app.use('/slack-graphql', slackAuth, handler);
// GitOps: Aggregator API
Expand Down
40 changes: 39 additions & 1 deletion src/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import basicAuth from 'express-basic-auth';
import jwt from 'jsonwebtoken';
import { parse, Kind } from 'graphql';
import { getAdmin, getAdminById } from '../services/admin.js';
import { validateAccessToken } from '../services/oauth.js';
import Admin from '../models/admin.js';
Expand Down Expand Up @@ -74,7 +75,8 @@ export async function auth(req, res, next) {
* 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`,
* and `GET /config/key/:key`. Don't default new routes to `authAny`;
* `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`).
*/
Expand All @@ -91,6 +93,7 @@ export async function authAny(req, res, next) {

req.token = token;
req.admin = admin;
req.isOAuth = strategy === validateAccessToken;
return next();
} catch (err) {
if (err.name === 'TokenExpiredError') {
Expand All @@ -105,6 +108,41 @@ export async function authAny(req, res, next) {
}
}

/**
* Restricts MCP/OAuth tokens (see `authAny`) to a set of top-level GraphQL
* query fields. Session JWTs are not restricted.
*
* OAuth requests are denied (403) unless the document is a single-operation
* `query` whose top-level selections are all plain fields listed in
* `allowedFields` (no mutations, introspection, or top-level fragments).
*/
export function restrictOAuthGraphQL(allowedFields) {
return (req, res, next) => {
if (!req.isOAuth) {
return next();
}

try {
const source = req.body?.query ?? req.query?.query;
const document = parse(String(source));
const operations = document.definitions.filter(d => d.kind === Kind.OPERATION_DEFINITION);

const allowed = operations.length === 1 &&
operations[0].operation === 'query' &&
operations[0].selectionSet.selections.every(s =>
s.kind === Kind.FIELD && allowedFields.includes(s.name.value));

if (allowed) {
return next();
}
} catch {
// unparsable documents are denied below
}

return res.status(403).send({ error: 'Operation not allowed for this token.' });
};
}

export async function authRefreshToken(req, res, next) {
try {
const token = getBearerToken(req);
Expand Down
48 changes: 48 additions & 0 deletions tests/oauth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,54 @@ describe('Testing protected resource access using an OAuth access token', () =>
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')
.set('Authorization', `Bearer ${accessToken}`)
.send({ query: `{ configuration(domain: "${domainId}", key: "${config1Document.key}", environment: "default") { config { key } } }` })
.expect(200);

expect(response.body.errors).toBeUndefined();
expect(response.body.data.configuration.config[0].key).toEqual(config1Document.key);
});

test('OAUTH_SUITE - Should NOT run other GraphQL operations using an OAuth access token', async () => {
const queries = [
`{ domain(_id: "${domainId}") { name } }`,
'{ __schema { types { name } } }',
`{ configuration(domain: "${domainId}") { domain { name } } domain(_id: "${domainId}") { name } }`,
`query { ...F } fragment F on Query { domain(_id: "${domainId}") { name } }`,
'mutation { foo }',
'not a query'
];

for (const query of queries) {
await request(app)
.post('/adm-graphql')
.set('Authorization', `Bearer ${accessToken}`)
.send({ query })
.expect(403);
}
});

test('OAUTH_SUITE - Should keep any query available for session JWT on /adm-graphql', async () => {
const response = await request(app)
.post('/adm-graphql')
.set('Authorization', `Bearer ${adminMasterAccountToken}`)
.send({ query: `{ domain(_id: "${domainId}") { name } }` })
.expect(200);

expect(response.body.data.domain.name).toEqual('Domain');
});

test('OAUTH_SUITE - Should NOT access /adm-graphql with an invalid token', async () => {
await request(app)
.post('/adm-graphql')
.set('Authorization', 'Bearer invalid-access-token')
.send({ query: '{ configuration(domain: "x") { domain { name } } }' })
.expect(401);
});

test('OAUTH_SUITE - Should NOT access protected resources with an invalid access token', async () => {
const response = await request(app)
.get('/domain')
Expand Down