Fiber Contrib

repository·main·Indexed 43 days ago

https://github.com/gofiber/contrib

A collection of third-party middlewares and service implementations for the Fiber web framework. Includes extensions for security and auth (Casbin, Coraza WAF, JWT, hCaptcha), observability (OpenTelemetry, Prometheus, Sentry, New Relic), logging (Zap, Zerolog), communication (Socket.io, WebSocket), and utilities like Circuit Breaker and Open Policy Agent (OPA).

Tokens
93K
Snippets
272
Records
362
Agent score
54%

What's inside Fiber Contrib

  1. Overview of gofiber/contrib

    main

    gofiber/contrib is a repository containing third-party middlewares and service implementations for the Fiber web framework. It provides a collection of extensions including security, observability, authentication, and utility tools to enhance Fiber applications.

    Go version support: The project only supports the latest two versions of Go. Check the official Go release page for details.

  2. What is Socket.io for Fiber?

    main

    Socket.io is a WebSocket wrapper for Fiber that implements the Engine.IO v4 / Socket.IO v5 wire protocol. It is designed to be fully compatible with the official socket.io-client library.

    Note for Migrations: If you previously used older socketio releases as a plain WebSocket event bus, you should migrate to github.com/gofiber/contrib/v3/websocket/event. A deprecated compatibility shim is available at github.com/gofiber/contrib/v3/socketio/legacy.

  3. Use SPNEGO Kerberos Authentication Middleware for Fiber v3

    main

    The spnego middleware provides SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) Kerberos authentication for Fiber v3 applications. It handles the SPNEGO negotiation process to authenticate users via Kerberos infrastructure.

    Requirements

    • Fiber v3
    • Kerberos infrastructure: A properly configured Kerberos environment is required for the middleware to function.
  4. Understand OpenTelemetry metrics behavior

    main

    When using the OTel middleware, note the following regarding request and response size measurements:

    • http.server.request.size and http.server.response.size are measured without buffering full streamed bodies into memory.
    • For streamed responses, the size is recorded when the stream reaches EOF.
    • For text/event-stream (SSE) responses, the response body size is not recorded.
  5. Handle WebSocket vs HTTP Long-polling transports

    main

    The Socket.io implementation supports both WebSocket and HTTP long-polling transports.

    When working with a socket instance (kws), you must account for the fact that kws.Conn (the underlying FastHTTP connection) is nil when the session is bound to HTTP long-polling.

    Best Practices:

    1. Use Listener APIs: Methods like Emit, Ack, Close, Broadcast, and EmitWithAck are transport-agnostic and work correctly regardless of whether the client is using WebSockets or long-polling.
    2. Guard Direct Access: If your code needs to touch the underlying WebSocket connection directly via kws.Conn, you must guard the operation to prevent nil pointer dereferences.

    Use kws.IsPolling() to explicitly check if the session is currently using long-polling.

    // Guarding direct connection access
    if kws.Conn != nil {
        // Access underlying FastHTTP connection
    } else {
        // Session is using HTTP long-polling
    }
    
    // Or checking transport type explicitly
    if kws.IsPolling() {
        // Handle long-polling specific logic
    }
  6. Implement custom KeytabLookup functions

    main

    The KeytabLookup field in spnego.Config expects a function that returns a *keytab.Keytab and an error. This allows you to fetch keytabs from databases, secrets managers, or remote services.

    Important Performance Note: KeytabLookup is called on every request (authenticated or not). If your lookup involves network calls or database queries, you must cache the result and refresh it out-of-band (e.g., via a TTL or rotation event) to avoid adding significant latency to every request.

    Security Warning: Do not return sensitive key material in the error returned by your lookup function. Errors are logged and passed to OnError. If you are reading a file, separate the file-reading error from the parsing error to avoid logging the key buffer.

    // Example: Retrieve keytab from a database
    func dbKeytabLookup() (*keytab.Keytab, error) {
        // Your database lookup logic here
        // ...
        return keytabFromDatabase, nil
    }
    
    // Example: Retrieve keytab from a remote service
    func remoteKeytabLookup() (*keytab.Keytab, error) {
        // Your remote service call logic here
        // ...
        return keytabFromRemote, nil
    }
  7. How WebSocket subprotocols work

    main

    The Subprotocols configuration field helps negotiate subprotocols by setting the Sec-Websocket-Protocol header.

    • All connections are sent to the handler function regardless of whether negotiation was successful.
    • You can retrieve the selected subprotocol using conn.Subprotocol().
    • Warning: If a client includes a Sec-Websocket-Protocol header but negotiation fails, the browser will immediately disconnect the connection after receiving the upgrade response.
  8. How CPULoadCriteria works

    main

    CPULoadCriteria implements the LoadCriteria interface using CPU usage as the metric. It uses a proportional rejection probability model based on two thresholds:

    • Below LowerThreshold: No requests are rejected.
    • Between LowerThreshold and UpperThreshold: The probability of rejecting a request increases as CPU usage approaches the UpperThreshold. The probability is calculated as: rejectionProbability := (cpuUsage - LowerThreshold*100) / (UpperThreshold - LowerThreshold)
    • Above UpperThreshold: All requests are rejected to prevent system overload.

    CPULoadCriteria Properties

    PropertyTypeDescription
    LowerThresholdfloat64Lower CPU usage threshold as a fraction (0.0 to 1.0).
    UpperThresholdfloat64Upper CPU usage threshold as a fraction (0.0 to 1.0).
    Intervaltime.DurationTime interval over which CPU usage is averaged.
    GetterCPUPercentGetterInterface to retrieve CPU usage percentages.
  9. Access Uptime status via JSON API

    main

    The Uptime middleware provides a JSON API that returns a snapshot of the current status. This snapshot is held in memory for one SampleInterval to minimize backing-store load.

    You can access this data at {UI.Path}/api/status. This is useful for building custom dashboards.

    The status object includes a summary for each service containing:

    • has_data (bool)
    • availability_rate (float)
    • estimated_downtime_seconds (int)
    • affected_days (int)
    • stable_streak_days (int)
    • stable_streak_capped (bool)
  10. How PASETO middleware works

    main

    The PASETO middleware provides authentication by validating PASETO tokens in incoming requests.

    • Valid Token: The middleware sets the payload data in Ctx.Locals. If PassLocalsToContext is enabled in Fiber, it also sets the data in the underlying context.Context. It then calls the next handler.
    • Invalid Token: Returns a 401 - Unauthorized error.
    • Missing Token: Returns a 400 - BadRequest error.

    This middleware is compatible with Fiber v3.

  11. Configure Trusted Proxies for Coraza WAF

    main

    When running Coraza behind a reverse proxy (e.g., Nginx, Caddy, Traefik, Cloudflare), you must configure Fiber's trusted proxy settings correctly.

    Coraza rules often rely on REMOTE_ADDR. If trusted proxy validation is not configured, attackers can spoof forwarding headers to control the client IP value, potentially bypassing security rules.

  12. Security and Standards Compliance in JWT Middleware

    main

    The JWT middleware enforces several security standards based on RFCs to prevent common vulnerabilities:

    • Algorithm Pinning: The signing algorithm is determined by your configuration (SigningKey.JWTAlg), not the token itself. This prevents algorithm substitution attacks. You can also use jwt.WithValidMethods in ParserOptions to explicitly pin allowed algorithms.
    • Refusal of alg: none: The middleware refuses tokens with alg: none and ignores header parameters like jwk, jku, x5u, and x5c to prevent key injection. To explicitly allow alg: none (not recommended), set SigningKey.Key to jwt.UnsafeAllowNoneSignatureType.
    • Critical Header Check: It validates the crit header parameter per RFC 7515. Tokens with unknown critical parameters are rejected.
    • Claim Validation: exp (expiration) and nbf (not before) are validated by default. You can use jwt.WithLeeway, jwt.WithExpirationRequired, or jwt.WithNotBeforeRequired in ParserOptions to adjust this. Use jwt.WithoutClaimsValidation() to disable validation entirely.
    • Base64url Padding: By default, segments must be unpadded. Use jwt.WithPaddingAllowed() in ParserOptions to allow padded segments.