net

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2024 License: MPL-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const KeyApiAction = "action"

Variables

View Source
var ErrNotFound = errors.New("not found")
View Source
var ErrUnauthorized = errors.New("unauthorized")

Functions

func CreateMtlsClient

func CreateMtlsClient(
	source *workloadapi.X509Source,
	predicate func(string) bool,
) (*http.Client, error)

TODO: document.

func CreateMtlsServer

func CreateMtlsServer(source *workloadapi.X509Source,
	tlsPort string,
	predicate func(string) bool) (*http.Server, error)

CreateMtlsServer creates an HTTP server configured for mutual TLS (mTLS) authentication using SPIFFE X.509 certificates. It sets up the server with a custom authorizer that validates client SPIFFE IDs against a provided predicate function.

Parameters:

  • source: An X509Source that provides the server's identity credentials and validates client certificates. It must be initialized and valid.
  • tlsPort: The network address and port for the server to listen on (e.g., ":8443").
  • predicate: A function that takes a SPIFFE ID string and returns true if the client should be allowed access, false otherwise.

Returns:

  • *http.Server: A configured HTTP server ready to be started with TLS enabled.
  • error: An error if the server configuration fails.

The server uses the provided X509Source for both its own identity and for validating client certificates. Client connections are only accepted if their SPIFFE ID passes the provided predicate function.

func Fallback added in v0.2.0

func Fallback(
	w http.ResponseWriter, r *http.Request, audit *log.AuditEntry,
) error

Fallback handles requests to undefined routes by returning a 400 Bad Request.

This function serves as a catch-all handler for undefined routes, logging the request details and returning a standardized error response. It uses MarshalBody to generate the response and handles any errors during response writing.

Parameters:

  • w: http.ResponseWriter - The response writer
  • r: *http.Request - The incoming request

The response always includes:

  • Status: 400 Bad Request
  • Content-Type: application/json
  • Body: JSON object with an error field

func HandleRequest added in v0.2.0

func HandleRequest[Req any, Res any](
	requestBody []byte,
	w http.ResponseWriter,
	errorResponse Res,
) *Req

HandleRequest unmarshals a JSON request body into a typed request struct.

This is a generic function that handles the common pattern of unmarshaling and validating incoming JSON requests. If unmarshaling fails, it sends the provided error response to the client with a 400 Bad Request status.

Type Parameters:

  • Req: The request type to unmarshal into
  • Res: The response type for error cases

Parameters:

  • requestBody: []byte - The raw JSON request body to unmarshal
  • w: http.ResponseWriter - The response writer for error handling
  • errorResponse: Res - A response object to send if unmarshaling fails

Returns:

  • *Req - A pointer to the unmarshaled request struct, or nil if unmarshaling failed

The function handles all error logging and response writing for the error case. Callers should check if the returned pointer is nil before proceeding.

func HandleRequestError

func HandleRequestError(w http.ResponseWriter, err error) error

HandleRequestError handles HTTP request errors by writing a 400 Bad Request status to the response writer. If err is nil, it returns nil. Otherwise, it writes the error status and returns a joined error containing both the original error and any error encountered while writing the response.

func HandleRoute added in v0.2.0

func HandleRoute(h Handler)

HandleRoute wraps an HTTP handler with audit logging functionality. It creates and manages audit log entries for the request lifecycle, including: - Generating unique trail IDs - Recording timestamps and durations - Tracking request status (created, success, error) - Capturing error information

The wrapped handler is mounted at the root path ("/") and automatically logs entry and exit audit events for all requests.

Parameters:

  • h: Handler function to wrap with audit logging

func MarshalBody added in v0.2.0

func MarshalBody(res any, w http.ResponseWriter) []byte

MarshalBody serializes a response object to JSON and handles error cases.

This function attempts to marshal the provided response object to JSON bytes. If marshaling fails, it sends a 500 Internal Server Error response to the client and returns nil. The function handles all error logging and response writing for the error case.

Parameters:

  • res: any - The response object to marshal to JSON
  • w: http.ResponseWriter - The response writer for error handling

Returns:

  • []byte - The marshaled JSON bytes, or nil if marshaling failed

func Post

func Post(client *http.Client, path string, mr []byte) ([]byte, error)

Post performs an HTTP POST request with a JSON payload and returns the response body. It handles the common cases of connection errors, non-200 status codes, and proper response body handling.

Parameters:

  • client: An *http.Client used to make the request, typically configured with TLS settings.
  • path: The URL path to send the POST request to.
  • mr: A byte slice containing the marshaled JSON request body.

Returns:

  • []byte: The response body if the request is successful.
  • error: An error if any of the following occur:
  • Connection failure during POST request
  • Non-200 status code in response
  • Failure to read response body
  • Failure to close response body

The function ensures proper cleanup by always attempting to close the response body, even if an error occurs during reading. Any error from closing the body is joined with any existing error using errors.Join.

Example:

client := &http.Client{}
data := []byte(`{"key": "value"}`)
response, err := Post(client, "https://api.example.com/endpoint", data)
if err != nil {
    log.Fatalf("failed to post: %v", err)
}

func ReadRequestBody

func ReadRequestBody(w http.ResponseWriter, r *http.Request) []byte

ReadRequestBody reads the entire request body from an HTTP request. It returns the body as a byte slice if successful. If there is an error reading the body or if the body is nil, it writes a 400 Bad Request status to the response writer and returns an empty byte slice. Any errors encountered are logged.

func Respond added in v0.2.0

func Respond(statusCode int, body []byte, w http.ResponseWriter)

Respond writes a JSON response with the specified status code and body.

This function sets the Content-Type header to application/json, writes the provided status code, and sends the response body. Any errors during writing are logged but not returned to the caller.

Parameters:

  • statusCode: int - The HTTP status code to send
  • body: []byte - The pre-marshaled JSON response body
  • w: http.ResponseWriter - The response writer to use

func Serve

func Serve(source *workloadapi.X509Source,
	initializeRoutes func(),
	predicate func(string) bool,
	tlsPort string) error

Serve initializes and starts an HTTPS server using mTLS authentication with SPIFFE X.509 certificates. It sets up the server routes using the provided initialization function and listens for incoming connections on the specified port.

Parameters:

  • source: An X509Source that provides the server's identity credentials and validates client certificates. Must not be nil.
  • initializeRoutes: A function that sets up the HTTP route handlers for the server. This function is called before the server starts.
  • tlsPort: The network address and port for the server to listen on (e.g., ":8443").

Returns:

  • error: Returns nil if the server starts successfully, otherwise returns an error explaining the failure. Specific error cases include:
  • If source is nil
  • If server creation fails
  • If the server fails to start or encounters an error while running

The function uses empty strings for the certificate and key file parameters in ListenAndServeTLS as the certificates are provided by the X509Source. The server's mTLS configuration is determined by the CreateMtlsServer function.

Types

type ApiUrl added in v0.2.0

type ApiUrl string
const SpikeKeeperUrlKeep ApiUrl = "/v1/store/keep"
const SpikeNexusUrlInit ApiUrl = "/v1/auth/init"
const SpikeNexusUrlLogin ApiUrl = "/v1/auth/login"
const SpikeNexusUrlSecrets ApiUrl = "/v1/store/secrets"

type Handler added in v0.2.0

Handler is a function type that processes HTTP requests with audit logging support.

func RouteFactory added in v0.2.0

func RouteFactory[ApiAction any](p ApiUrl, a ApiAction, m string,
	switchyard func(a ApiAction, p ApiUrl) Handler) Handler

RouteFactory creates HTTP route handlers for API endpoints using a generic switching function. It enforces POST-only methods per ADR-0012 and logs route creation details.

Type Parameters:

  • ApiAction: Type representing the API action to be handled

Parameters:

  • p: API URL for the route
  • a: API action instance
  • m: HTTP method
  • switchyard: Function that returns appropriate handler based on action and URL

Returns:

  • Handler: Route handler function or Fallback for non-POST methods

type SpikeKeeperApiAction added in v0.2.0

type SpikeKeeperApiAction string
const ActionKeeperDefault SpikeKeeperApiAction = ""
const ActionKeeperRead SpikeKeeperApiAction = "read"

type SpikeNexusApiAction added in v0.2.0

type SpikeNexusApiAction string
const ActionNexusAdminLogin SpikeNexusApiAction = "admin-login"
const ActionNexusCheck SpikeNexusApiAction = "check"
const ActionNexusDefault SpikeNexusApiAction = ""
const ActionNexusDelete SpikeNexusApiAction = "delete"
const ActionNexusGet SpikeNexusApiAction = "get"
const ActionNexusList SpikeNexusApiAction = "list"
const ActionNexusUndelete SpikeNexusApiAction = "undelete"

Jump to

Keyboard shortcuts

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