tkInfra

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: MIT Imports: 42 Imported by: 3

Documentation

Index

Constants

View Source
const (
	SerializationFormatJson = "json"
	SerializationFormatYaml = "yaml"
)
View Source
const (
	RegexLargeFileThresholdBytes       int64 = 10 * 1024 * 1024
	ReadFileContentDefaultMaxSizeBytes int64 = 500 * 1024 * 1024
)
View Source
const (
	ReadThroughCertPairCertPathEnvVarName string = "CERTIFICATE_PAIR_CERT_PATH"
	ReadThroughCertPairKeyPathEnvVarName  string = "CERTIFICATE_PAIR_KEY_PATH"
	ReadThroughPkiDirEnvVarName           string = "PKI_DIR"
)
View Source
const (
	ShellExecutionTimeoutDefaultSecs   uint64 = 1800
	ShellExecutionTimeoutHardLimitSecs uint64 = 3600
	ShellExecutionTimeoutGraceSecs     uint64 = 10
	ShellCommandTimeoutExitCode        int    = 124
)
View Source
const (
	CharsetLowercaseLetters string = "abcdefghijklmnopqrstuvwxyz"
	CharsetUppercaseLetters string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	CharsetNumbers          string = "0123456789"
	CharsetSymbols          string = "!@#$%^&*()_+"
)
View Source
const (
	TrustedIpsEnvVarName   string = "TRUSTED_IPS"
	TrustedCidrsEnvVarName string = "TRUSTED_CIDRS"
)
View Source
const CypherNewSecretKeyLength = 32
View Source
const (
	ServerPublicIpAddressEnvVarName string = "SERVER_PUBLIC_IP_ADDR"
)

Variables

View Source
var (
	ErrDnsLookupResponseIdMismatch       = errors.New("DnsLookupResponseIdMismatch")
	ErrDnsLookupResponseNotResponse      = errors.New("DnsLookupResponseNotResponse")
	ErrDnsLookupResponseQuestionMismatch = errors.New("DnsLookupResponseQuestionMismatch")
	ErrDnsLookupResponseNameError        = errors.New("DnsLookupResponseNameError")
	ErrDnsLookupResponseServerFailure    = errors.New("DnsLookupResponseServerFailure")
	ErrDnsLookupResponseRefused          = errors.New("DnsLookupResponseRefused")
	ErrDnsLookupResponseUnknownRCode     = errors.New("DnsLookupResponseUnknownRCode")
	ErrDnsLookupResponseTruncated        = errors.New("DnsLookupResponseTruncated")
)
View Source
var (
	ErrSourceFileMissing            = errors.New("SourceFileNotFound")
	ErrTargetFileExists             = errors.New("TargetFileAlreadyExists")
	ErrFileMissing                  = errors.New("FileNotFound")
	ErrFileEmpty                    = errors.New("FileEmpty")
	ErrReplacementWouldTruncateFile = errors.New("ReplacementWouldTruncateFile")
	ErrDirCompressionWrongFormat    = errors.New("DirectoryCompressionMustUseTarFormat")
	ErrCompressedFileMissing        = errors.New("CompressedFileNotFound")
	ErrSourceDirMissing             = errors.New("SourceDirNotFound")
	ErrTargetDirExists              = errors.New("TargetDirAlreadyExists")
	ErrSourcePathMissing            = errors.New("SourcePathNotFound")
	ErrSymlinkExists                = errors.New("SymlinkAlreadyExists")
	ErrTargetPathExists             = errors.New("TargetPathAlreadyExists")
	ErrRegexPatternMissing          = errors.New("RegexPatternCannotBeNil")
	ErrUnsupportedCompressionFormat = errors.New("UnsupportedCompressionFormat")
	ErrTargetIsDirectory            = errors.New("TargetIsDirectory")
	ErrSourceIsDirectory            = errors.New("SourceIsDirectory")
	ErrFileTooLarge                 = errors.New("FileTooLarge")
	ErrTargetIsSymlink              = errors.New("TargetIsSymlink")
	ErrTargetNotDirectory           = errors.New("TargetNotDirectory")
)

Functions

func FileDeserializer added in v0.0.2

func FileDeserializer(
	filePath string,
) (outputMap map[string]any, err error)

func IsStdoutTerminal added in v0.3.3

func IsStdoutTerminal() bool

IsStdoutTerminal is the single interactivity check shared by the CLI logger and response renderer. Both honor one contract: logs go to stderr, stdout carries the JSON response only, and a human at a terminal gets richer formatting. Both sides must agree or the response channel corrupts.

func NewCypherSecretKey added in v0.1.7

func NewCypherSecretKey() (string, error)

NewCypherSecretKey generates a cryptographically secure random 32-byte secret key, encodes it in base64 for safe storage and transmission, and returns it as a string. This key is suitable for AES-GCM encryption and should be kept confidential.

func ReadServerPrivateIpAddress added in v0.0.6

func ReadServerPrivateIpAddress() (ipAddress tkValueObject.IpAddress, err error)

func ReadServerPublicIpAddress added in v0.0.6

func ReadServerPublicIpAddress() (ipAddress tkValueObject.IpAddress, err error)

func StringDeserializer added in v0.0.2

func StringDeserializer(
	serializedString string,
	serializationFormat string,
) (outputMap map[string]any, err error)

func TrustedCidrsReader added in v0.2.7

func TrustedCidrsReader() (trustedCidrBlocks []tkValueObject.CidrBlock, err error)

Types

type CertificateSettings added in v0.2.0

type CertificateSettings struct {
	CommonName           *tkValueObject.Fqdn
	AltNames             []tkValueObject.Fqdn
	IsCA                 bool
	MaxPathLengthPtr     *int
	HasMaxPathLengthZero bool
}

type Cypher added in v0.1.7

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

func NewCypher added in v0.1.7

func NewCypher(encodedSecretKey string) (*Cypher, error)

NewCypher creates a new Cypher instance with the provided base64-encoded secret key. The key must be a valid base64 string that decodes to exactly 16, 24, or 32 bytes for AES encryption. Use NewCypherSecretKey to generate a suitable key if needed. Returns an error if the key is invalid, providing fail-fast validation.

func (*Cypher) Decrypt added in v0.1.7

func (cypher *Cypher) Decrypt(encryptedText string) (plainText string, err error)

func (*Cypher) Encrypt added in v0.1.7

func (cypher *Cypher) Encrypt(plainText string) (encryptedText string, err error)

type DnsLookup added in v0.1.8

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

func NewDnsLookup added in v0.1.8

func NewDnsLookup(settings DnsLookupSettings) *DnsLookup

func (*DnsLookup) Execute added in v0.1.8

func (lookup *DnsLookup) Execute(
	hostname tkValueObject.UnixHostname,
	recordType *tkValueObject.DnsRecordType,
) ([]string, error)

type DnsLookupSettings added in v0.2.9

type DnsLookupSettings struct {
	PrimaryResolver           tkValueObject.IpAddress
	SecondaryResolver         tkValueObject.IpAddress
	QueryTimeoutSecs          uint
	DialTimeoutMs             uint
	ShouldBypassLocalResolver bool
}

type FileClerk added in v0.0.7

type FileClerk struct{}

func (FileClerk) CompressDir added in v0.0.7

func (clerk FileClerk) CompressDir(
	sourcePath string,
	compressionFormatPtr *string,
) (compressedFilePath string, err error)

func (FileClerk) CompressFile added in v0.0.7

func (clerk FileClerk) CompressFile(
	sourcePath string,
	compressionFormatPtr *string,
	shouldKeepSourceFilePtr *bool,
) (compressedFilePath string, err error)

CompressFile compresses sourcePath (file or directory) next to it and returns the compressed path. A file source is removed on success unless shouldKeepSourceFilePtr requests otherwise; directory sources are never removed.

func (FileClerk) CopyDir added in v0.0.7

func (clerk FileClerk) CopyDir(sourcePath, targetPath string) error

func (FileClerk) CopyFile added in v0.0.7

func (clerk FileClerk) CopyFile(sourcePath, targetPath string) error

func (FileClerk) CreateDir added in v0.0.7

func (clerk FileClerk) CreateDir(dirPath string) error
func (clerk FileClerk) CreateSymlink(
	sourcePath, targetPath string,
	shouldOverwrite bool,
) error

func (FileClerk) DecompressDir added in v0.0.7

func (clerk FileClerk) DecompressDir(
	sourcePath string,
	targetPathPtr *string,
	shouldKeepSourceFilePtr *bool,
) (decompressedDirPath string, err error)

func (FileClerk) DecompressFile added in v0.0.7

func (clerk FileClerk) DecompressFile(
	sourcePath string,
	targetPathPtr *string,
	shouldKeepSourceFilePtr *bool,
) (decompressedFilePath string, err error)

DecompressFile expands sourcePath (optionally into targetPathPtr) and removes the archive unless shouldKeepSourceFilePtr requests otherwise. Zip extraction overwrites existing files at the destination without warning: only decompress archives you trust.

func (FileClerk) DeleteDir added in v0.0.7

func (FileClerk) DeleteDir(dirPath string) error

DeleteDir removes a directory tree. A missing path is a no-op; a path that is not a directory (file or symlink) is rejected instead of silently ignored.

func (FileClerk) DeleteFile added in v0.0.7

func (FileClerk) DeleteFile(filePath string) error

DeleteFile removes a file or symlink. A missing path is a no-op; a directory is rejected.

func (FileClerk) DeleteFileContent added in v0.0.7

func (clerk FileClerk) DeleteFileContent(filePath string) error

func (FileClerk) FileContentRegexReplace added in v0.3.0

func (clerk FileClerk) FileContentRegexReplace(
	filePath tkValueObject.UnixAbsoluteFilePath,
	regexPattern *regexp.Regexp,
	replacement string,
) (replacementCount int, err error)

FileContentRegexReplace atomically substitutes regex matches in a file. Empty files and directories are rejected; symlinks are followed. Replacing everything with "" fails as a call-site bug — use TruncateFileContent to empty a file on purpose. Files at or above RegexLargeFileThresholdBytes are processed line-by-line, so multi-line patterns only match in smaller files; original line terminators are kept.

func (FileClerk) FileContentRegexSearch added in v0.2.9

func (clerk FileClerk) FileContentRegexSearch(
	filePath tkValueObject.UnixAbsoluteFilePath,
	regexPattern *regexp.Regexp,
) (regexSearchFindings []FileContentRegexFindings, err error)

FileContentRegexSearch finds every regex match in a file, returning each match's 1-based inclusive line range and capture groups. Files under RegexLargeFileThresholdBytes are matched in one pass — per-line anchors need the (?m) flag — and multi-line matches span every line they touch. Larger files stream line-by-line: multi-line patterns then match within a single line only, and LineNumRange is always [n, n].

func (FileClerk) FileExists added in v0.0.7

func (FileClerk) FileExists(filePath string) bool

func (FileClerk) IsDir added in v0.0.7

func (clerk FileClerk) IsDir(filePath string) bool

func (FileClerk) IsFile added in v0.0.7

func (clerk FileClerk) IsFile(filePath string) bool
func (FileClerk) IsSymlink(sourcePath string) bool

func (FileClerk) IsSymlinkTo added in v0.0.7

func (clerk FileClerk) IsSymlinkTo(sourcePath string, targetPath string) bool

func (FileClerk) MoveDir added in v0.0.7

func (clerk FileClerk) MoveDir(sourcePath, targetPath string) error

func (FileClerk) MoveFile added in v0.0.7

func (clerk FileClerk) MoveFile(sourcePath, targetPath string) error

MoveFile never replaces an existing target. Cross-device moves fall back to copy+delete: the two files briefly coexist, and an interrupted run leaves a partial target next to an untouched source.

func (FileClerk) OverwriteFile added in v0.3.0

func (clerk FileClerk) OverwriteFile(sourcePath, targetPath string) error

OverwriteFile atomically replaces targetPath's underlying file with sourcePath's content. Symlink targets are written through, not replaced: the original file and every other reference to it stay in place.

func (FileClerk) ReadFileContent added in v0.0.7

func (clerk FileClerk) ReadFileContent(
	filePath string,
	maxContentSizeBytesPtr *int64,
) (fileContent string, err error)

ReadFileContent loads a file's full content into memory, capped by ReadFileContentDefaultMaxSizeBytes. Files over the cap fail with ErrFileTooLarge rather than returning partially; callers facing larger files should stream them (io.Reader/bufio.Scanner) instead of raising the cap.

func (FileClerk) RemoveSymlink(symlinkPath string) error

func (FileClerk) RenameFile added in v0.0.7

func (clerk FileClerk) RenameFile(sourcePath, targetPath string) error

func (FileClerk) TouchFile added in v0.3.3

func (FileClerk) TouchFile(filePath string) error

TouchFile refreshes timestamps or creates the file, like touch(1) — but a dangling symlink at the path fails with ErrTargetIsSymlink instead of creating the file behind the link.

func (FileClerk) TruncateFileContent added in v0.0.7

func (clerk FileClerk) TruncateFileContent(filePath string) error

func (FileClerk) UpdateFileContent added in v0.0.7

func (clerk FileClerk) UpdateFileContent(
	filePath, newContent string,
	shouldOverwrite bool,
) error

func (FileClerk) UpdateFileOwnership added in v0.0.7

func (clerk FileClerk) UpdateFileOwnership(
	filePath string,
	userId, groupId int,
) error

func (FileClerk) UpdateFilePermissions added in v0.0.7

func (FileClerk) UpdateFilePermissions(
	filePath string,
	permissionsPtr *os.FileMode,
) error

UpdateFilePermissions never chmods through a symlink. Unlike chmod(2), it requires read permission on the target; root is exempt.

func (FileClerk) WriteNewFile added in v0.3.3

func (clerk FileClerk) WriteNewFile(
	filePath, content string,
	permissions os.FileMode,
) error

type FileContentRegexFindings added in v0.3.0

type FileContentRegexFindings struct {
	Match        string
	Groups       []string
	LineNumRange []int
}

FileContentRegexFindings holds one regex match plus its 1-based line range and capture groups. LineNumRange is [start, end] inclusive; a single-line match has start == end.

type PrivateKeySettings added in v0.2.0

type PrivateKeySettings struct {
	Algorithm tkValueObject.PrivateKeyAlgorithm
	BitSize   int
}

type PublicIpAddressResolver added in v0.2.9

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

func NewPublicIpAddressResolver added in v0.2.9

func NewPublicIpAddressResolver() *PublicIpAddressResolver

func (*PublicIpAddressResolver) Resolve added in v0.2.9

func (resolver *PublicIpAddressResolver) Resolve() (
	ipAddress tkValueObject.IpAddress, err error,
)

type ReadThrough added in v0.1.0

type ReadThrough struct {
}

Provides methods for reading information that when not found, are generated on the fly.

func (*ReadThrough) CertPairFilePathsReader added in v0.1.0

func (rt *ReadThrough) CertPairFilePathsReader() (
	certPath tkValueObject.UnixAbsoluteFilePath,
	keyPath tkValueObject.UnixAbsoluteFilePath,
	err error,
)

Attempts to retrieve the certificate pair file paths from the environment variables "CERTIFICATE_PAIR_CERT_PATH" and "CERTIFICATE_PAIR_KEY_PATH", otherwise generates a self-signed certificate pair on local 'pki' directory (or the directory specified by the environment variable "PKI_DIR") and returns the absolute paths to the generated files.

type Shell added in v0.0.6

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

func NewShell added in v0.0.6

func NewShell(settings ShellSettings) Shell

NewShell returns a value, not a pointer. Run copies the settings per call, so the sub-shell rewrite during preparation never compounds. A pointer receiver was rejected: it would leak that rewrite across calls and double-wrap the command on the second Run.

func (Shell) Run added in v0.0.6

func (shell Shell) Run() (stdoutStr string, err error)

type ShellError added in v0.0.6

type ShellError struct {
	StdErr   string `json:"stdErr"`
	ExitCode int    `json:"exitCode"`
}

func (*ShellError) Error added in v0.0.6

func (e *ShellError) Error() string

type ShellEscape added in v0.0.7

type ShellEscape struct {
}

func (ShellEscape) Quote added in v0.0.7

func (ShellEscape) Quote(inputStr string) string

func (ShellEscape) StripUnsafe added in v0.0.7

func (ShellEscape) StripUnsafe(inputStr string) string

type ShellSettings added in v0.0.6

type ShellSettings struct {
	Command                         string
	Args                            []string
	ShouldUseSubShell               bool
	ShouldUseCleanEnv               bool
	ShouldDisableTimeoutHardLimit   bool
	ShouldIgnoreUsernameLookupError bool
	Username                        string
	WorkingDirectory                string
	ExecutionTimeoutSecs            uint64
	Envs                            []string
	StdoutFilePath                  string
	StderrFilePath                  string
}

type Synthesizer

type Synthesizer struct{}

func (*Synthesizer) CACertificatePemFactory added in v0.2.0

func (synth *Synthesizer) CACertificatePemFactory(
	settings CertificateSettings,
) (certPem string, keyPem string, err error)

func (*Synthesizer) CertificatePemFactory added in v0.2.0

func (synth *Synthesizer) CertificatePemFactory(
	settings CertificateSettings,
) (certPem string, keyPem string, err error)

func (*Synthesizer) CharsetPresenceGuarantor

func (synth *Synthesizer) CharsetPresenceGuarantor(
	originalString []byte,
	charset string,
) []byte

func (*Synthesizer) MailAddressFactory

func (synth *Synthesizer) MailAddressFactory(username *string) string

func (*Synthesizer) PasswordFactory

func (synth *Synthesizer) PasswordFactory(
	desiredLength int,
	shouldIncludeSymbols bool,
) string

func (*Synthesizer) PrivateKeyPemFactory added in v0.2.0

func (synth *Synthesizer) PrivateKeyPemFactory(
	settings PrivateKeySettings,
) (keyPem string, err error)

func (*Synthesizer) SelfSignedCertificatePairFactory added in v0.1.0

func (synth *Synthesizer) SelfSignedCertificatePairFactory(
	commonName *tkValueObject.Fqdn,
	altNames []tkValueObject.Fqdn,
) (certPair tls.Certificate, err error)

func (*Synthesizer) SelfSignedCertificatePairPemFactory added in v0.1.0

func (synth *Synthesizer) SelfSignedCertificatePairPemFactory(
	commonName *tkValueObject.Fqdn,
	altNames []tkValueObject.Fqdn,
) (certPem string, keyPem string, err error)

func (*Synthesizer) UsernameFactory

func (synth *Synthesizer) UsernameFactory() string

Directories

Path Synopsis
db

Jump to

Keyboard shortcuts

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