utils

package
v4.38.8 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2024 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BlockTypeRSAPrivateKey      = "RSA PRIVATE KEY"
	BlockTypeRSAPublicKey       = "RSA PUBLIC KEY"
	BlockTypeECDSAPrivateKey    = "EC PRIVATE KEY"
	BlockTypePKCS8PrivateKey    = "PRIVATE KEY"
	BlockTypePKIXPublicKey      = "PUBLIC KEY"
	BlockTypeCertificate        = "CERTIFICATE"
	BlockTypeCertificateRequest = "CERTIFICATE REQUEST"
	BlockTypeX509CRL            = "X509 CRL"

	KeyAlgorithmRSA     = "RSA"
	KeyAlgorithmECDSA   = "ECDSA"
	KeyAlgorithmEd25519 = "ED25519"

	HashAlgorithmSHA1   = "SHA1"
	HashAlgorithmSHA256 = "SHA256"
	HashAlgorithmSHA384 = "SHA384"
	HashAlgorithmSHA512 = "SHA512"

	EllipticCurveP224 = "P224"
	EllipticCurveP256 = "P256"
	EllipticCurveP384 = "P384"
	EllipticCurveP521 = "P521"

	EllipticCurveAltP224 = "P-224"
	EllipticCurveAltP256 = "P-256"
	EllipticCurveAltP384 = "P-384"
	EllipticCurveAltP521 = "P-521"
)

X.509 consts.

View Source
const (
	// Hour is an int based representation of the time unit.
	Hour = time.Minute * 60

	// Day is an int based representation of the time unit.
	Day = Hour * 24

	// Week is an int based representation of the time unit.
	Week = Day * 7

	// Year is an int based representation of the time unit.
	Year = Day * 365

	// Month is an int based representation of the time unit.
	Month = Year / 12
)
View Source
const (
	DurationUnitDays   = "d"
	DurationUnitWeeks  = "w"
	DurationUnitMonths = "M"
	DurationUnitYears  = "y"
)

Duration unit types.

View Source
const (
	HoursInDay   = 24
	HoursInWeek  = HoursInDay * 7
	HoursInMonth = HoursInDay * 30
	HoursInYear  = HoursInDay * 365
)

Number of hours in particular measurements of time.

View Source
const (
	// RFC3339Zero is the default value for time.Time.Unix().
	RFC3339Zero = int64(-62135596800)
)

Variables

View Source
var BuildBranch = "master"

BuildBranch is replaced by LDFLAGS at build time with the current branch.

View Source
var BuildCommit = "unknown"

BuildCommit is replaced by LDFLAGS at build time with the current commit.

View Source
var BuildDate = ""

BuildDate is replaced by LDFLAGS at build time with the date the build started.

View Source
var BuildExtra = ""

BuildExtra is replaced by LDFLAGS at build time with a blank string by default. People porting Authelia can use this to add a suffix to their versions.

View Source
var BuildNumber = "0"

BuildNumber is replaced by LDFLAGS at build time with the CI build number.

View Source
var BuildState = "untagged dirty"

BuildState is replaced by LDFLAGS at build time with `tagged` or `untagged` depending on if the commit is tagged, and `clean` or `dirty` depending on the working tree state. For example if the commit was tagged and the working tree was dirty it would be "tagged dirty". This is used to determine the version string output mode.

View Source
var BuildTag = "unknown"

BuildTag is replaced by LDFLAGS at build time with the latest tag at or before the current commit.

View Source
var ErrTimeoutReached = errors.New("timeout reached")

ErrTimeoutReached error thrown when a timeout is reached.

View Source
var (
	// StandardTimeLayouts is the set of standard time layouts used with ParseTimeString.
	StandardTimeLayouts = []string{
		"Jan 2 15:04:05 2006",
		time.DateTime,
		time.RFC3339,
		time.RFC1123Z,
		time.RubyDate,
		time.ANSIC,
		time.DateOnly,
	}
)

Functions

func BytesJoin added in v4.38.0

func BytesJoin(s ...[]byte) (dst []byte)

BytesJoin is an alternate form of bytes.Join which doesn't use a sep.

func CastX509AsCertificate added in v4.36.0

func CastX509AsCertificate(c any) (certificate *x509.Certificate, ok bool)

CastX509AsCertificate converts an interface to an *x509.Certificate.

func CheckUntil

func CheckUntil(interval time.Duration, timeout time.Duration, predicate func() (bool, error)) error

CheckUntil regularly check a predicate until it's true or time out is reached.

func Command

func Command(name string, args ...string) *exec.Cmd

Command create a command at the project root.

func CommandWithStdout

func CommandWithStdout(name string, args ...string) *exec.Cmd

CommandWithStdout create a command forwarding stdout and stderr to the OS streams.

func ConvertDERToPEM added in v4.35.0

func ConvertDERToPEM(der []byte, blockType PEMBlockType) ([]byte, error)

ConvertDERToPEM convert certificate in DER format into PEM format.

func Decrypt

func Decrypt(ciphertext []byte, key *[32]byte) (plaintext []byte, err error)

Decrypt decrypts data using 256-bit AES-GCM. This both hides the content of the data and provides a check that it hasn't been altered. Expects input form nonce|ciphertext|tag where '|' indicates concatenation.

func DirectoryExists

func DirectoryExists(path string) (exists bool, err error)

DirectoryExists returns true if the given path exists and is a directory.

func ECDSASignatureAlgorithmFromString added in v4.36.0

func ECDSASignatureAlgorithmFromString(algorithm string) (alg x509.SignatureAlgorithm)

ECDSASignatureAlgorithmFromString returns a x509.SignatureAlgorithm for the ECDSA x509.PublicKeyAlgorithm given an algorithm string.

func EllipticCurveFromString added in v4.36.0

func EllipticCurveFromString(curveString string) (curve elliptic.Curve)

EllipticCurveFromString turns a string into an elliptic.Curve.

func Encrypt

func Encrypt(plaintext []byte, key *[32]byte) (ciphertext []byte, err error)

Encrypt encrypts data using 256-bit AES-GCM. This both hides the content of the data and provides a check that it hasn't been altered. Output takes the form nonce|ciphertext|tag where '|' indicates concatenation.

func EqualURLs added in v4.38.0

func EqualURLs(first, second *url.URL) bool

EqualURLs returns true if the two *url.URL values are effectively equal taking into consideration web normalization.

func FileExists

func FileExists(path string) (exists bool, err error)

FileExists returns true if the given path exists and is a file.

func GenerateCertificate added in v4.35.0

func GenerateCertificate(privateKeyBuilder PrivateKeyBuilder, hosts []string, validFrom time.Time, validFor time.Duration, isCA bool) ([]byte, []byte, error)

GenerateCertificate generate a certificate given a private key. RSA, Ed25519 and ECDSA are officially supported.

func GetExpectedErrTxt

func GetExpectedErrTxt(err string) string

GetExpectedErrTxt returns error text for expected errs. THIS IS A TEST UTILITY FUNCTION.

func HasDomainSuffix added in v4.38.0

func HasDomainSuffix(domain, domainSuffix string) bool

HasDomainSuffix returns true if the URI hostname is equal to the domain or if it has a suffix of the domain prefixed with a period.

func HasURIDomainSuffix added in v4.36.7

func HasURIDomainSuffix(uri *url.URL, domainSuffix string) bool

HasURIDomainSuffix returns true if the URI hostname is equal to the domain suffix or if it has a suffix of the domain suffix prefixed with a period.

func HashSHA256FromPath

func HashSHA256FromPath(path string) (output string, err error)

HashSHA256FromPath takes a path string and calculates the SHA256 checksum of the file at the path returning it as a base16 hash string.

func HashSHA256FromString

func HashSHA256FromString(input string) (output string)

HashSHA256FromString takes an input string and calculates the SHA256 checksum returning it as a base16 hash string.

func IsBoolCountLessThanN added in v4.35.0

func IsBoolCountLessThanN(n int, v bool, vals ...bool) bool

IsBoolCountLessThanN takes an int (n), bool (v), and then a variadic slice of bool (vals). If the number of bools in vals with the value v is more than n, it returns false, otherwise it returns true.

func IsIntegerInSlice added in v4.38.0

func IsIntegerInSlice(needle int, haystack []int) bool

func IsStringAbsURL

func IsStringAbsURL(input string) (err error)

IsStringAbsURL checks a string can be parsed as a URL and that is IsAbs and if it can't it returns an error describing why.

func IsStringAlphaNumeric

func IsStringAlphaNumeric(input string) bool

IsStringAlphaNumeric returns false if any rune in the string is not alphanumeric.

func IsStringInSlice

func IsStringInSlice(needle string, haystack []string) (inSlice bool)

IsStringInSlice checks if a single string is in a slice of strings.

func IsStringInSliceContains

func IsStringInSliceContains(needle string, haystack []string) (inSlice bool)

IsStringInSliceContains checks if a single string is in an array of strings.

func IsStringInSliceF added in v4.38.0

func IsStringInSliceF(needle string, haystack []string, isEqual func(needle, item string) bool) (inSlice bool)

IsStringInSliceF checks if a single string is in a slice of strings using the provided isEqual func.

func IsStringInSliceFold

func IsStringInSliceFold(needle string, haystack []string) (inSlice bool)

IsStringInSliceFold checks if a single string is in a slice of strings but uses strings.EqualFold to compare them.

func IsStringSliceContainsAll added in v4.33.0

func IsStringSliceContainsAll(needles []string, haystack []string) (inSlice bool)

IsStringSliceContainsAll checks if the haystack contains all strings in the needles.

func IsStringSliceContainsAny added in v4.33.0

func IsStringSliceContainsAny(needles []string, haystack []string) (inSlice bool)

IsStringSliceContainsAny checks if the haystack contains any of the strings in the needles.

func IsStringSliceContainsAnyF added in v4.38.0

func IsStringSliceContainsAnyF(needles []string, haystack []string, isInSlice func(needle string, haystack []string) bool) (inSlice bool)

IsStringSliceContainsAnyF checks if the haystack contains any of the strings in the needles using the isInSlice func.

func IsStringSlicesDifferent

func IsStringSlicesDifferent(a, b []string) (different bool)

IsStringSlicesDifferent checks two slices of strings and on the first occurrence of a string item not existing in the other slice returns true, otherwise returns false.

func IsStringSlicesDifferentFold

func IsStringSlicesDifferentFold(a, b []string) (different bool)

IsStringSlicesDifferentFold checks two slices of strings and on the first occurrence of a string item not existing in the other slice (case insensitive) returns true, otherwise returns false.

func IsURISafeRedirection added in v4.36.7

func IsURISafeRedirection(uri *url.URL, domain string) bool

IsURISafeRedirection returns true if the URI passes the IsURISecure and HasURIDomainSuffix, i.e. if the scheme is secure and the given URI has a hostname that is either exactly equal to the given domain or if it has a suffix of the domain prefixed with a period.

func IsURISecure added in v4.36.7

func IsURISecure(uri *url.URL) bool

IsURISecure returns true if the URI has a secure schemes (https or wss).

func IsURLInSlice added in v4.35.0

func IsURLInSlice(needle *url.URL, haystack []*url.URL) (has bool)

IsURLInSlice returns true if the needle url.URL is in the []url.URL haystack.

func IsX509PrivateKey added in v4.36.0

func IsX509PrivateKey(i any) bool

IsX509PrivateKey returns true if the provided interface is an rsa.PrivateKey, ecdsa.PrivateKey, or ed25519.PrivateKey.

func JoinAndCanonicalizeHeaders added in v4.35.0

func JoinAndCanonicalizeHeaders(sep []byte, headers ...string) (joined []byte)

JoinAndCanonicalizeHeaders join header strings by a given sep.

func KeySigAlgorithmFromString added in v4.36.0

func KeySigAlgorithmFromString(keyAlgorithm, signatureAlgorithm string) (keyAlg x509.PublicKeyAlgorithm, sigAlg x509.SignatureAlgorithm)

KeySigAlgorithmFromString returns a x509.PublicKeyAlgorithm and x509.SignatureAlgorithm given a keyAlgorithm and signatureAlgorithm string.

func NewTLSConfig

func NewTLSConfig(config *schema.TLS, rootCAs *x509.CertPool) (tlsConfig *tls.Config)

NewTLSConfig generates a tls.Config from a schema.TLS and a x509.CertPool.

func NewX509CertPool

func NewX509CertPool(directory string) (certPool *x509.CertPool, warnings []error, errors []error)

NewX509CertPool generates a x509.CertPool from the system PKI and the directory specified.

func OriginFromURL added in v4.35.0

func OriginFromURL(u *url.URL) (origin *url.URL)

OriginFromURL returns an origin url.URL given another url.URL.

func PEMBlockFromX509Key added in v4.36.0

func PEMBlockFromX509Key(key any, legacy bool) (block *pem.Block, err error)

PEMBlockFromX509Key turns a PublicKey or PrivateKey into a pem.Block.

func ParseDurationString

func ParseDurationString(input string) (duration time.Duration, err error)

ParseDurationString standardizes a duration string with StandardizeDurationString then uses time.ParseDuration to convert it into a time.Duration.

func ParsePEMBlock added in v4.38.0

func ParsePEMBlock(block *pem.Block) (key any, err error)

ParsePEMBlock parses a single PEM block into the relevant X509 data struct.

func ParseTimeString added in v4.38.0

func ParseTimeString(input string) (t time.Time, err error)

ParseTimeString attempts to parse a string with several time formats.

func ParseTimeStringWithLayouts added in v4.38.0

func ParseTimeStringWithLayouts(input string, layouts []string) (match time.Time, err error)

ParseTimeStringWithLayouts attempts to parse a string with several time formats. The format with the most matching characters is returned.

func ParseX509FromPEM added in v4.36.0

func ParseX509FromPEM(data []byte) (key any, err error)

ParseX509FromPEM parses PEM bytes and returns a PKCS key.

func ParseX509FromPEMRecursive added in v4.38.0

func ParseX509FromPEMRecursive(data []byte) (decoded any, err error)

ParseX509FromPEMRecursive allows returning the appropriate key type given some PEM encoded input. For Keys this is a single value of one of *rsa.PrivateKey, *rsa.PublicKey, *ecdsa.PrivateKey, *ecdsa.PublicKey, ed25519.PrivateKey, or ed25519.PublicKey. For certificates this is either a *X509.Certificate, or a []*X509.Certificate.

func PathExists

func PathExists(path string) (exists bool, err error)

PathExists returns true if the given path exists.

func PublicKeyAlgorithmFromString added in v4.36.0

func PublicKeyAlgorithmFromString(algorithm string) (alg x509.PublicKeyAlgorithm)

PublicKeyAlgorithmFromString returns a x509.PublicKeyAlgorithm given an appropriate string.

func PublicKeyFromPrivateKey added in v4.36.0

func PublicKeyFromPrivateKey(privateKey any) (publicKey any)

PublicKeyFromPrivateKey returns a PublicKey when provided with a PrivateKey.

func RSASignatureAlgorithmFromString added in v4.36.0

func RSASignatureAlgorithmFromString(algorithm string) (alg x509.SignatureAlgorithm)

RSASignatureAlgorithmFromString returns a x509.SignatureAlgorithm for the RSA x509.PublicKeyAlgorithm given an algorithm string.

func RunCommandAndReturnOutput

func RunCommandAndReturnOutput(command string) (output string, exitCode int, err error)

RunCommandAndReturnOutput runs a shell command then returns the stdout and the exit code.

func RunCommandUntilCtrlC

func RunCommandUntilCtrlC(cmd *exec.Cmd)

RunCommandUntilCtrlC run a command until ctrl-c is hit.

func RunCommandWithTimeout

func RunCommandWithTimeout(cmd *exec.Cmd, timeout time.Duration) error

RunCommandWithTimeout run a command with timeout.

func RunFuncUntilCtrlC

func RunFuncUntilCtrlC(fn func() error) error

RunFuncUntilCtrlC run a function until ctrl-c is hit.

func RunFuncWithRetry

func RunFuncWithRetry(attempts int, sleep time.Duration, f func() error) (err error)

RunFuncWithRetry run a function for n attempts with a sleep of n duration between each attempt.

func Shell

func Shell(command string) *exec.Cmd

Shell create a shell command.

func SliceString

func SliceString(s string, d int) (array []string)

SliceString splits a string s into an array with each item being a max of int d d = denominator, n = numerator, q = quotient, r = remainder.

func StandardizeDurationString added in v4.34.0

func StandardizeDurationString(input string) (output string, err error)

StandardizeDurationString converts units of time that stdlib is unaware of to hours.

func StringHTMLEscape

func StringHTMLEscape(input string) (output string)

StringHTMLEscape escapes chars for a HTML body.

func StringJoinAnd added in v4.38.7

func StringJoinAnd(items []string) string

func StringJoinBuild added in v4.38.7

func StringJoinBuild(sep, sepFinal, quote string, items []string) string

func StringJoinComma added in v4.38.7

func StringJoinComma(word string, items []string) string

func StringJoinDelimitedEscaped added in v4.35.0

func StringJoinDelimitedEscaped(value []string, delimiter rune) string

StringJoinDelimitedEscaped joins a string with a specified rune delimiter after escaping any instance of that string in the string slice. Used with StringSplitDelimitedEscaped.

func StringJoinOr added in v4.38.7

func StringJoinOr(items []string) string

func StringSliceFromURLs added in v4.35.0

func StringSliceFromURLs(urls []*url.URL) []string

StringSliceFromURLs returns a []string from a []url.URL.

func StringSlicesDelta

func StringSlicesDelta(before, after []string) (added, removed []string)

StringSlicesDelta takes a before and after []string and compares them returning a added and removed []string.

func StringSplitDelimitedEscaped added in v4.35.0

func StringSplitDelimitedEscaped(value string, delimiter rune) (out []string)

StringSplitDelimitedEscaped splits a string with a specified rune delimiter after unescaping any instance of that string in the string slice that has been escaped. Used with StringJoinDelimitedEscaped.

func TLSVersionFromBytesString added in v4.38.2

func TLSVersionFromBytesString(input string) (version int, err error)

TLSVersionFromBytesString converts a given 4 byte hexadecimal string into the appropriate TLS version.

func URLPathFullClean added in v4.36.2

func URLPathFullClean(u *url.URL) (output string)

URLPathFullClean returns a URL path with the query parameters appended (full path) with the path portion parsed through path.Clean given a *url.URL.

func URLsFromStringSlice added in v4.35.0

func URLsFromStringSlice(urls []string) []*url.URL

URLsFromStringSlice returns a []url.URL from a []string.

func UnixNanoTimeToMicrosoftNTEpoch added in v4.38.0

func UnixNanoTimeToMicrosoftNTEpoch(nano int64) (t uint64)

UnixNanoTimeToMicrosoftNTEpoch converts a unix timestamp in nanosecond format to win32 epoch format.

func Version

func Version() (versionString string)

Version returns the Authelia version.

The format of the string is dependent on the values in BuildState. If tagged and clean are present it returns the BuildTag i.e. v1.0.0. If dirty and tagged are present it returns <BuildTag>-dirty. Otherwise, the following is the format: untagged-<BuildTag>-dirty-<BuildExtra> (<BuildBranch>, <BuildCommit>).

func VersionAdv added in v4.36.9

func VersionAdv(tag, state, commit, branch, extra string) (version string)

VersionAdv takes inputs to generate the version.

func WriteCertificateBytesAsPEMToPath added in v4.38.0

func WriteCertificateBytesAsPEMToPath(path string, csr bool, certs ...[]byte) (err error)

WriteCertificateBytesAsPEMToPath writes a certificate/csr to a file in the PEM format.

func WriteCertificateBytesAsPEMToWriter added in v4.38.0

func WriteCertificateBytesAsPEMToWriter(wr io.Writer, csr bool, certs ...[]byte) (err error)

WriteCertificateBytesAsPEMToWriter writes a certificate/csr to a io.Writer in the PEM format.

func WriteKeyToPEM added in v4.36.0

func WriteKeyToPEM(key any, path string, legacy bool) (err error)

WriteKeyToPEM writes a key that can be encoded as a PEM to a file in the PEM format.

func WritePEMBlocksToPath added in v4.38.0

func WritePEMBlocksToPath(path string, blocks ...*pem.Block) (err error)

WritePEMBlocksToPath writes a set of *pem.Blocks to a file.

func WritePEMBlocksToWriter added in v4.38.0

func WritePEMBlocksToWriter(wr io.Writer, blocks ...*pem.Block) (err error)

func X509ParseExtendedKeyUsage added in v4.36.0

func X509ParseExtendedKeyUsage(extKeyUsages []string, ca bool) (extKeyUsage []x509.ExtKeyUsage)

X509ParseExtendedKeyUsage parses a list of extended key usages. If provided with an empty list returns a default of Server Auth unless ca is true in which case it returns a default of Any.

func X509ParseKeyUsage added in v4.36.0

func X509ParseKeyUsage(keyUsages []string, ca bool) (keyUsage x509.KeyUsage)

X509ParseKeyUsage parses a list of key usages. If provided with an empty list returns a default of Key Encipherment and Digital Signature unless ca is true in which case it returns Cert Sign.

Types

type ECDSAKeyBuilder added in v4.35.0

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

ECDSAKeyBuilder builder of ECDSA private key.

func (ECDSAKeyBuilder) Build added in v4.35.0

func (ekb ECDSAKeyBuilder) Build() (any, error)

Build an ECDSA private key.

func (ECDSAKeyBuilder) WithCurve added in v4.35.0

func (ekb ECDSAKeyBuilder) WithCurve(curve elliptic.Curve) ECDSAKeyBuilder

WithCurve configure the curve to use for the ECDSA private key.

type Ed25519KeyBuilder added in v4.35.0

type Ed25519KeyBuilder struct{}

Ed25519KeyBuilder builder of Ed25519 private key.

func (Ed25519KeyBuilder) Build added in v4.35.0

func (ekb Ed25519KeyBuilder) Build() (any, error)

Build an Ed25519 private key.

type ErrSliceSortAlphabetical

type ErrSliceSortAlphabetical []error

ErrSliceSortAlphabetical is a helper type that can be used with sort.Sort to sort a slice of errors in alphabetical order. Usage is simple just do sort.Sort(ErrSliceSortAlphabetical([]error{})).

func (ErrSliceSortAlphabetical) Len

func (s ErrSliceSortAlphabetical) Len() int

func (ErrSliceSortAlphabetical) Less

func (s ErrSliceSortAlphabetical) Less(i, j int) bool

func (ErrSliceSortAlphabetical) Swap

func (s ErrSliceSortAlphabetical) Swap(i, j int)

type PEMBlockType added in v4.35.0

type PEMBlockType int

PEMBlockType represent an enum of the existing PEM block types.

const (
	// Certificate block type.
	Certificate PEMBlockType = iota
	// PrivateKey block type.
	PrivateKey
)

type PrivateKeyBuilder added in v4.35.0

type PrivateKeyBuilder interface {
	Build() (any, error)
}

PrivateKeyBuilder interface for a private key builder.

type RSAKeyBuilder added in v4.35.0

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

RSAKeyBuilder builder of RSA private key.

func (RSAKeyBuilder) Build added in v4.35.0

func (rkb RSAKeyBuilder) Build() (any, error)

Build a RSA private key.

func (RSAKeyBuilder) WithKeySize added in v4.35.0

func (rkb RSAKeyBuilder) WithKeySize(bits int) RSAKeyBuilder

WithKeySize configure the key size to use with RSA.

Jump to

Keyboard shortcuts

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