graphql

package
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 24, 2025 License: MIT Imports: 16 Imported by: 0

README

GraphQL Package

Overview

The graphql package provides utilities for working with GraphQL in Go services, including server configuration, error handling, and role-based access control (RBAC).

Features

  • GraphQL Server Configuration: Sensible defaults for GraphQL server setup
  • Error Handling: Proper context and logging for GraphQL errors
  • Role-Based Access Control: RBAC with the @isAuthorized directive
  • Metrics and Tracing: Performance monitoring for GraphQL operations
  • Timeout and Cancellation: Proper handling of timeouts and cancellations

Installation

go get github.com/abitofhelp/servicelib/graphql

Quick Start

See the Directive Registration example for a complete, runnable example of how to set up a GraphQL server with the @isAuthorized directive.

Configuration

See the Auth Configuration example for a complete, runnable example of how to configure the auth service for GraphQL.

API Documentation

Core Types
IsAuthorizedDirective

The IsAuthorizedDirective function implements the @isAuthorized directive for GraphQL, which can be used to restrict access to GraphQL operations based on user roles.

See the Directive Registration example for a complete, runnable example of how to use the IsAuthorizedDirective.

CheckAuthorization

The CheckAuthorization function is a helper for checking authorization in resolvers with roles, scopes, and resources.

See the Resolver Authorization example for a complete, runnable example of how to use the CheckAuthorization function.

Key Methods
IsAuthorizedWithScopes

The IsAuthorizedWithScopes function checks if a user has the required roles, scopes, and access to a resource.

See the Resolver Authorization example for a complete, runnable example of how to use the IsAuthorizedWithScopes function.

HasScope

The HasScope function checks if a user has a specific scope.

HasResource

The HasResource function checks if a user has access to a specific resource.

Examples

For complete, runnable examples, see the following files in the examples directory:

Best Practices

  1. Schema Design: Define clear Role, Scope, and Resource enums in your GraphQL schema.

  2. Directive Usage: Apply the @isAuthorized directive to all operations that require authorization.

  3. JWT Configuration: Configure the JWT authentication middleware to extract roles, scopes, and resources from tokens.

  4. Error Handling: Implement proper error handling for authorization failures.

  5. Testing: Generate test tokens with different roles, scopes, and resources to verify your authorization logic.

Troubleshooting

Common Issues
Authorization Failures

Issue: Users with valid tokens are not authorized to perform operations.

Solution: Check that the token contains the correct roles, scopes, and resources. Verify that the @isAuthorized directive is configured correctly.

Directive Registration Errors

Issue: Errors when registering the @isAuthorized directive.

Solution: Ensure that your GraphQL schema includes the Role, Scope, and Resource enums and the directive definition.

Performance Issues

Issue: Authorization checks are causing performance issues.

Solution: Use the provided metrics to identify bottlenecks. Consider caching authorization results for frequently accessed operations.

  • Auth - The auth component provides JWT authentication middleware used by the graphql package.
  • Middleware - The middleware component includes HTTP middleware for authentication and authorization.
  • Telemetry - The telemetry component provides metrics and tracing used by the graphql package.

Contributing

Contributions to this component are welcome! Please see the Contributing Guide for more information.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package graphql provides utilities for working with GraphQL.

Package graphql provides utilities for working with GraphQL.

Package graphql provides utilities for working with GraphQL.

Index

Constants

This section is empty.

Variables

View Source
var (
	// AuthorizationCheckDuration measures the duration of authorization checks
	AuthorizationCheckDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
		Name:    "authorization_check_duration_seconds",
		Help:    "Duration of authorization checks in seconds",
		Buckets: prometheus.DefBuckets,
	})

	// AuthorizationFailures counts the number of failed authorization attempts
	AuthorizationFailures = prometheus.NewCounter(prometheus.CounterOpts{
		Name: "authorization_failures_total",
		Help: "Total number of authorization failures",
	})
)

Functions

func CheckAuthorization

func CheckAuthorization(ctx context.Context, allowedRoles []string, requiredScopes []string, resource string, operation string, logger *logging.ContextLogger) error

CheckAuthorization is a helper function to check if the user is authorized to perform an operation It can be used in resolvers to perform custom authorization checks

Parameters:

  • ctx: The context of the request
  • allowedRoles: The roles that are allowed to perform the operation
  • requiredScopes: The scopes that are required to perform the operation (optional)
  • resource: The resource being accessed (optional)
  • operation: The name of the operation being performed
  • logger: A context logger for logging (optional, can be nil)

Returns:

  • An error if not authorized, nil if authorized

func ConvertRolesToStrings

func ConvertRolesToStrings[T fmt.Stringer](roles []T) []string

ConvertRolesToStrings converts a slice of enum roles to a slice of strings This is useful when working with generated enum types for roles

Parameters:

  • roles: A slice of role enums that have a String() method

Returns:

  • A slice of strings representing the roles

func HandleError

func HandleError(ctx context.Context, err error, operation string, logger *logging.ContextLogger) error

HandleError processes an error and returns an appropriate GraphQL error. It logs the error and converts it to a GraphQL error with appropriate extensions. Parameters:

  • ctx: The context containing trace information
  • err: The error to handle
  • operation: The name of the operation that caused the error
  • logger: The logger to use for logging the error

Returns:

  • error: A GraphQL error with appropriate extensions

func IsAuthorizedDirective

func IsAuthorizedDirective(ctx context.Context, obj interface{}, next graphql.Resolver, allowedRoles []string, requiredScopes []string, resource string, logger *logging.ContextLogger) (interface{}, error)

IsAuthorizedDirective implements the @isAuthorized directive for GraphQL It checks if the user has any of the allowed roles and all of the required scopes for the specified resource

Parameters:

  • ctx: The context of the request
  • obj: The object being resolved
  • next: The next resolver in the chain
  • allowedRoles: The roles that are allowed to access this field
  • requiredScopes: The scopes that are required to access this field (optional)
  • resource: The resource being accessed (optional)
  • logger: A context logger for logging (optional, can be nil)

Returns:

  • The result of the next resolver if authorized
  • An error if not authorized

func NewServer

func NewServer(schema graphql.ExecutableSchema, logger *logging.ContextLogger, cfg ServerConfig) *handler.Server

NewServer creates a new GraphQL server with the given schema and configuration

Types

type ServerConfig

type ServerConfig struct {
	MaxQueryDepth      int
	MaxQueryComplexity int
	RequestTimeout     time.Duration
}

ServerConfig contains configuration for the GraphQL server

func DefaultServerConfig added in v1.5.0

func DefaultServerConfig() ServerConfig

DefaultServerConfig returns a default configuration for the GraphQL server. This is an alias for NewDefaultServerConfig for compatibility with the configscan tool.

func NewDefaultServerConfig

func NewDefaultServerConfig() ServerConfig

NewDefaultServerConfig creates a new server configuration with default values

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL