secret

package
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: May 26, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AccessHandlerError = "API_SECRET_ACCESS_HANDLER_ERROR"
	AccessHandlerName  = "API_SECRET_MIDDLEWARE"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Provider

type Provider[T goservectx.Principal] interface {

	// GetPublicKey (ctx *context.Request[T]) (string, error):
	//	   Fetches the API secret key for the given request context. The method should implement
	//	   any necessary logic to securely retrieve and provide the key, such as decryption or
	//	   validation.
	//
	// Example Use Case:
	// When processing an API request that requires validation with a secret key, the implementation
	// of this interface can retrieve and provide the appropriate key tailored to the request's context.
	//
	// Returns:
	//   - A string representing the API secret key.
	//   - An error if the key retrieval or processing fails, ensuring proper error handling in the
	//	 request lifecycle.
	GetPublicKey(ctx *goservectx.Request[T]) (string, error)

	// GetJwtEntry generates the jwt.Entry for the given ApiKeyEntryData and Request.
	// This method is responsible for processing the API key entry data and request context to create an ApiJWTInfo object,
	// which contains essential JWT-related information such as the client, key, and expiration details.
	//
	// Parameters:
	//   - apiKeyEntryData: An instance of ApiKeyEntryData that includes client details, expiration duration, and unique client identifier.
	//   - ctx: The API request context, which contains metadata and principal information related to the API key generation process.
	//
	// Returns:
	//   - jwt.Entry: The generated ApiJWTInfo object containing JWT details necessary for creating the API secret JWT.
	//   - error: If an error occurs during the process, it returns the corresponding error; otherwise, nil.
	GetJwtEntry(apiKeyEntryData model.ApiKeyEntryData, ctx *goservectx.Request[T]) (model.Entry, error)

	// OnGenerated is invoked after an API key has been successfully generated.
	// This function allows additional processing or handling, such as logging,
	// auditing, or notifying dependent systems of the newly generated API key.
	//
	// Parameters:
	//   - response: The generated token as jwt.Response.
	//   - jwtEntry: The requested jwt.Entry.
	//   - ctx: The API request context, containing metadata and principal
	//		  information related to the API key generation.
	OnGenerated(response goservejwt.Response, jwtEntry model.Entry, ctx goservectx.SampleContext[T])

	// RequiredScopes returns a list of scopes that are mandatory for accessing the related end point
	// resources registered by invoking server.Api SecretService method.
	RequiredScopes() []string
}

Provider is an interface designed to provide secure access to API secret keys based on the context of an incoming API request.

This interface plays a crucial role in enabling secure communication and access control by retrieving API keys that are specific to each request. It abstracts the mechanism for obtaining these keys, which could involve fetching from a database, a configuration file, or any other secure storage mechanism.

Type Parameters:

  • T: A type that satisfies the `context.Principal` interface, representing the authentication and authorization context for API requests.

type Service

type Service[T goservectx.Principal] interface {
	security.Service[T]
	Provider[T]

	// HandlerSecretAccess is the core function of the Service interface that is responsible for
	// validating API secret keys to ensure secure access to API resources.
	//
	// This method enforces access security by leveraging the following mechanisms:
	//   - Validates the API key against the stored private key to confirm its authenticity.
	//   - Handles any errors that occur during the validation process, responding with appropriate
	//	 HTTP status codes and error messages if validation fails.
	//
	// The function works as follows:
	//   1. Calls the `ApiSecretKeyValidation` method to validate the API key and public/private key pair.
	//   2. If the validation fails, invokes the `handlerErrorOrElse` method from the Service to handle
	//	  the failure, typically responding with `http.StatusUnauthorized`.
	//   3. If validation is successful, allows the request to proceed by returning `true`.
	//
	// Args:
	//   - ctx (*context.Request[T]): The context of the incoming API request that carries
	//	 all necessary information for validation, such as JWT claims and keys.
	//
	// Returns:
	//   - bool: `true` if the API key is valid and access is granted; `false` otherwise.
	HandlerSecretAccess(ctx *goservectx.Request[T]) bool

	// DisableForPublicPath sets whether validation should be skipped for public API paths.
	//
	// This method allows configuring the API secret handler to bypass validation for requests
	// targeting public endpoints. When enabled, security mechanisms such as API key validation
	// may not be enforced on these paths, allowing unauthenticated access as needed.
	//
	// Args:
	//   - ignore (bool): A flag indicating whether to ignore validation for public paths.
	//	 Set to `true` to skip validation; set to `false` to enforce validation.
	DisableForPublicPath(ignore bool) Service[T]

	// Handler processes API key generation requests and returns a JWT response.
	// It validates the API key entry data, generates a public key if not present, creates
	// the JWT, and sends the response back to the client.
	//
	// Parameters:
	//   - ctx: The request context which includes request-related metadata and the ability to send responses.
	//   - apiKeyEntryData: The API key entry data which contains information such as client name, expiration duration,
	//	 and a unique client ID.
	//
	// Behavior:
	//   - Logs the API key generation request.
	//   - Retrieves JWT entry information based on the provided API key data.
	//   - If the public key is missing, generates a public key for the request.
	//   - Constructs the JWT token with roles and expiration information.
	//   - Sends the generated JWT as a response to the client.
	//   - Logs and sends an internal server error response if any operation fails.
	//
	// Errors:
	//   - If any step fails (e.g., JWT generation, public key retrieval), the function logs the error and
	//	 responds with an internal server error to the client.
	Handler(ctx *goservectx.Request[T], body model.ApiKeyEntryData)

	// SecretKey returns the current API secret key used for cryptographic operations and token generation.
	SecretKey() string

	// InitAPISecretKey initializes the API secret key by reading and parsing a private key file.
	//
	// This function performs the following steps:
	// - Reads the private key file specified by the `secretKey` field.
	// - Decodes the PEM block from the file data.
	// - Parses the private key from the PEM data using PKCS8 format.
	// - Validates the type of the private key (either ECDSA or RSA).
	// - Stores the private key in the `apiSecret` field of the `apiSecretHandlerImpl` struct.
	//
	// Logs an error and terminates the application if any of the above steps fail.
	InitAPISecretKey()

	// ApiSecretKeyValidation verifies the validity of a public key against the private key stored in the handler.
	//
	// This function performs the following steps:
	// - Extracts JWT claims from the request context using the Service.
	// - Loads the API secret using the provided `ApiSecretKeyServiceProvider`.
	// - Decrypts the API access key to retrieve the PEM-encoded public key.
	// - Decodes the PEM-encoded public key and parses it into a usable public key object.
	// - Validates the type of the parsed public key (ECDSA or RSA).
	// - Ensures the extracted public key corresponds to the private key stored in the `apiSecret` field.
	//
	// If any of the above steps fail, the function logs the error and returns `false`, indicating that
	// the public key validation has failed. Otherwise, it returns `true`.
	//
	// Args:
	//
	//	  ctx (*api_context.Request[T]):
	//		 - The context of the API request carrying the necessary data for validation.
	//
	// Returns:
	//
	//	  bool:
	//		 - `true` if the public key is valid and corresponds to the private key.
	//		 - `false` if the public key is invalid or the validation fails.
	ApiSecretKeyValidation(ctx *goservectx.Request[T]) bool

	// GeneratePubKey generates an encrypted public key from a given private key file.
	//
	// This function performs the following steps:
	// - Reads the private key from the specified file path.
	// - Decodes the PEM block from the private key data.
	// - Parses the private key using the PKCS8 format.
	// - Determines the type of the private key (ECDSA or RSA).
	// - Marshals the corresponding public key into PEM format.
	// - Encrypts the generated PEM-encoded public key using the securityService's encryption logic.
	//
	// Arguments:
	//   - secretKey (string): The file path to the private key.
	//
	// Returns:
	//   - (string, error): An encrypted PEM-encoded public key and an error (if any occurred).
	//
	// Errors:
	//   - Fails if the private key file cannot be read, parsed, or if the key type is unsupported.
	//   - Fails if the public key cannot be marshaled or encrypted.
	//
	// Example:
	//
	//	 encryptedPubKey, err := handler.generatePubKey("path/to/private.key")
	//	 if err != nil {
	//		 log.Printf("Error generating public key: %v", err)
	//	 }
	GeneratePubKey(secretKey string) (string, error)
}

func New

func New[T goservectx.Principal](
	provider Provider[T],
	service security.Service[T],
) Service[T]

New creates and initializes a new instance of Service interface implementation, which handles security-related operations for API requests, such as validating API keys and initializing cryptographic keys. It encapsulates the logic necessary for validating API secret keys, restricting unauthorized resource access, and managing cryptographic operations.

Type Parameters:

  • T: A type that satisfies the `goservectx.Principal` interface, representing the API request's security context.

Parameters:

  • provider: An implementation of the Provider interface responsible for managing API secrets and key-related operations.
  • service: An implementation of the security.Service interface for cryptographic and validation-related services.

Returns:

  • An instance of the Service interface, initialized and ready to perform security operations.

Notes:

  • The function retrieves the API private key from the "API_PRIVATE_KEY" environment variable.
  • It terminates the application if the private key is not set or fails to initialize properly.

Jump to

Keyboard shortcuts

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