Membrane API Gateway Documentation

repository·master·Indexed 20 days ago

https://github.com/membrane/api-gateway

A lightweight, high-performance API Gateway built on Java for managing REST, GraphQL, and legacy Web Services (SOAP/WSDL). Features include SQL-injection protection based on OWASP Core Rule Set, JSON API Greasing for testing, and flexible deployment options via Docker or RPM on RHEL 8. Supports configuration through proxies.xml using Spring Expression Language (SpEL) and modularization via include directives.

Tokens
77.8K
Snippets
287
Records
417
Agent score
70%

What's inside Membrane API Gateway

  1. Overview of Membrane API Gateway Configuration and Extension

    master

    Membrane API Gateway can be adapted and customized for real-world scenarios beyond basic reverse-proxy usage. Key extension capabilities include:

    • Behavior Modification: Using conditional logic, global plugin chains, and reusable plugin sequences to control how APIs and the gateway behave.
    • Message Persistence: Saving API messages using different ExchangeStore implementations like local disk (File ExchangeStore) or MongoDB ExchangeStore for inspection and analysis.
    • Java Integration: Extending the gateway by writing custom interceptors in Java or embedding the Membrane engine directly into an existing Java application.
    • Dynamic Routing: Using service discovery mechanisms like etcd to dynamically update routing based on available services.
  2. OAuth2 Implementation Examples

    master

    The security/oauth2 directory contains several implementation patterns for securing APIs and integrating with identity providers using OAuth2 and OpenID Connect. Available patterns include:

    • JWT Token Validation (Azure AD): Validating JWT tokens issued by Microsoft Azure Active Directory.
    • OAuth2 Resource Owner Password Flow: Securing APIs using username/password-based authentication.
    • OAuth2 Authorization Code Flow: Standard flow using authorization codes for web applications.
    • OAuth2 Client Credentials Flow: Machine-to-machine (M2M) authentication.
    • OAuth2 with OpenID Connect: Using Membrane as an OpenID Connect authorization server.
    • OAuth2 with Google: Authenticating users via Google OAuth2.
    • OAuth2 with GitHub: Authenticating users via GitHub OAuth2.
    • OAuth2 Implicit Flow: Browser-based authentication examples.
  3. Implement WebSocket interceptors using embedded or standalone examples

    master

    The custom-websocket-interceptor example directory provides two distinct patterns for integrating custom WebSocket interceptors into Membrane:

    1. Embedded Pattern: Creates an embedded Membrane instance within your own application code and adds the custom WebSocket interceptor directly to that instance.
    2. Standalone Pattern: Demonstrates how to compile a custom WebSocket interceptor as a separate component and integrate it into a fully standalone Membrane application deployment.
  4. Logging Requests and Responses

    master

    The logging examples demonstrate different ways to intercept and record API Gateway request and response data. Depending on your observability needs, you can choose from several logging strategies:

    • Console: Output logs directly to the standard console or a local log file.
    • CSV: Export log data into a structured CSV format for spreadsheet analysis.
    • JSON: Log data as JSON objects, ideal for ingestion by log aggregators like ELK or Splunk.
    • Database (JDBC): Persist request and response statistics directly into a relational database using JDBC.
  5. Explore Membrane API Gateway examples

    master
    The distribution/examples directory contains hands-on, ready-to-run samples for solving common API Gateway tasks. These examples cover deployment, security, transformation, and orchestration. You can use these samples to understand how to implement specific features like OpenAPI validation, JWT authentication, or JSON-to-XML transformation.
  6. Use ProblemDetails for API error responses

    master

    When returning error messages to an API caller, use the ProblemDetails (PD) format. Note that returning a PD is a way to communicate with the client and is not a substitute for server-side logging.

    A ProblemDetails object includes:

    • type and title: Basic error identification.
    • subtype(s): A string used to identify the specific error. The first component should be uncritical for security (e.g., /security/oauth2/keystore/invalid-alias).
    • component: The mandatory field identifying the component that caused the error.
    • detail: A human-readable description (returned in production).
    • internal/message: The raw message from the underlying exception.
  7. How OpenAPI validation routing works

    master

    When using OpenAPI validation, Membrane uses the servers definition within the OpenAPI specification to determine where to route the request.

    Example OpenAPI snippet for routing:

    info:
      ...
    servers:
      - url: http://localhost:3000

    Workflow:

    1. Membrane receives a request.
    2. The request is validated against the OpenAPI spec.
    3. If valid, Membrane forwards the request to the url specified in the servers section of the OpenAPI document.
    4. The backend response is optionally validated against the spec before being returned to the client.
  8. Resolve JSON Schema $ref URNs using schemaMappings

    master

    When working with complex JSON Schemas that use $id or $ref with URNs (e.g., urn:app:base_def), Membrane can resolve these references to local files using the schemaMappings configuration.

    In the provided example, schemas/schema2001.json contains URN references. These are resolved by mapping the URNs to specific local schema files (such as schemas/base.json and schemas/meta.json) within the API configuration (apis.yaml). This allows the validator to perform full schema validation even when the schema is modularized across multiple files via URNs.

  9. Flow guarantees in Request and Response flows

    master

    Membrane provides the following guarantees within its flow execution model:

    • In a Response-flow, a response is guaranteed to exist.
    • In a Request-flow, a request is guaranteed to exist.

    Because of these guarantees, developers do not need to perform null checks on the request or response objects within these specific flow contexts.

  10. Validate Requests and Responses against OpenAPI

    master

    Membrane can validate incoming requests and outgoing responses against OpenAPI specifications provided in YAML or JSON format. These specifications can be stored locally on disk or accessed via a network URL.

    Configuration

    To enable validation, use the OpenAPIProxy within your proxies.xml configuration. You can specify the location of the specification and set the validate attribute to requests (to validate incoming requests) or responses (to validate backend responses).

    Validation Behavior

    • Successful Validation: If the request matches the OpenAPI definition, Membrane forwards the request to the backend server defined in the servers section of the OpenAPI document and returns the backend's response to the client.
    • Validation Failure: If the request violates the specification, Membrane intercepts the request and returns a validation error response to the client immediately, without calling the backend.
    <api port="2000">
        <openapi location="contacts-api-v1.yml" validate="requests"/>
    </api>
  11. Protect MCP servers with mcpProtection

    master

    The mcpProtection plugin sits in front of a Model Context Protocol (MCP) server to control tool visibility and access. It uses a top-down rule evaluation where the first matching rule wins. Note that initialize and ping operations are always allowed by default.

    Use the tools list to specify allow or deny rules (supporting regex) for specific tools.

    api:
      port: 2000
      flow:
        - mcpProtection:
            tools:
              - allow: getCustomers
              - allow: getOrders
              - deny: '.*'
      target:
        url: http://my-mcp-server