Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects

Project: A Secured API Layer

Combine auth context, role-based field access, depth and cost limits, safe error formatting and tests in one runnable GraphQL security stand-in.

A GraphQL endpoint lets clients write their own queries. That is the whole appeal, and also the risk: anyone who can reach it can ask for expensive things, ask for fields they should not see, or try to learn from error messages. This project builds the layers that stand between a request and your data, then proves they work with tests.

The pieces come from earlier lessons: Authentication and Authorization, Query Depth, Complexity and Other Attacks and How Execution Works and How Errors Behave. Here they work together. No real server runs on this site: the production setup is read-only, and everything else is one runnable stand-in written in plain Node.

The layers

A request meets five checks

Authenticate Token in, user out. Once, at the edge.
Limit Reject too-deep or too-costly queries before running.
Authorize Roles and ownership, per field.
Mask errors Hide internals, keep safe codes.

Cheap checks first, so abuse costs you almost nothing.

1 / 2
flowchart LR
    R["HTTP request"] --> A["Authenticate<br/>build context"]
    A --> P["Parse"]
    P --> L["Depth and cost limits"]
    L --> E["Execute with field checks"]
    E --> F["Format errors"]
    F --> S["JSON response"]
    A -->|"bad token"| X["401"]
    L -->|"too big"| Y["400"]

Rejections happen as early as possible; only valid, affordable queries reach resolvers.

The schema

The schema is the part a real server would take as SDL. Note that email is nullable: if the viewer may not see it, the field can become null with an error instead of wiping out its whole parent.

GRAPHQL
type User {
  id: ID!
  name: String!
  email: String
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  author: User!
}

type Query {
  me: User
  posts(first: Int = 10): [Post!]!
  secretStats: String
  crash: String
}

secretStats is for administrators only. crash exists only so we can watch an unexpected failure being masked.

The stand-in gateway

Read the code in this order: the data and tokens, the limits (depthOf, costOf), the executor (field-level checks live there), formatError, handle (the whole pipeline) and finally the tests at the bottom. A few simplifications to keep in mind: the parser handles only { field(arg: value) { nested } }; auth is a lookup table instead of JWT or sessions; costs are a simple rule (each field costs 1, and a list multiplies the cost of its children by first). Real libraries offer more refined versions of each.

Node.js A secured stand-in: auth, roles, limits, error masking, tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study how each layer behaves. The anonymous request works, because reading posts is public. me fails with a code, not a crash. The email example shows field-level authorization turning one field into null with a FORBIDDEN error while its siblings still arrive. The cost limit stops a harmless-looking first: 50 request before a single resolver runs. The masked error shows the client only a request id, while the real message (with a password inside it) reaches the server log.

Authorization in this stand-in lives inside field resolvers to keep the code in one file. In a real API, put the rules in your business layer (a policy or service function) and call it from the resolver, so REST endpoints, jobs and GraphQL cannot disagree.

A persisted-query allow-list

The strictest option for a private API is to accept only queries you know in advance. At build time each client query is hashed and registered. At run time the client sends only the hash, and anything unknown is refused, which removes most query-based attacks in one stroke. Real systems (Apollo's persisted queries, Relay's compiler) do this; the stand-in shows the check.

Node.js Allow-list by query hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Allow-lists work well when you control every client. For a public API with unknown clients, depth and cost limits remain your main protection.

Going to production (read-only)

The same pipeline in a real deployment looks like this. These snippets are examples to adapt; check your server library's current documentation, since option names change.

JavaScript
// Example with Apollo Server 4 style options (read-only)
const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: process.env.NODE_ENV !== "production",
  validationRules: [depthLimit(6), costLimit({ maximumCost: 1000 })],
  formatError: (formatted, error) =>
    isExpected(error) ? formatted : { message: "Internal server error", extensions: { code: "INTERNAL" } },
});

Around the server, add: HTTPS only, a rate limit per client at the proxy, a request timeout, a cap on request body size (a megabyte of query text is also an attack), structured logs with the operation name but never variable values, and a CORS policy naming the origins you trust.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why run depth and cost checks before execution?

    Static analysis of the parsed query is cheap, so abusive requests are stopped before any expensive work starts.
  2. 2. A user may not see another user's email. What is a good result in this design?

    email is nullable, so a field-level failure stays local. Siblings keep their data.
  3. 3. What should a client see when an unexpected exception (a database error) occurs?

    Internal messages can leak secrets and structure. Log them privately and give the client something safe to quote to support.
  4. 4. Where should authentication normally happen?

    Authenticate at the edge and pass the result through the context. Resolvers then only make authorization decisions.
  5. 5. What does a persisted-query allow-list do?

    Clients send only a hash of a registered query. Unknown hashes are refused.

Summary

  • Layer your defenses: authenticate once, limit early, authorize per field, mask errors.
  • Depth and cost limits are cheap static checks on the parsed query.
  • Make fields that can be hidden nullable, so a denial stays local.
  • Put the real rules in the business layer; resolvers just call them.
  • Show clients safe error codes and request ids; keep details in logs.
  • Allow-lists of persisted queries suit APIs where you control the clients.
  • Test each layer, including the failure cases.

Next: Practice Exercises with Solutions.