tkPresentation

package
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 22 Imported by: 17

README

Presentation

Presentation layer of Infinite Toolkit (TK). It parses untrusted input, wraps responses, and provides Echo middleware. It depends on infra and domain. Part of Infinite Toolkit.

Middleware

  • PanicHandler: Handle panics in HTTP requests, log filtered stack traces (excluding domain layers), and respond with error messages; uses TRUSTED_IPS and TRUSTED_CIDRS env vars to mask sensitive information from untrusted operators. It can be used with CLI applications as well. The trust check uses the extracted requester IP. When the whole chain is trusted, that IP is the original requester as recorded by the first proxy. A client on the trusted network can claim another trusted IP by sending its own X-Forwarded-For. Overwrite the header at the proxy to prevent this.

    // ForApiInitialization
    echoInstance.Use(ApiPanicHandler)
    
    // ForCliInitialization
    defer CliPanicHandler()
    
  • LogHandler: Configure logging levels via LOG_LEVEL environment variable and initialize structured logging with slog and Zerolog.

Helpers

  • RequiredParamsInspector: Check that every required parameter is present in a request input map before further parsing.

    paramsReceived := map[string]any{"name": "John", "age": 30}
    paramsRequired := []string{"name", "email"}
    requiredParamsValidationErr := RequiredParamsInspector(paramsReceived, paramsRequired)
    
  • ApiRequestInputReader: Read and parse JSON, form data, or multipart files from Echo HTTP requests into structured data. Uploaded files are grouped under the files key by form field: requestBody["files"] is a map[string][]*multipart.FileHeader, one key per field, each slice in upload order. A request with no files carries no files key.

    inputReader := ApiRequestInputReader{}
    requestData, requestParsingErr := inputReader.Reader(echoContext)
    
  • RequesterIpExtractor: Requester IP extraction with a peer trust gate and a right-to-left trust chain walk. Reads IP_EXTRACT_HEADER env var as a comma-separated ordered chain (default: X-Forwarded-For,X-Real-IP). When RemoteAddr is not a trusted IP (local, private, link-local, or in TRUSTED_IPS/TRUSTED_CIDRS), the extractor returns it and ignores the headers, because the client connected directly. Otherwise each header is walked right-to-left; malformed entries are ignored, and the first entry that is not a trusted IP is returned. When every entry is trusted, the extractor returns the original requester, the first entry of the first header that has one. This matches Echo's RealIP semantics. Otherwise it returns RemoteAddr. The chain supports the special keywords Direct and RemoteAddr to force extraction from http.Request.RemoteAddr.

    IP_EXTRACT_CONFIRMATION_HEADERS adds an optional confirmation gate:

    • The value is a comma-separated list of header names.
    • A bare HeaderName, or HeaderName= with an empty value, requires presence.
    • HeaderName=secret requires a constant-time value match.
    • All entries must use the same mode; a mixed list is invalid.
    • The gate passes when at least one requirement passes.
    • A missing header, wrong value, mixed list, or invalid name/value returns RemoteAddr.
    • Whitespace around entries, names, and values is trimmed.
    • Confirmation header names and values are not logged.
    • Unset or empty preserves the current behavior.

    Example: a request arrives with X-Forwarded-For: 127.0.0.1 and RemoteAddr: 172.17.0.1:54321. Both addresses are trusted, so the extractor returns 127.0.0.1, not the proxy address.

    Security: The headers are read only from trusted peers: loopback, private, link-local, or in TRUSTED_IPS/TRUSTED_CIDRS. A client on an untrusted network cannot choose the reported address. Right-to-left traversal skips values a client prepends when a trusted proxy appends the real client last. A proxy with a public address must be listed in TRUSTED_CIDRS, or the extractor reports the proxy address. Over-broad TRUSTED_CIDRS is the risk: the extractor would trust a range that includes untrusted clients. Behind an L4 proxy that cannot overwrite headers, set IP_EXTRACT_CONFIRMATION_HEADERS so requests that bypass the edge fail closed. Presence alone is forgeable; use HeaderName=secret when the origin is directly reachable.

    Proxy entries: Do not add a private/internal proxy range to TRUSTED_IPS or TRUSTED_CIDRS unless you intend that proxy to be a trusted panic operator. The extractor already trusts loopback, private, and link-local peers, so the entry does not change header trust. It does make PanicHandler trust the proxy address: when the confirmation gate fails, Execute returns the proxy's RemoteAddr, and a listed proxy then unlocks full panic details. A public proxy must be listed for header extraction. If you also configure the confirmation gate, make sure it passes on that path, or a failed gate will return the proxy address and treat it as a trusted operator.

    extractor := NewRequesterIpExtractor()
    
    ipAddress, err := extractor.Execute(httpRequest)
    
  • EnvsInspector: Inspect and validate environment variables from .env files loaded via ENV_FILE_PATH env var, supporting required and auto-fillable variables.

    optionalEnvFilePath := "/path/to/.env"
    requiredEnvVarNames := []string{"TRAIL_DATABASE_FILE_PATH", "SESSION_TOKEN_SECRET"}
    autoFillableEnvVars := []string{"SESSION_TOKEN_SECRET"}
    envsInspector := NewEnvsInspector(
      optionalEnvFilePath, requiredEnvVarNames, autoFillableEnvVars,
    )
    envsValidationErr := envsInspector.Inspect()
    
  • PaginationDtoParser: Parse pagination parameters like pageNumber, itemsPerPage, lastSeenId, sortBy, and sortDirection from HTTP requests into a tkDto.Pagination. A zero itemsPerPage fails with InvalidItemsPerPage; a fractional pageNumber or itemsPerPage fails with InvalidPageNumber or InvalidItemsPerPage.

    defaultPagination := tkDto.Pagination{PageNumber: 0, ItemsPerPage: 10}
    untrustedInput := map[string]any{"pageNumber": 1, "itemsPerPage": 20}
    parsedPagination, paginationParsingErr := PaginationDtoParser(
      defaultPagination, untrustedInput,
    )
    
  • PaginationQueryParamsInputReader: Read pagination query params and caller-listed optional params from an Echo context into the untrusted input map that PaginationDtoParser consumes. It reads pageNumber, itemsPerPage, sortBy, sortDirection, and lastSeenId. A pagination value enters the map only when its tk conversion succeeds, so a malformed value stays out and PaginationDtoParser returns the default. A zero itemsPerPage is dropped. Optional params enter the map when present and non-empty, with no conversion; a pagination key listed among them is ignored, so the converted value stands. The reader writes no defaults; the liaison owns them through PaginationDtoParser.

    optionalParamNames := []string{"nature", "name", "type", "status"}
    untrustedInput := tkPresentation.PaginationQueryParamsInputReader(
      echoContext, optionalParamNames,
    )
    
  • UiRequestInputReader: Read DataTable/Carousel fragment query params into the liaison input map. It reads configured filters by Key and QueryParamName, with scalar, multi-select, and range kinds; range filters use Min/Max suffixes and return {min, max}. It composes PaginationQueryParamsInputReader for the unprefixed pagination keys, copies BaseInput shallowly, and injects operatorAccountId, operatorSri, and operatorIpAddress from the Echo context after reading query params. The fragment route identifies the component, so there is no component prefix. A missing or wrong-type operator account ID fails with OperatorAccountIdNotFound; query-supplied operator fields are overwritten. When operatorIpAddress is absent from the Echo context, the reader extracts the requester IP from the request and fails with InvalidOperatorIpAddress if extraction fails. Pagination defaults stay with the liaison factory.

    reader := tkPresentation.UiRequestInputReader{
      Filters: []tkPresentation.UiQueryParamFilter{
        {Key: "status"},
        {
          Key:            "tags",
          QueryParamName: "tag",
          Kind:           tkPresentation.UiQueryParamFilterKindMulti,
        },
        {
          Key:            "cpu",
          QueryParamName: "cores",
          Kind:           tkPresentation.UiQueryParamFilterKindRange,
        },
      },
      BaseInput: map[string]any{"withMetrics": true},
    }
    input, readingErr := reader.Read(echoContext)
    

    Map DataTable/Carousel kinds to the reader kinds: text and enum filters are scalar, multi-enum filters are multi, and number/date ranges are range. Add a scalar filter for the search placeholder when the table has a search box. The QueryUrlTemplate must map {sortKey} to sortBy for the pagination reader. Filters and pagination override BaseInput; operator fields always win.

  • ParseFieldMatchPatterns: Parse a semicolon-separated list of field:pattern pairs into a map keyed by QueryFieldName. Each entry is trimmed. An empty pattern after the colon defaults to equals. Field names keep their case. A missing colon fails with InvalidFieldMatchPattern; an invalid field name returns the QueryFieldName constructor error (QueryFieldNameCannotBeEmpty, QueryFieldNameTooBig, or InvalidQueryFieldName); an input that cannot convert to a string fails with FieldMatchPatternsMustBeString.

    fieldMatchPatterns, parsingErr := ParseFieldMatchPatterns(
      "name:contains;status:equals",
    )
    
  • StringSliceVoParser: Convert comma-separated, semicolon-separated, or array strings into value object slices.

    rawInput := "note1,note2;note3"
    parsedNotes := StringSliceValueObjectParser(rawInput, tkValueObject.NewGenericNotes)
    
  • TimeParamsParser: Parse date ranges, timestamps, and relative times from request parameters.

    timeParamNames := []string{"createdAt", "updatedAt"}
    untrustedInput := map[string]any{"createdAt": 1609459200}
    parsedTimeParams := TimeParamsParser(timeParamNames, untrustedInput)
    fmt.Println(parsedTimeParams["createdAt"])
    
  • LiaisonResponder: Build liaison responses with the outcome already set. Create it once with map[error]LiaisonResponseStatus and inject it into liaisons. Success, Created, Accepted, and MultiStatus build success responses. InputError builds a UserError response for invalid request input. AppError maps a use-case error through errors.Is; a match uses the mapped status and the matched sentinel's message in both Body and ReadableMessage, while an unmapped, ambiguous, or success-mapped error uses UnknownError with InternalServerError and logs the cause. Use-case sentinels are the public error contract; the use case hides infra errors behind them. The API emitter, CLI renderer, and downstream UI presenters only translate LiaisonResponseStatus to their own transport. The responder logs mapping failures and mapped server errors without request context; API handlers that need request-scoped logging should log 5xx responses at the Echo boundary.

    responder := NewLiaisonResponder(
        map[error]LiaisonResponseStatus{
            errRecordNotFound: LiaisonResponseStatusNotFound,
        },
    )
    
    func (liaison *X) Do(input map[string]any) LiaisonResponse {
        username, err := valueObject.NewUsername(input["username"])
        if err != nil {
            return liaison.responder.InputError(err.Error())
        }
    
        result, err := useCase.Execute(...)
        if err != nil {
            return liaison.responder.AppError(err)
        }
    
        return liaison.responder.Success(result, "OperationCompleted")
    }
    
  • ResponseWrapper: The API and CLI response types and emitters. ApiResponseWrapper is the standard HTTP envelope. LiaisonApiResponseEmitter maps a LiaisonResponse to its HTTP status and writes the envelope; LiaisonCliResponseRenderer writes the CLI JSON and exits with the mapped code.

    apiResponse := NewApiResponseWrapper(201, accountEntity, "AccountCreatedSuccessfully")
    
    liaisonResponse := responder.Success(accountEntity, "AccountRetrievedSuccessfully")
    
    liaisonApiEmissionErr := LiaisonApiResponseEmitter(echoContext, liaisonResponse)
    
    LiaisonCliResponseRenderer(liaisonResponse)
    

Documentation

Index

Constants

View Source
const (
	EnvsInspectorEnvFilePathEnvVarName string = "ENV_FILE_PATH"
)

Variables

View Source
var ErrEnvsInspectorEnvLoad = errors.New("InvalidEnvFileContent")

Functions

func LiaisonApiResponseEmitter added in v0.1.1

func LiaisonApiResponseEmitter(
	echoContext echo.Context,
	liaisonResponse LiaisonResponse,
) error

func LiaisonCliResponseRenderer added in v0.1.1

func LiaisonCliResponseRenderer(liaisonResponse LiaisonResponse)

func PaginationDtoParser added in v0.4.4

func PaginationDtoParser(
	defaultPagination tkDto.Pagination,
	untrustedInput map[string]any,
) (parsedPagination tkDto.Pagination, err error)

func PaginationQueryParamsInputReader added in v0.4.4

func PaginationQueryParamsInputReader(
	echoContext echo.Context, optionalParamNames []string,
) map[string]any

func ParseFieldMatchPatterns added in v0.4.4

func ParseFieldMatchPatterns(input any) (
	fieldNameMatchPatternsMap map[tkValueObject.QueryFieldName]tkValueObject.MatchPattern,
	err error,
)

func RequiredParamsInspector added in v0.0.4

func RequiredParamsInspector(paramsReceived map[string]any, paramsRequired []string) error

func SimpleCliResponseRenderer added in v0.2.3

func SimpleCliResponseRenderer(
	isSuccess bool, message string,
)

func StringSliceValueObjectParser

func StringSliceValueObjectParser[TypedObject any](
	rawInputValues any,
	valueObjectConstructor func(any) (TypedObject, error),
) []TypedObject

StringSliceValueObjectParser converts various input formats into a slice of typed objects. It accepts: - nil (returns empty slice) - string (splits by ";" or "," and parses each element) - slice (parses each element) - single value (parses as one element)

The valueObjectConstructor function is used to convert each raw value into the desired type. Invalid values are logged and skipped.

func TimeParamsParser added in v0.1.1

func TimeParamsParser(
	timeParamNames []string,
	untrustedInput map[string]any,
) map[string]*tkValueObject.UnixTime

This function parses time parameters from untrusted input. Time parameters are almost always optional, so it returns a map of pointers to tkValueObject.UnixTime. This allows the caller to easily determine if a time parameter was provided by checking if the pointer is nil. The parsed time parameters can then be directly set in a DTO.

Types

type ApiRequestInputReader added in v0.1.2

type ApiRequestInputReader struct {
}

func (ApiRequestInputReader) FormUrlEncodedDataProcessor added in v0.1.2

func (reader ApiRequestInputReader) FormUrlEncodedDataProcessor(
	requestBody map[string]any, formData map[string][]string,
) map[string]any

func (ApiRequestInputReader) Reader added in v0.1.2

func (reader ApiRequestInputReader) Reader(echoContext echo.Context) (map[string]any, error)

ApiRequestInputReader.Reader extracts and normalizes input data from an HTTP request into a flat map[string]any.

It processes the request body based on Content-Type, merges query parameters, path parameters, and optionally includes operator context information.

Content-Type handling:

  • application/json: Parses JSON body directly into the map. Returns "InvalidJsonBody" error if JSON is malformed.
  • application/x-www-form-urlencoded: Processes form data, preserving multiple values as string slices when a key appears more than once. Supports dot notation for nested structures (e.g., "user.name" becomes map["user"]["name"]).
  • multipart/form-data: Processes form fields similar to URL-encoded data. File uploads are grouped under the "files" key by form field, each field holding its files in upload order. Returns "InvalidMultipartFormData" error if the multipart form cannot be parsed.
  • Other/missing Content-Type: Returns "InvalidContentType" error.

Query parameters:

  • Query parameters are merged into the result map. When a query parameter has multiple values (e.g., ?tags=tag1&tags=tag2), only the FIRST value is captured. This is a design decision to optimize for the common single-value case (~99% of use cases).
  • For the rare cases where multiple values are needed, use a delimiter at the controller level. For example: ?tags=tag1;tag2 and split on ";" in your controller logic.

Route Path parameters:

  • All Echo route path parameters (e.g., :id, :name) are merged into the result map.

Operator context (if present in Echo context):

  • operatorSri: Extracted from context key and included in the result map.
  • operatorAccountId: Extracted from context key and included in the result map.
  • operatorIpAddress: If missing, populated using NewRequesterIpExtractor().Execute().

Returns:

  • A map[string]any containing all extracted request data, or
  • An echo.HTTPError with status 400 (Bad Request) and a descriptive message if parsing fails.

func (ApiRequestInputReader) StringDotNotationToHierarchicalMap added in v0.1.2

func (reader ApiRequestInputReader) StringDotNotationToHierarchicalMap(
	hierarchicalMap map[string]any, remainingKeys []string, finalValue string,
) map[string]any

type ApiResponseWrapper added in v0.1.1

type ApiResponseWrapper struct {
	Status          int    `json:"status"`
	Body            any    `json:"body"`
	ReadableMessage string `json:"readableMessage"`
}

func NewApiResponseWrapper added in v0.1.1

func NewApiResponseWrapper(
	status int,
	body any,
	readableMessage string,
) ApiResponseWrapper

type EnvsInspector added in v0.1.0

type EnvsInspector struct {
	// contains filtered or unexported fields
}

func NewEnvsInspector added in v0.1.0

func NewEnvsInspector(
	envFilePath *tkValueObject.UnixAbsoluteFilePath,
	requiredEnvVars, autoFillableEnvVars []string,
) *EnvsInspector

func (*EnvsInspector) Inspect added in v0.1.0

func (envsInspector *EnvsInspector) Inspect() (err error)

type LiaisonResponder added in v0.4.5

type LiaisonResponder struct {
	// contains filtered or unexported fields
}

func NewLiaisonResponder added in v0.4.5

func NewLiaisonResponder(
	errorStatusesMap map[error]LiaisonResponseStatus,
) LiaisonResponder

func (LiaisonResponder) Accepted added in v0.4.5

func (responder LiaisonResponder) Accepted(
	body any, readableMessage string,
) LiaisonResponse

func (LiaisonResponder) AppError added in v0.4.5

func (responder LiaisonResponder) AppError(
	appErr error,
) LiaisonResponse

func (LiaisonResponder) Created added in v0.4.5

func (responder LiaisonResponder) Created(
	body any, readableMessage string,
) LiaisonResponse

func (LiaisonResponder) InputError added in v0.4.5

func (responder LiaisonResponder) InputError(
	message string,
) LiaisonResponse

func (LiaisonResponder) MultiStatus added in v0.4.5

func (responder LiaisonResponder) MultiStatus(
	body any, readableMessage string,
) LiaisonResponse

func (LiaisonResponder) Success added in v0.4.5

func (responder LiaisonResponder) Success(
	body any, readableMessage string,
) LiaisonResponse

type LiaisonResponse added in v0.1.1

type LiaisonResponse struct {
	Status          LiaisonResponseStatus `json:"status"`
	Body            any                   `json:"body"`
	ReadableMessage string                `json:"readableMessage"`
}

type LiaisonResponseStatus added in v0.1.1

type LiaisonResponseStatus string
const (
	LiaisonResponseStatusSuccess            LiaisonResponseStatus = "success"
	LiaisonResponseStatusCreated            LiaisonResponseStatus = "created"
	LiaisonResponseStatusAccepted           LiaisonResponseStatus = "accepted"
	LiaisonResponseStatusMultiStatus        LiaisonResponseStatus = "multiStatus"
	LiaisonResponseStatusUserError          LiaisonResponseStatus = "userError"
	LiaisonResponseStatusUnauthorized       LiaisonResponseStatus = "unauthorized"
	LiaisonResponseStatusForbidden          LiaisonResponseStatus = "forbidden"
	LiaisonResponseStatusNotFound           LiaisonResponseStatus = "notFound"
	LiaisonResponseStatusTimeout            LiaisonResponseStatus = "timeout"
	LiaisonResponseStatusConflict           LiaisonResponseStatus = "conflict"
	LiaisonResponseStatusRateLimited        LiaisonResponseStatus = "rateLimited"
	LiaisonResponseStatusInfraError         LiaisonResponseStatus = "infraError"
	LiaisonResponseStatusUnknownError       LiaisonResponseStatus = "unknownError"
	LiaisonResponseStatusServiceUnavailable LiaisonResponseStatus = "serviceUnavailable"
)

type RequesterIpExtractor added in v0.2.7

type RequesterIpExtractor struct {
	// contains filtered or unexported fields
}

func NewRequesterIpExtractor added in v0.2.7

func NewRequesterIpExtractor() RequesterIpExtractor

func (RequesterIpExtractor) Execute added in v0.2.7

func (extractor RequesterIpExtractor) Execute(
	httpRequest *http.Request,
) (tkValueObject.IpAddress, error)

type UiQueryParamFilter added in v0.4.4

type UiQueryParamFilter struct {
	Key            string
	QueryParamName string
	Kind           UiQueryParamFilterKind
}

type UiQueryParamFilterKind added in v0.4.4

type UiQueryParamFilterKind string
const (
	UiQueryParamFilterKindScalar UiQueryParamFilterKind = "scalar"
	UiQueryParamFilterKindMulti  UiQueryParamFilterKind = "multi"
	UiQueryParamFilterKindRange  UiQueryParamFilterKind = "range"
)

type UiRequestInputReader added in v0.4.4

type UiRequestInputReader struct {
	Filters   []UiQueryParamFilter
	BaseInput map[string]any
}

func (UiRequestInputReader) Read added in v0.4.4

func (reader UiRequestInputReader) Read(
	echoContext echo.Context,
) (map[string]any, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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