Skip to content

Conversation

@Moumouls
Copy link
Member

@Moumouls Moumouls commented Oct 26, 2025

Pull Request

Issue

Closes: FILL_THIS_OUT

Approach

Update to V5, something changed on how introspection is managed internally, or maybe we got a bug before, introspection is always activated for master key, and public introspection is stil an option to opt in

Tasks

  • Add tests
  • Add changes to documentation (guides, repository pages, code comments)
  • Add security check
  • Add new Parse Error codes to Parse JS SDK

Summary by CodeRabbit

  • Chores

    • Upgraded Apollo Server to 5.0.0 and added updated Express integration for improved runtime compatibility.
  • Features

    • Revised GraphQL introspection behavior: server-level introspection enabled while access is now explicitly controlled so schema queries remain restricted unless authorized.
  • Tests

    • Added coverage for multiple introspection access scenarios to ensure correct authorization behavior.

@parse-github-assistant
Copy link

I will reformat the title to use the proper commit message syntax.

@parse-github-assistant parse-github-assistant bot changed the title feat: update apollo server feat: Update apollo server Oct 26, 2025
@parse-github-assistant
Copy link

parse-github-assistant bot commented Oct 26, 2025

🚀 Thanks for opening this pull request!

❌ Please fill out all fields with a placeholder FILL_THIS_OUT. If a field does not apply to the pull request, fill in n/a or delete the line.

@parseplatformorg
Copy link
Contributor

parseplatformorg commented Oct 26, 2025

Snyk checks have passed. No issues have been found so far.

Status Scanner Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@coderabbitai
Copy link

coderabbitai bot commented Oct 26, 2025

📝 Walkthrough

Walkthrough

Replaces Apollo Express adapter with @as-integrations/express5, bumps @apollo/server to 5.0.0, adds AST-based __type introspection detection and guard logic, and adds tests covering aliased and key-authorized introspection scenarios.

Changes

Cohort / File(s) Summary
Dependency updates
package.json
Upgrades @apollo/server 4.12.1 → 5.0.0 and adds @as-integrations/express5@1.1.2
GraphQL server & introspection control
src/GraphQL/ParseGraphQLServer.js
Replaces @apollo/server/express4 import with @as-integrations/express5; adds parse import and helpers hasTypeIntrospection(query) and throwIntrospectionError(); implements two-step introspection detection (fast string check for __schema, AST check for __type) and uses these in the introspection plugin; sets ApolloServer introspection: true in initialization
Tests: introspection coverage
spec/ParseGraphQLServer.spec.js
Adds tests asserting blocking of __type introspection (including aliased forms) without master/maintenance key and allowing introspection with master/maintenance key or when public introspection is enabled; introduces server reconfiguration in test setup for introspection-enabled cases

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Express
  participant ParseGraphQLServer
  participant ApolloServer
  participant IntrospectionPlugin

  Client->>Express: HTTP GraphQL request
  Express->>ParseGraphQLServer: route handling
  ParseGraphQLServer->>ApolloServer: forward request
  ApolloServer->>IntrospectionPlugin: onRequest / requestDidStart
  IntrospectionPlugin->>IntrospectionPlugin: fast string check for "__schema"
  alt contains "__schema"
    IntrospectionPlugin-->>ApolloServer: throw introspection error
  else contains "__type"
    IntrospectionPlugin->>ParseGraphQLServer: parse query AST (hasTypeIntrospection)
    alt AST indicates type introspection
      IntrospectionPlugin-->>ApolloServer: throw introspection error
    else
      IntrospectionPlugin-->>ApolloServer: allow request
    end
  else
    IntrospectionPlugin-->>ApolloServer: allow request
  end
  ApolloServer-->>Client: response / error
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas to focus review:
    • Correct usage and compatibility of the new @as-integrations/express5 adapter with current server setup.
    • Correctness and completeness of AST-based __type detection (edge cases, aliases, fragments).
    • Tests: ensure reconfiguration setup/teardown doesn't leak state between suites and that all authorization paths (master/maintenance/public) are covered.

Possibly related PRs

Suggested reviewers

  • mtrezza

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description follows the required template structure and includes all major sections: Issue, Approach, and Tasks. However, the Issue section is incomplete—it contains only the placeholder text "Closes: FILL_THIS_OUT" without linking to an actual GitHub issue, which is a required field explicitly identified in both the template and the PR objectives. The Approach section provides some explanation of the changes but is somewhat vague and unclear ("Update to V5, something changed on how introspection is managed internally..."). The Tasks section is present with items listed but all remain unchecked, which may be appropriate if no documentation, security checks, or error code changes are needed. Fill out the Issue section by adding the GitHub issue number or link that this PR addresses (replacing "FILL_THIS_OUT" with an actual issue reference). Additionally, clarify the Approach section to better explain the introspection behavior changes and their rationale, and review the Tasks checklist to confirm whether any of the listed items apply and should be marked as completed or deleted as instructed.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title "perf: Update to @apollo/server 5.0.0" accurately references the Apollo Server version upgrade from 4.12.1 to 5.0.0, which is indeed a primary change in the pull request's package.json modifications. The title is concise and specific enough for a developer scanning history to understand the core dependency update. However, the raw summary indicates that beyond the version bump, the PR includes significant changes to introspection handling logic (new helpers, two-step introspection checks, and extensive test coverage), which represent behavioral modifications rather than performance improvements. While the "perf:" prefix may be somewhat inaccurate given the nature of the introspection logic changes, the title does capture a real and substantial aspect of the changeset.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ast-grep (0.39.6)
spec/ParseGraphQLServer.spec.js

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/GraphQL/ParseGraphQLServer.js (1)

16-52: Consider using Apollo Server v5's native introspection controls instead of string-based detection.

Apollo Server v5 provides built-in introspection controls via the introspection boolean option, the nodeEnv option to override NODE_ENV-derived defaults, and validationRules including a disable-introspection validation rule that runs before execution. The verification found no existing false positive scenarios in the codebase (no user-defined fields or classes containing __schema), so the current string-based detection works correctly. However, leveraging Apollo's native introspection option or validation rules would be more robust and maintainable than a custom plugin with includes('__schema') detection.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 00f8d4c and bbdeb06.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • package.json (1 hunks)
  • src/GraphQL/ParseGraphQLServer.js (2 hunks)
🔇 Additional comments (2)
src/GraphQL/ParseGraphQLServer.js (1)

4-4: LGTM: Correct import for Apollo Server v5.

The migration from @apollo/server/express4 to @as-integrations/express5 aligns with Apollo Server v5's architectural changes, where Express integration was moved to a separate package.

package.json (1)

23-24: No breaking changes or security issues detected with Apollo Server 5.0.0 upgrade.

Apollo Server 5.0.0 has no known security vulnerabilities, and all critical breaking changes are properly addressed:

  • Node.js v20.0.0+ is required; package.json correctly constrains versions to compatible ranges (>=20.18.0, >=22.12.0)
  • graphql >= v16.11.0 is required as a peer dependency; the codebase specifies 16.11.0
  • Express middleware import has changed; this is addressed in the codebase migration

Comment on lines +107 to 108
introspection: true,
plugins: [ApolloServerPluginCacheControlDisabled(), IntrospectionControlPlugin(this.config.graphQLPublicIntrospection)],
Copy link

@coderabbitai coderabbitai bot Oct 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify the introspection behavior change with Apollo Server v5 migration.

The introspection configuration has changed from dynamic (config.graphQLPublicIntrospection) to always true with plugin-based access control. This architectural shift delegates enforcement to IntrospectionControlPlugin rather than Apollo Server's native configuration.

According to the PR description, the intended behavior is:

  • Master key: introspection always enabled ✓
  • Public: introspection remains opt-in via config.graphQLPublicIntrospection

Please verify:

  1. Introspection queries with master key work correctly
  2. Introspection queries without master key are blocked when graphQLPublicIntrospection is false
  3. Introspection queries without master key succeed when graphQLPublicIntrospection is true

You may also want to check Apollo Server v5 documentation for the recommended introspection control pattern:


🌐 Web query:

Apollo Server 5 introspection control best practices

💡 Result:

Short best-practices checklist for controlling introspection in Apollo Server 5

  1. Make introspection environment-aware — disable in production, enable in dev/staging. Use an env var to set ApolloServer.introspection. [1][2]

    Example: set introspection: process.env.NODE_ENV !== 'production'. [2]

  2. If you must allow introspection in production, restrict it to authenticated/trusted users only — gate via middleware or a custom validation rule (e.g., NoSchemaIntrospectionCustomRule when unauthenticated). [3][5]

  3. Use a schema registry / Apollo Studio instead of public introspection for team discovery and change history — publish schemas so developers don’t need endpoint introspection. [1][2]

  4. Layer other protections (don’t rely on “security through obscurity” alone):

    • Query depth/complexity and cost analysis.
    • Rate limiting, per-client quotas, and field-level throttling.
    • Operation whitelisting (allow only vetted queries).
    • Strong auth & authorization for every resolver.
    • Mask detailed error/stack traces in production. [1][3][5]
  5. CI / deployment controls:

    • Run automated breaking-change checks (graphql-inspector or schema checks) before deploy.
    • Treat introspection toggles as part of config reviewed in releases. [5]
  6. Monitoring & incident response:

    • Log and monitor unusual query patterns and failed introspection attempts.
    • Alert on spikes that may indicate automated schema-recon attacks. [1][4]

Recommended reading / references

  • Apollo GraphOS / Security guidance (turn off production introspection, use Studio). [1]
  • Apollo blog: “Why You Should Disable GraphQL Introspection in Production” (how-to example). [2]
  • GraphQL.org: introspection and NoSchemaIntrospectionCustomRule guidance. [3]
  • “Going to Production” / graphql-js production checklist (depth limits, validation rules). [5]

References
[1] Apollo GraphQL — Graph Security / Security pages.
[2] Apollo GraphQL blog — Why You Should Disable GraphQL Introspection In Production.
[3] graphql.org — Security / Introspection docs and NoSchemaIntrospectionCustomRule.
[4] Apollo GraphQL — 9 Ways To Secure your GraphQL API (security checklist).
[5] graphql-js — Going to Production guidance.

Would you like a short Apollo Server 5 code example showing environment-based introspection + a conditional validation rule?


Apollo Server 5 introspection configuration contradicts security best practices — introspection should be disabled at server level.

Apollo Server 5 best practices recommend making introspection environment-aware (disable in production, enable in dev/staging) and if introspection must be allowed in production, restricting it to authenticated/trusted users only via middleware or custom validation rules.

The current implementation sets introspection: true unconditionally, which contradicts this guidance. The recommended pattern is to use a schema registry/Apollo Studio instead of public introspection, and layer other protections such as query depth/complexity analysis and rate limiting.

Fix: Change line 107 from introspection: true to introspection: false (or environment-aware: introspection: process.env.NODE_ENV !== 'production'), and let IntrospectionControlPlugin handle conditional enablement for authenticated master keys only. This follows the principle of fail-closed (deny by default) with opt-in access for trusted clients.

🤖 Prompt for AI Agents
In src/GraphQL/ParseGraphQLServer.js around lines 107 to 108, the server is
configured with unconditional introspection enabled which violates best
practices; change the server-level introspection setting to fail-closed (e.g.
set introspection to false or make it environment-aware like
process.env.NODE_ENV !== 'production') so the default is disabled, and rely on
IntrospectionControlPlugin for conditional/exempted access
(authenticated/trusted clients) while also ensuring any related tests/configs
reflect the new default.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Help me understand this change. We just added this option to restrict introspection. Does this make introspection available only with masterKey? Is there any other place in code where the config option is used?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for all occurrences of graphQLPublicIntrospection in the codebase
echo "=== Searching for graphQLPublicIntrospection usage ==="
rg -n "graphQLPublicIntrospection" -C 3

echo -e "\n=== Finding related test files ==="
fd -e spec.js -e test.js | xargs rg -l "introspection" 2>/dev/null | head -20

echo -e "\n=== Checking ParseGraphQLController for config definition ==="
fd "ParseGraphQLController" --type f -e js -e ts | head -5

Length of output: 5735


🏁 Script executed:

#!/bin/bash
# Check the introspection test to understand expected behavior
echo "=== Introspection test details ==="
rg -n -A 30 "should have public introspection enabled if enabled" spec/ParseGraphQLServer.spec.js

echo -e "\n=== Check for related introspection tests ==="
rg -n -B 5 -A 20 "public introspection" spec/ParseGraphQLServer.spec.js | head -100

Length of output: 2884


@mtrezza Great questions! Let me clarify how this change works:

How the introspection control works now:

The graphQLPublicIntrospection config option is still used and functional — it's passed to the IntrospectionControlPlugin on line 108. The architectural change is that Apollo Server's native introspection setting is now always true, but the actual access control is handled by the custom plugin.

Behavior breakdown:

  1. With graphQLPublicIntrospection: false (default):

    • ✅ Master key or maintenance key → introspection allowed
    • ❌ No master key → introspection blocked (403 error)
  2. With graphQLPublicIntrospection: true:

    • ✅ Anyone can introspect (with or without master key)

Why this change was needed:

Apollo Server's native introspection setting is binary (on/off), but the requirement is ternary:

  • Master/maintenance keys should always have introspection access
  • Public access should be opt-in via config

The IntrospectionControlPlugin (lines 17-50) implements this logic:

if (publicIntrospection) {
  return; // Allow all
}
if (isMasterOrMaintenance) {
  return; // Allow master/maintenance
}
// Otherwise block introspection queries

Other places the config is used:

  • Security checks: src/Security/CheckGroups/CheckGroupServerConfig.js (warns if public introspection is enabled)
  • Config definitions: src/Options/Definitions.js, src/Options/index.js
  • Tests: spec/ParseGraphQLServer.spec.js validates all three scenarios
  • Documentation: src/Options/docs.js

The tests confirm this behavior works as expected across all scenarios.


🧬 Code Graph Analysis Results

[ParseGraphQLServer.js, lines 4-22]
const IntrospectionControlPlugin = (publicIntrospection) => ({

requestDidStart: (requestContext) => ({

didResolveOperation: async () => {
  // If public introspection is enabled, we allow all introspection queries
  if (publicIntrospection) {
    return;
  }

  const isMasterOrMaintenance = requestContext.contextValue.auth?.isMaster || requestContext.contextValue.auth?.isMaintenance
  if (isMasterOrMaintenance) {
    return;
  }

  // Now we check if the query is an introspection query
  // this check strategy should work in 99.99% cases
  // we can have an issue if a user name a field or class __schemaSomething
  // we want to avoid a full AST check
  const isIntrospectionQuery =
    requestContext.request.query?.includes('__schema')

  if (isIntrospectionQuery) {
    throw new GraphQLError('Introspection is not allowed', {
      extensions: {
        http: {
          status: 403,
        },
      }
    });
  }
},

})

});

[ParseGraphQLServer.js, lines 40-50]
const apollo = new ApolloServer({
csrfPrevention: {
// See https://www.apollographql.com/docs/router/configuration/csrf/
// needed since we use graphql upload
requestHeaders: ['X-Parse-Application-Id'],
},
introspection: true,
plugins: [ApolloServerPluginCacheControlDisabled(), IntrospectionControlPlugin(this.config.graphQLPublicIntrospection)],
schema,
});
await apollo.start();
this._server = expressMiddleware(apollo, {
context,
});
return this._server;
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So there is no security issue with this change?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the introspection tests for security scenarios
echo "=== Checking introspection test coverage ==="
rg -n -A 40 "describe.*introspection" spec/ParseGraphQLServer.spec.js

echo -e "\n=== Look for __type queries (another introspection mechanism) ==="
rg -n "__type" spec/ParseGraphQLServer.spec.js

echo -e "\n=== Check if the plugin handles all introspection query types ==="
rg -n "__schema|__type|__typename" src/GraphQL/ParseGraphQLServer.js

Length of output: 21398


🏁 Script executed:

#!/bin/bash
# Search for tests that verify introspection is blocked
echo "=== Looking for tests that verify introspection blocking ==="
rg -n -B 5 -A 15 "should.*not.*introspection|introspection.*blocked|introspection.*disabled" spec/ParseGraphQLServer.spec.js

echo -e "\n=== Looking for tests with graphQLPublicIntrospection config ==="
rg -n -B 3 -A 10 "graphQLPublicIntrospection" spec/ParseGraphQLServer.spec.js

echo -e "\n=== Check for any introspection security tests ==="
rg -n -B 5 -A 10 "403.*introspection|Introspection is not allowed" spec/ParseGraphQLServer.spec.js

Length of output: 1967


🏁 Script executed:

#!/bin/bash
# Check a sample __type query test to see if it uses master key
echo "=== Examining __type query test context (around line 741) ==="
sed -n '720,780p' spec/ParseGraphQLServer.spec.js

echo -e "\n=== Check if tests without master key use __type ==="
# Look for tests that explicitly don't use master key and check if they use __type
rg -n -B 10 "__type.*name.*Query" spec/ParseGraphQLServer.spec.js | head -60

echo -e "\n=== Check the test setup for apollo client configuration ==="
rg -n -A 5 "createApolloClient|apolloClient.*=|new ApolloClient" spec/ParseGraphQLServer.spec.js | head -40

Length of output: 3483


🏁 Script executed:

#!/bin/bash
# Check the test context around the introspection and __type tests
echo "=== Looking at test setup before introspection tests ==="
sed -n '600,650p' spec/ParseGraphQLServer.spec.js

echo -e "\n=== Looking at apolloClient setup in the test file ==="
sed -n '460,490p' spec/ParseGraphQLServer.spec.js

echo -e "\n=== Check if httpLink includes master key ==="
rg -n -B 5 -A 5 "httpLink.*=|createHttpLink" spec/ParseGraphQLServer.spec.js | head -50

Length of output: 4268


🏁 Script executed:

#!/bin/bash
# Check what the headers variable contains
echo "=== Looking for headers variable definition ==="
rg -n -B 2 -A 5 "^[ ]*headers[ ]*=" spec/ParseGraphQLServer.spec.js | head -60

echo -e "\n=== Check what headers are used by default in tests ==="
sed -n '1,100p' spec/ParseGraphQLServer.spec.js | grep -A 10 "headers"

echo -e "\n=== Look for default header setup in the test ==="
rg -n "X-Parse-Master-Key.*test|masterKey.*headers" spec/ParseGraphQLServer.spec.js | head -20

Length of output: 1225


🏁 Script executed:

#!/bin/bash
# Check the describe block setup to see default headers
echo "=== Looking at the main describe block setup ==="
sed -n '40,100p' spec/ParseGraphQLServer.spec.js

echo -e "\n=== Looking for where headers constant is defined ==="
rg -n "const headers|let headers" spec/ParseGraphQLServer.spec.js | head -10

echo -e "\n=== Check around line 460 for full context of apolloClient setup ==="
sed -n '440,480p' spec/ParseGraphQLServer.spec.js

Length of output: 3680


🏁 Script executed:

#!/bin/bash
# Check what headers is set to at line 279
echo "=== Looking at headers definition at line 279 ==="
sed -n '275,285p' spec/ParseGraphQLServer.spec.js

echo -e "\n=== Looking at the broader context around line 279 ==="
sed -n '270,320p' spec/ParseGraphQLServer.spec.js

echo -e "\n=== Check if headers includes master key by default ==="
sed -n '275,295p' spec/ParseGraphQLServer.spec.js

Length of output: 1930


@mtrezza Yes, there is a security issue with this change. I've identified a critical vulnerability in the introspection control implementation.

The Security Problem

The IntrospectionControlPlugin only blocks queries containing __schema, but GraphQL has multiple introspection mechanisms:

  1. __schema - blocked by the plugin ✅
  2. __type - NOT blocked by the plugin ❌
  3. __typename - typically allowed (used in normal queries)

Proof of the Vulnerability

Looking at the test suite:

Default headers (line 279):

const headers = {
  'X-Parse-Application-Id': 'test',
  'X-Parse-Javascript-Key': 'test',
  // NO MASTER KEY
};

These __type introspection queries run without master key throughout the tests:

  • Line 741: __type(name: "Object")
  • Line 756: __type(name: "Date")
  • Line 931: __type(name: "Query")
  • Hundreds more...

All these tests pass, meaning __type queries work without master key even when graphQLPublicIntrospection: false, effectively bypassing the introspection restriction.

Why This Change Makes It Worse

Before (Apollo Server v4):

introspection: this.config.graphQLPublicIntrospection
  • Apollo Server natively blocked all introspection queries when set to false
  • This included both __schema and __type

After (This PR):

introspection: true  // Always enabled at Apollo level
  • Apollo Server allows all introspection
  • Plugin only blocks __schema queries
  • __type queries completely bypass security

Recommended Fix

The plugin needs to check for all introspection query types:

const isIntrospectionQuery =
  requestContext.request.query?.includes('__schema') ||
  requestContext.request.query?.includes('__type')

Or better yet, consider reverting to Apollo Server's native introspection configuration and using validation rules for conditional master-key access, as that's more robust than string matching.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai is there a way to limit public __type introspection to what is needed for the Parse.File functionality?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for Parse.File GraphQL schema definition and __type usage
echo "=== Searching for Parse.File type definitions in GraphQL schema ==="
rg -n "__type" --type js -C 5 src/GraphQL/

echo -e "\n=== Looking for File type schema definitions ==="
rg -n "type.*File|FileInfo|_File" src/GraphQL/ --type js -C 3 | head -80

echo -e "\n=== Searching for __type field usage in tests ==="
rg -n "__type" spec/ParseGraphQLServer.spec.js -C 3 | head -100

echo -e "\n=== Check Parse.File related GraphQL operations ==="
rg -n "Parse\.File|FileInfo" spec/ParseGraphQLServer.spec.js -C 5 | head -60

Length of output: 32638


@mtrezza Yes, there's a way to limit public __type introspection while preserving Parse.File functionality!

The Key Distinction

The search results reveal that __type is used in two completely different ways:

  1. Parse's internal JSON representation (data):

    { __type: 'File', name: 'foo.jpg', url: 'https://...' }
    { __type: 'Date', iso: '2016-05-22T09:00:00.000Z' }
    { __type: 'Pointer', className: 'User', objectId: '...' }
  2. GraphQL introspection query (schema exploration):

    query {
      __type(name: "FileInfo") {  # ← Note the parentheses!
        kind
        fields { name }
      }
    }

The Solution

Introspection queries always use function call syntax with parentheses: __type(
Data fields never have parentheses: just __type as a property

The plugin can check for __type( to block introspection while allowing Parse's internal __type property:

const isIntrospectionQuery =
  requestContext.request.query?.includes('__schema') ||
  requestContext.request.query?.includes('__type(')

This works because:

  • ✅ Blocks introspection: query { __type(name: "User") { ... } } contains __type(
  • ✅ Allows Parse.File: GraphQL never sends the JSON representation as part of the query string — the { __type: 'File' } object exists only in response data and variables, not in the query text itself

Why This Is Safe

When you save a Parse.File, the client sends:

mutation {
  createObject(fields: { photo: { file: "photo.jpg" } })
}

The { __type: 'File', name: 'photo.jpg' } representation is created server-side by the transformers (see src/GraphQL/transformers/mutation.js lines 98-100). The query string itself never contains __type as a field access.

Recommendation

Update the plugin on line 36-37 from:

const isIntrospectionQuery =
  requestContext.request.query?.includes('__schema')

To:

const isIntrospectionQuery =
  requestContext.request.query?.includes('__schema') ||
  requestContext.request.query?.includes('__type(')

This provides complete introspection blocking (both __schema and __type mechanisms) while preserving all Parse.File and other special type functionality.


🧬 Code Graph Analysis Results

[src/GraphQL/ParseGraphQLServer.js] Introspection control mechanism

Snippet (complete):

const IntrospectionControlPlugin = (publicIntrospection) => ({

requestDidStart: (requestContext) => ({
didResolveOperation: async () => {
// If public introspection is enabled, we allow all introspection queries
if (publicIntrospection) {
return;
}

  const isMasterOrMaintenance = requestContext.contextValue.auth?.isMaster || requestContext.contextValue.auth?.isMaintenance
  if (isMasterOrMaintenance) {
    return;
  }

  // Now we check if the query is an introspection query
  // this check strategy should work in 99.99% cases
  // we can have an issue if a user name a field or class __schemaSomething
  // we want to avoid a full AST check
  const isIntrospectionQuery =
    requestContext.request.query?.includes('__schema')

  if (isIntrospectionQuery) {
    throw new GraphQLError('Introspection is not allowed', {
      extensions: {
        http: {
          status: 403,
        },
      }
    });
  }
},

})

});

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Moumouls what do you think? Are we onto something here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mtrezza coderabbit suggestion is wrong, because GQL spec allow line return after "__type"

Example query

image image

The suggested change will not work, and can be bypassed easily

A smart move could be:

  • string match on __type and __schema
  • if __type match, let's parse AST to ensure that it's not the root field introspection query

So we only parse the request in case the request looks suspicious :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'll add it it's not that hard

@codecov
Copy link

codecov bot commented Oct 26, 2025

Codecov Report

❌ Patch coverage is 94.73684% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 93.00%. Comparing base (b298ccc) to head (7f522e2).
⚠️ Report is 1 commits behind head on alpha.

Files with missing lines Patch % Lines
src/GraphQL/ParseGraphQLServer.js 94.73% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            alpha    #9888      +/-   ##
==========================================
- Coverage   93.01%   93.00%   -0.02%     
==========================================
  Files         187      187              
  Lines       15163    15177      +14     
  Branches      177      177              
==========================================
+ Hits        14104    14115      +11     
- Misses       1047     1050       +3     
  Partials       12       12              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mtrezza mtrezza changed the title feat: Update apollo server perf: Update to @apollo/server 5.0.0 Oct 26, 2025
@Moumouls
Copy link
Member Author

@mtrezza i improved the system
btw: this update need to drop node 18 for parse-server

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
spec/ParseGraphQLServer.spec.js (3)

733-771: Harden negative introspection tests with fragments and variables.

Great coverage for direct and aliased __type; consider adding fragment- and variable-based cases to prevent bypass via AST shape changes.

Example additions:

+        it('should block __type introspection in fragment without master key', async () => {
+          try {
+            await apolloClient.query({
+              query: gql`
+                query {
+                  ...Frag
+                }
+                fragment Frag on Query {
+                  __type(name: "User") { name }
+                }
+              `,
+            });
+            fail('should have thrown an error');
+          } catch (e) {
+            expect(e.message).toEqual('Response not successful: Received status code 403');
+            expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
+          }
+        });
+
+        it('should block variable-based __type introspection without master key', async () => {
+          try {
+            await apolloClient.query({
+              query: gql`
+                query TypeIntrospection($name: String!) {
+                  __type(name: $name) { name }
+                }
+              `,
+              variables: { name: 'User' },
+            });
+            fail('should have thrown an error');
+          } catch (e) {
+            expect(e.message).toEqual('Response not successful: Received status code 403');
+            expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
+          }
+        });

773-792: Strengthen positive assertions for allowed __type results.

When introspection is permitted, assert specific fields (e.g., name === 'User', kind === 'OBJECT') to catch regressions beyond mere success.

Example:

-          expect(introspection.data).toBeDefined();
-          expect(introspection.data.__type).toBeDefined();
+          expect(introspection.data?.__type?.name).toBe('User');
+          expect(introspection.data?.__type?.kind).toBe('OBJECT');
+          expect(introspection.errors).toBeUndefined();

Also applies to: 794-813, 815-834, 836-852


1678-1681: Avoid redundant cache reset before recreating the server.

You reset caches then replace parseGraphQLServer with a new instance, which already starts clean. Drop the reset to shave test time.

-          await parseGraphQLServer.setGraphQLConfig({});
-          await resetGraphQLCache();
-          await createGQLFromParseServer(parseServer, { graphQLPublicIntrospection: true });
+          await parseGraphQLServer.setGraphQLConfig({});
+          await createGQLFromParseServer(parseServer, { graphQLPublicIntrospection: true });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bbdeb06 and 7f522e2.

📒 Files selected for processing (2)
  • spec/ParseGraphQLServer.spec.js (5 hunks)
  • src/GraphQL/ParseGraphQLServer.js (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-05-09T09:59:06.289Z
Learnt from: mtrezza
PR: parse-community/parse-server#9445
File: spec/ParseLiveQuery.spec.js:1340-1375
Timestamp: 2025-05-09T09:59:06.289Z
Learning: New tests in the parse-server repository should use async/await with promise-based patterns rather than callback patterns with `done()`. The preferred pattern is to create a Promise that resolves when an expected event occurs, then await that Promise.

Applied to files:

  • spec/ParseGraphQLServer.spec.js
🧬 Code graph analysis (1)
spec/ParseGraphQLServer.spec.js (1)
spec/helper.js (2)
  • parseServer (167-167)
  • reconfigureServer (180-214)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: PostgreSQL 15, PostGIS 3.3
  • GitHub Check: PostgreSQL 15, PostGIS 3.4
  • GitHub Check: PostgreSQL 16, PostGIS 3.5
  • GitHub Check: Node 18
  • GitHub Check: PostgreSQL 17, PostGIS 3.5
  • GitHub Check: PostgreSQL 18, PostGIS 3.6
  • GitHub Check: PostgreSQL 15, PostGIS 3.5
  • GitHub Check: Node 20
  • GitHub Check: Redis Cache
  • GitHub Check: MongoDB 8, ReplicaSet
  • GitHub Check: MongoDB 6, ReplicaSet
  • GitHub Check: MongoDB 7, ReplicaSet
  • GitHub Check: Code Analysis (javascript)
  • GitHub Check: Docker Build
🔇 Additional comments (8)
src/GraphQL/ParseGraphQLServer.js (4)

4-4: LGTM! Import changes align with Apollo Server v5 migration.

The migration from @apollo/server/express4 to @as-integrations/express5 and the addition of parse for AST-based introspection detection are necessary for the upgrade.

Also applies to: 7-7


38-46: LGTM! Clean error handling extraction.

The helper function provides consistent error messaging and proper HTTP 403 status for introspection denial.


64-78: LGTM! Well-optimized two-stage introspection check.

The implementation balances security and performance effectively:

  • Fast path for __schema (simple string match)
  • Smart path for __type (AST parsing only when string is present)
  • Comments clearly explain the rationale

This addresses the performance concerns and bypass risks discussed in previous comments. The AST-based approach correctly handles whitespace variations that would bypass simple string matching like __type(.

Note: Once the fragment bypass issue in hasTypeIntrospection is fixed, this logic will be fully secure.


138-138: LGTM! Introspection control architecture is sound.

Based on the extensive discussion in previous review comments, setting introspection: true at the Apollo Server level is the correct approach for Apollo Server v5. The IntrospectionControlPlugin handles the ternary access control logic (master key always allowed, public opt-in via graphQLPublicIntrospection), which cannot be expressed through Apollo's native binary introspection setting.

spec/ParseGraphQLServer.spec.js (4)

857-859: Enabling public introspection per-suite is appropriate.

This localizes schema type checks that rely on __type without requiring master key. LGTM.


1019-1021: Relay suite setup looks good.

Recreating the server with graphQLPublicIntrospection avoids auth headers in type lookups. LGTM.


1567-1568: Parse Class Types suite setup is consistent.

Per-suite enablement keeps tests independent. LGTM.


7968-7969: Function mutations suite setup is sound.

Recreating with public introspection avoids auth headers for enum/type checks. LGTM. Based on learnings.

Comment on lines +16 to +36
const hasTypeIntrospection = (query) => {
try {
const ast = parse(query);
// Check only root-level fields in the query
// Note: selection.name.value is the actual field name, so this correctly handles
// aliases like "myAlias: __type(...)" where name.value === "__type"
for (const definition of ast.definitions) {
if (definition.kind === 'OperationDefinition' && definition.selectionSet) {
for (const selection of definition.selectionSet.selections) {
if (selection.kind === 'Field' && selection.name.value === '__type') {
return true;
}
}
}
}
return false;
} catch (e) {
// If parsing fails, we assume it's not a valid query and let Apollo handle it
return false;
}
};
Copy link

@coderabbitai coderabbitai bot Oct 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Fragment definitions can bypass introspection control.

The function only checks OperationDefinition selections, but GraphQL allows defining introspection queries in named fragments that are then spread into operations:

fragment IntrospectionFragment on Query {
  __type(name: "User") { fields { name } }
}

query {
  ...IntrospectionFragment
}

This bypasses the check entirely because FragmentDefinition nodes are not inspected.

Apply this diff to check fragment definitions:

 const hasTypeIntrospection = (query) => {
   try {
     const ast = parse(query);
     // Check only root-level fields in the query
     // Note: selection.name.value is the actual field name, so this correctly handles
     // aliases like "myAlias: __type(...)" where name.value === "__type"
     for (const definition of ast.definitions) {
-      if (definition.kind === 'OperationDefinition' && definition.selectionSet) {
+      if ((definition.kind === 'OperationDefinition' || definition.kind === 'FragmentDefinition') && definition.selectionSet) {
         for (const selection of definition.selectionSet.selections) {
           if (selection.kind === 'Field' && selection.name.value === '__type') {
             return true;
           }
         }
       }
     }
     return false;
   } catch (e) {
     // If parsing fails, we assume it's not a valid query and let Apollo handle it
     return false;
   }
 };
🤖 Prompt for AI Agents
In src/GraphQL/ParseGraphQLServer.js around lines 16 to 36, the current
hasTypeIntrospection only inspects OperationDefinition root fields and misses
FragmentDefinition usage; update it to build a map of FragmentDefinition nodes
from the AST and traverse selections recursively (handle Field, InlineFragment,
and FragmentSpread), resolving FragmentSpread by looking up the fragment in the
map and descending into its selectionSet, and maintain a visited-fragment set to
avoid cycles; return true if any visited Field has name.value === '__type' (or
nested contains it), otherwise false, and keep the existing try/catch behavior.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'll take a look

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Moumouls, sounds good! Let me know if you need any clarification on the fragment bypass issue or if you'd like me to help verify the fix once you've implemented it. 🐰

@mtrezza mtrezza added the state:breaking Breaking change requires major version increment and `BREAKING CHANGE` commit message label Oct 29, 2025
@mtrezza
Copy link
Member

mtrezza commented Oct 29, 2025

@mtrezza i improved the system btw: this update need to drop node 18 for parse-server

Marked as breaking change; can be merged with Parse Server 9 which will drop Node 18 support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state:breaking Breaking change requires major version increment and `BREAKING CHANGE` commit message

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants