letsgo

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2022 License: MIT Imports: 21 Imported by: 0

README

Let's Go

Golang quickstart wrapper library for application building featuring Viper, Zerolog and Go-TUF

Let's Go handles repetitive application config and log initialization while health checking directory structure and file permissions

Purpose

Standardized application initialization for a stable and error free startup - save the debugging for after the logger has been initalized ;)

  • Create and maintain application config directory
  • Initialize application logger that prints both to file, and STDOUT
  • Provide Wrapper for TUF framework for easy self-updater
  • Automatic log rotation (WIP)

While almost all features of this library can be done natively in the individual applications, minus log rotation, the purpose is to remove unecessary customization options and provide an opininated default application startup so you don't have to understand the advanced aspects of these applications to get started working on your own. Expecially the TUF framework.

QuickStart

Initialize logger and configuration file with directory using sane defaults. This is the only command required to use this library. QuickStart() returns (*zap.Logger, error) and sets up viper config.

If you also wish to use the Self updater provided by this library, see Package Delivery

letsgo.QuickStart(
	ApplicationName  string, // Define ApplicationName, value is not used if a config directory is defined. Will set default config location to ~/.config/$ApplicationName
	opts *QuickStartOptions, // Additional optional settings; set to nil to accept all defaults
)

Working Example

log, err letsgo.QuickStart("MyApplication", nil)
if err != nil{
	panic(err)
}
log.Info("Logger and config (" + viper.ConfigFileUsed +") initialized succesfully")

Viper Configuration Example

After initializtion, viper may be used as defined in it's README

Example

viper.Set("foo", "bar")

To load value from config:

fmt.Println(viper.GetString("foo"))
> bar

You may set defaults for configuration options after calling QuickStart() by using viper.SetDefault()

ZeroLog Examples

Defined log levels map directly to zerolog

var logLevels = map[int8]zerolog.Level{
	6:  zerolog.PanicLevel,
	5:  zerolog.FatalLevel,
	4:  zerolog.ErrorLevel,
	3:  zerolog.WarnLevel,
	2:  zerolog.InfoLevel,
	1:  zerolog.DebugLevel,
	0:  zerolog.TraceLevel,
	-1: zerolog.Disabled,
}

Usage Examples:

InfoLevel:

log.Info().Msg("This is an info log")

PanicLevel:

log.Panic().Msg("This is a panic log")

Package Deliver - Secure file download

TUF Client (letsgo)
TUF Remote Respository (Server)

The TUF remote repository is not managed by letsgo and should be created using the TUF CLI. However, I will provide a simplified guide here as the manual provided on their github and website offer every option and configuration available, most you will not care about for a simple setup.

You can download using go install github.com/theupdateframework/go-tuf/cmd/tuf@latest.

Full instructions for use are available on their Github.

Overview

TUF Repository is secured using 4 main keys, these keys can be stored in seperate places so even if one area of delivery is compromised, the attacker will not be able to push invalid packages; the key may also be rotated to easily resume production. See what attacks TUF protects from

The 4 keys used by TUF are as follows:

  • Root
  • Targets
  • Snapshot
  • Timestamp

Root: Signs the other keys. You will need to include a copy of this key in your original distribution. letsgo's PackageDelivery(root []byte) referes to this original key. Private Root Password should be kept Offline

Targets: Signs the target files IE: the files you wish to distribute.

Snapshot: Signs the metadata file that provides information about the targets

Timestamp: Signs a timestamp statement periodically. Private Timestamp Password should be kept online

  • Offline Keys are keys that are stored and used manually by human intervention
  • Online Keys are keys that are used by automated processes IE: CI/CD

Terms used as defined in TUF specification

Initial Repository Setup

View full guide

Requires tuf-cli go install github.com/theupdateframework/go-tuf/cmd/tuf@latest

Start by setting up the 4 keys.

tuf gen-key root

tuf gen-key targets

tuf gen-key snapshot

tuf gen-key timestamp

Then sign initial root.json and enter root key passphrase you created above

tuf sign root.json

Your done, you have setup your repository. To add files to your repository see below

Adding Files to Repository

View full guide

Requires tuf-cli go install github.com/theupdateframework/go-tuf/cmd/tuf@latest

To add a target file located at staged/targets/foo/bar/baz.txt

$ tree .
.
├── keys
│   ├── snapshot.json
│   ├── targets.json
│   └── timestamp.json
├── repository
└── staged
    ├── root.json
    └── targets
        └── foo
            └── bar
                └── baz.txt

tuf add foo/bar/baz.txt

You will be required to enter your target keys passphrase.

You will than sign tuf snapshot and tuf timestamp

tuf snapshot

tuf timestamp

Finally, to commit to the respository, use

tuf commit

Your file has been added and will be available under repository/*

Hosting Repository for Client Connection

You will need to host your repository as an http file server so letsgo can connect. If you require an http file server my pure go implementation using go's net/http package is available here

Documentation

Overview

Package letsgo uses several popular application libraries (Viper, Zap, Go-TUF) to provide an opinionated jumpstart wrapper library.

``` letsgo.QuickStart(

ApplicationName  string, // Define ApplicationName, value is not used if a config directory is defined. Will set default config location to ~/.config/$ApplicationName
opts *QuickStartOptions, // Additional optional settings; set to nil to accept all defaults

) ``` Initialize logger and configuration file with directory using sane defaults. **This is the only command required to use this library**. QuickStart() returns (\*zap.Logger, error) and sets up viper config.

Index

Constants

This section is empty.

Variables

View Source
var KeyString string

Functions

func PackageDelivery added in v0.3.0

func PackageDelivery(remoteRepo string, files []string, root []byte, opts *PackageDeliveryOptions) error
PackageDelivery

Easily Update your package binary to the latest version. Returned error should not fatal; error should be considered informational only per TUF specification. (https://theupdateframework.github.io/specification/latest/#detailed-client-workflow)

Uses TUF native golang library to download file.

Remote repository must be a valid TUF repository.

File will be downlaoded to $ViperConfigDirectory/updates

## Through Cloudflare ZTNA

Going through cloudflare ztna requires extra steps, namely, providing a valid JWT to authenticate. This can be aquired by calling `cloudflared access login {url}` using cloudflared (https://github.com/cloudflare/cloudflared)

letsgo supports its usage, but does not provide functionality for getting a valid JWT; it must be provided as function argument.

## Arguments

repo: string | Remote TUF repository url. (include prefix http|https, do not include ending /)

file: string | File to download

root: []byte | original tuf repo root.json ( tuf assumes that a good, trusted copy of this file was shipped with the package manager or software updater using an out-of-band process.)

opts: struct | see struct for details; nil is supported (uses option defaults)

func QuickSetup

func QuickSetup(applicationName string, opts *QuickStartOptions) (*zerolog.Logger, error)

QuickSetup

The simpliest way to initialize config structure and logging or your money back guarantee.

applicationName (string): Define ApplicationName, value is not used if a config directory is defined. Will set default config location to /home/$USER$/.config/$ApplicationName

opts (QuickStartOptions): Can be set to nil to go with QuickSetup defaults.

returns (*zap.Logger):, use this in place of default logger

func RestartExecutable added in v0.3.0

func RestartExecutable()
RestartExecutable

Restarts the currently running excutable by spawning a seperate process that kills the current running program and spawns a new instance.

WIP

func SwitchFile added in v0.7.0

func SwitchFile(oldFile, newFile string) error
SwitchFile

oldFile (string): File that you wish to replace newFile (string): New file that will take the place of the old file

func VerifyPath added in v0.7.0

func VerifyPath(path string, mode os.FileMode) error

Types

type CloudflareZTOptions added in v0.3.0

type CloudflareZTOptions struct {
	JWT string // CloudflareZT requires a JSON Web Token to be passed to authenticate through ZTNA. This can be a static service-app JWT or the value generated by calling `cloudflared access login {url}`.
}

type PackageDeliveryOptions added in v0.3.0

type PackageDeliveryOptions struct {
	LocalRepo     string // Set local tuf repository | Leave "" for default $viperConfigDir/updates
	ReplaceBinary string // Set whether to automatically replace the current running binary with a downloaded file. Set string to name of desired file. Empty string will not replace
	// FilesAreRegex bool   // You can set your []files string to be regex rather than direct file names. This will allow many options such as searcing for a specific release (IE: file-windows64 )
	SmartSuffixOptions  *SmartSuffixOptions  // Used to find correct file if different binaries are packaged per arch.
	CloudflareZTOptions *CloudflareZTOptions // There is extra backend work for authentication that must occur to host TUF Repo behind cloudflared zero trust | Default OFF
}

type QuickStartOptions added in v0.3.0

type QuickStartOptions struct {
	LogLevelDefault        int8 // Set zerolog default level [-1 to 6] -1 will disable logging
	EnableConfigEncryption bool // Determine whether to create secure folder. This creates a folder with 0700 (this mirrors ssh private key requirements) permissions that store an encryption key, you can than use this key to store encrypted information in the config file. This allows the config file to retain wider read permissions while still containing sensitive information.
}

type SmartSuffixOptions added in v0.3.0

type SmartSuffixOptions struct {
	EnableSmartSuffix  bool   // Will look for file suffix to determine which file to download. IE: If you want to download file "file1" from linux-amd64, it will look to download "file_linux-amd64". | Default OFF
	NameSeperatorValue string // Value between filename and arch values. | Default "_": "file1_linux-amd64"
	ArchSeperatorValue string // Value between GOOS and GOARCH. | Default "-": "file1_linux-amd64"
}

Jump to

Keyboard shortcuts

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