util

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const MaxResourceIndicators = 10

MaxResourceIndicators caps how many `resource` values a single OAuth request may carry. RFC 8707 sets no upper bound, so we pick a generous limit that defeats DoS amplification (a request could otherwise inflate the persisted authorization-code row and the issued JWT's `aud` array).

View Source
const MaxResourceURILength = 1024

MaxResourceURILength caps the length of each individual resource value. Without this, a single huge URI would still pass count-validation and then balloon DB rows, JWT `aud` arrays, and audit-log payloads. 1024 is generous for any realistic MCP server URL.

Variables

View Source
var ErrInvalidResource = errors.New("invalid resource indicator")

ErrInvalidResource is returned by ValidateResourceIndicators when a `resource` parameter (RFC 8707 §2) is malformed. The handler layer maps this to the OAuth error code "invalid_target".

Functions

func AudienceClaim added in v0.31.0

func AudienceClaim(aud []string) any

AudienceClaim collapses an audience list into the shape conventionally emitted as a JWT `aud` claim (RFC 7519 §4.1.3): nil for an empty list, a plain string for a single value, or a fresh []string for multiple values. The returned slice is a defensive copy so the caller may mutate the input without affecting any value already handed to a JWT signer or serializer.

func AudienceFromClaims added in v0.31.0

func AudienceFromClaims(claims map[string]any) []string

AudienceFromClaims extracts the JWT `aud` claim from a decoded MapClaims map and normalizes it to []string. The jwt library decodes single-string aud claims as `string` and multi-value aud claims as `[]any` (via json.Unmarshal); this helper folds both shapes into the same slice form for callers that need the audience without going through the JWT library.

func CryptoRandomBytes

func CryptoRandomBytes(length int) ([]byte, error)

CryptoRandomBytes generates cryptographically secure random bytes

func CryptoRandomString

func CryptoRandomString(length int) (string, error)

CryptoRandomString generates a random hex string for salts

func GenerateRandomPassword added in v0.24.0

func GenerateRandomPassword(length int) (string, error)

GenerateRandomPassword generates a random password of specified length. Uses base64url encoding and truncates to length printable characters.

func GetIPFromContext

func GetIPFromContext(ctx context.Context) string

GetIPFromContext extracts the client IP address from the context. Returns empty string if IP cannot be determined.

func GetRequestMethodFromContext added in v0.25.0

func GetRequestMethodFromContext(ctx context.Context) string

GetRequestMethodFromContext extracts the HTTP method from the context.

func GetRequestPathFromContext added in v0.25.0

func GetRequestPathFromContext(ctx context.Context) string

GetRequestPathFromContext extracts the request path from the context.

func GetUserAgentFromContext added in v0.25.0

func GetUserAgentFromContext(ctx context.Context) string

GetUserAgentFromContext extracts the User-Agent from the context.

func HashToken

func HashToken(token, salt string) string

HashToken returns PBKDF2 hash of token with salt Parameters match Gitea's implementation for security consistency

func IsRedirectSafe added in v0.14.0

func IsRedirectSafe(redirectURL, baseURL string) bool

IsRedirectSafe validates that a redirect URL is safe to use. It only allows: 1. Relative paths starting with "/" but not "//" 2. Absolute URLs that match the baseURL host

func IsScopeSubset added in v0.20.0

func IsScopeSubset(allowed, requested string) bool

IsScopeSubset returns true if every scope in requested is present in allowed. Both are space-separated scope strings. An empty requested string is always valid.

func IsStringSliceSetEqual added in v0.31.0

func IsStringSliceSetEqual(a, b []string) bool

IsStringSliceSetEqual reports whether `a` and `b` contain the same set of strings (order-independent, duplicates collapsed). Used by RFC 8707 consent matching where the resource set the user approved must exactly match the set the next request is asking for — narrowing or widening should both re-prompt, not silently match a remembered consent.

func IsStringSliceSubset added in v0.31.0

func IsStringSliceSubset(super, sub []string) bool

IsStringSliceSubset reports whether every element of `sub` appears in `super`. An empty `sub` is always a subset; an empty `super` paired with a non-empty `sub` is not. Used by RFC 8707 §2.2 audience-narrowing checks and any other set-membership test on `[]string` slices.

func IsValidProjectIdentifier added in v0.29.0

func IsValidProjectIdentifier(s string) bool

IsValidProjectIdentifier reports whether s matches the project-identifier shape. Empty input returns false; callers that treat empty as "unset" must check before calling.

func SHA256Hex added in v0.15.0

func SHA256Hex(s string) string

SHA256Hex returns the SHA-256 hash of s as a lowercase hex string. Intended for use with high-entropy, unguessable values (e.g., randomly generated tokens); for such inputs, a salt is not required for security.

func ScopeSet added in v0.18.0

func ScopeSet(scopes string) map[string]bool

ScopeSet parses a space-separated scope string into a boolean lookup map.

func SetIPContext added in v0.14.0

func SetIPContext(ctx context.Context, ip string) context.Context

SetIPContext embeds client IP into a standard context

func SetRequestMetadataContext added in v0.25.0

func SetRequestMetadataContext(
	ctx context.Context,
	userAgent, path, method string,
) context.Context

SetRequestMetadataContext embeds HTTP request metadata into a standard context.

func TruncateString added in v0.18.0

func TruncateString(s string, maxLen int) string

TruncateString truncates s to maxLen runes and appends "..." if truncated.

func UniqueKeys added in v0.20.0

func UniqueKeys[T any](items []T, keyFn func(T) string) []string

UniqueKeys extracts unique non-empty string keys from a slice using keyFn.

func ValidateResourceIndicators added in v0.31.0

func ValidateResourceIndicators(values []string) ([]string, error)

ValidateResourceIndicators validates a list of OAuth 2.0 Resource Indicator values per RFC 8707 §2.1. Each value must be:

  • non-empty
  • within MaxResourceURILength bytes
  • parseable as a URI
  • absolute (has a scheme)
  • http or https scheme — `javascript:`, `data:`, `file:` etc. are rejected so a downstream consumer that turns `aud` back into a URL cannot be tricked into a dangerous scheme
  • has a non-empty host (rejects shapes like `https:foo` or `http:/path` that pass IsAbs() but have no usable authority)
  • free of a fragment component

The overall list size is also capped (see MaxResourceIndicators) to prevent DoS amplification.

Empty input returns (nil, nil) so callers that don't pass `resource` behave exactly as before. On success the caller's slice is returned unchanged — the function only validates, it does not transform.

func WriteCredentialsFile added in v0.19.0

func WriteCredentialsFile(dir, content string) (string, error)

WriteCredentialsFile writes initial credentials to a new file with 0600 permissions. Uses O_CREATE|O_EXCL to fail if the file already exists (prevents overwriting existing credentials and symlink attacks). Returns the file path on success.

Types

This section is empty.

Jump to

Keyboard shortcuts

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