Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

With errors #189

Merged
merged 10 commits into from
Sep 30, 2019
43 changes: 17 additions & 26 deletions crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ import (
"encoding/pem"
"errors"
"fmt"
"io"
"hash/adler32"
"io"
"math/big"
"net"
"time"
Expand All @@ -48,12 +48,12 @@ func adler32sum(input string) string {

// uuidv4 provides a safe and secure UUID v4 implementation
func uuidv4() string {
return fmt.Sprintf("%s", uuid.New())
return uuid.New().String()
}

var master_password_seed = "com.lyndir.masterpassword"
var masterPasswordSeed = "com.lyndir.masterpassword"

var password_type_templates = map[string][][]byte{
var passwordTypeTemplates = map[string][][]byte{
"maximum": {[]byte("anoxxxxxxxxxxxxxxxxx"), []byte("axxxxxxxxxxxxxxxxxno")},
"long": {[]byte("CvcvnoCvcvCvcv"), []byte("CvcvCvcvnoCvcv"), []byte("CvcvCvcvCvcvno"), []byte("CvccnoCvcvCvcv"), []byte("CvccCvcvnoCvcv"),
[]byte("CvccCvcvCvcvno"), []byte("CvcvnoCvccCvcv"), []byte("CvcvCvccnoCvcv"), []byte("CvcvCvccCvcvno"), []byte("CvcvnoCvcvCvcc"),
Expand All @@ -66,7 +66,7 @@ var password_type_templates = map[string][][]byte{
"pin": {[]byte("nnnn")},
}

var template_characters = map[byte]string{
var templateCharacters = map[byte]string{
'V': "AEIOU",
'C': "BCDFGHJKLMNPQRSTVWXYZ",
'v': "aeiou",
Expand All @@ -78,14 +78,14 @@ var template_characters = map[byte]string{
'x': "AEIOUaeiouBCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz0123456789!@#$%^&*()",
}

func derivePassword(counter uint32, password_type, password, user, site string) string {
var templates = password_type_templates[password_type]
func derivePassword(counter uint32, passwordType, password, user, site string) string {
var templates = passwordTypeTemplates[passwordType]
if templates == nil {
return fmt.Sprintf("cannot find password template %s", password_type)
return fmt.Sprintf("cannot find password template %s", passwordType)
}

var buffer bytes.Buffer
buffer.WriteString(master_password_seed)
buffer.WriteString(masterPasswordSeed)
binary.Write(&buffer, binary.BigEndian, uint32(len(user)))
buffer.WriteString(user)

Expand All @@ -95,7 +95,7 @@ func derivePassword(counter uint32, password_type, password, user, site string)
return fmt.Sprintf("failed to derive password: %s", err)
}

buffer.Truncate(len(master_password_seed))
buffer.Truncate(len(masterPasswordSeed))
binary.Write(&buffer, binary.BigEndian, uint32(len(site)))
buffer.WriteString(site)
binary.Write(&buffer, binary.BigEndian, counter)
Expand All @@ -107,9 +107,9 @@ func derivePassword(counter uint32, password_type, password, user, site string)

buffer.Truncate(0)
for i, element := range temp {
pass_chars := template_characters[element]
pass_char := pass_chars[int(seed[i+1])%len(pass_chars)]
buffer.WriteByte(pass_char)
passChars := templateCharacters[element]
passChar := passChars[int(seed[i+1])%len(passChars)]
buffer.WriteByte(passChar)
}

return buffer.String()
Expand Down Expand Up @@ -237,11 +237,8 @@ func generateCertificateAuthority(
}

ca.Cert, ca.Key, err = getCertAndKey(template, priv, template, priv)
if err != nil {
return ca, err
}

return ca, nil
return ca, err
}

func generateSelfSignedCertificate(
Expand All @@ -263,11 +260,8 @@ func generateSelfSignedCertificate(
}

cert.Cert, cert.Key, err = getCertAndKey(template, priv, template, priv)
if err != nil {
return cert, err
}

return cert, nil
return cert, err
}

func generateSignedCertificate(
Expand Down Expand Up @@ -318,11 +312,8 @@ func generateSignedCertificate(
signerCert,
signerKey,
)
if err != nil {
return cert, err
}

return cert, nil
return cert, err
}

func getCertAndKey(
Expand Down Expand Up @@ -361,7 +352,7 @@ func getCertAndKey(
return "", "", fmt.Errorf("error pem-encoding key: %s", err)
}

return string(certBuffer.Bytes()), string(keyBuffer.Bytes()), nil
return certBuffer.String(), keyBuffer.String(), nil
}

func getBaseCertTemplate(
Expand Down
2 changes: 1 addition & 1 deletion crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func TestGenPrivateKey(t *testing.T) {
}
// ensure that we can base64 encode the string
tpl = `{{genPrivateKey "rsa" | b64enc}}`
out, err = runRaw(tpl, nil)
_, err = runRaw(tpl, nil)
if err != nil {
t.Error(err)
}
Expand Down
12 changes: 12 additions & 0 deletions date.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ func dateModify(fmt string, date time.Time) time.Time {
return date.Add(d)
}

func mustDateModify(fmt string, date time.Time) (time.Time, error) {
d, err := time.ParseDuration(fmt)
if err != nil {
return time.Time{}, err
}
return date.Add(d), nil
}

func dateAgo(date interface{}) string {
var t time.Time

Expand All @@ -78,6 +86,10 @@ func toDate(fmt, str string) time.Time {
return t
}

func mustToDate(fmt, str string) (time.Time, error) {
return time.ParseInLocation(fmt, str, time.Local)
}

func unixEpoch(date time.Time) string {
return strconv.FormatInt(date.Unix(), 10)
}
18 changes: 17 additions & 1 deletion defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func empty(given interface{}) bool {
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
return g.Len() == 0
case reflect.Bool:
return g.Bool() == false
return !g.Bool()
case reflect.Complex64, reflect.Complex128:
return g.Complex() == 0
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
Expand Down Expand Up @@ -67,12 +67,28 @@ func toJson(v interface{}) string {
return string(output)
}

func mustToJson(v interface{}) (string, error) {
output, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(output), nil
}

// toPrettyJson encodes an item into a pretty (indented) JSON string
func toPrettyJson(v interface{}) string {
output, _ := json.MarshalIndent(v, "", " ")
return string(output)
}

func mustToPrettyJson(v interface{}) (string, error) {
output, err := json.MarshalIndent(v, "", " ")
if err != nil {
return "", err
}
return string(output), nil
}

// ternary returns the first value if the last value is true, otherwise returns the second value.
func ternary(vt interface{}, vf interface{}, v bool) interface{} {
if v {
Expand Down
24 changes: 21 additions & 3 deletions dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,32 @@ func merge(dst map[string]interface{}, srcs ...map[string]interface{}) interface
return dst
}

func mustMerge(dst map[string]interface{}, srcs ...map[string]interface{}) (interface{}, error) {
for _, src := range srcs {
if err := mergo.Merge(&dst, src); err != nil {
return nil, err
}
}
return dst, nil
}

func mergeOverwrite(dst map[string]interface{}, srcs ...map[string]interface{}) interface{} {
for _, src := range srcs {
for _, src := range srcs {
if err := mergo.MergeWithOverwrite(&dst, src); err != nil {
// Swallow errors inside of a template.
return ""
}
}
return dst
}
return dst
}

func mustMergeOverwrite(dst map[string]interface{}, srcs ...map[string]interface{}) (interface{}, error) {
for _, src := range srcs {
if err := mergo.MergeWithOverwrite(&dst, src); err != nil {
return nil, err
}
}
return dst, nil
}

func values(dict map[string]interface{}) []interface{} {
Expand Down
6 changes: 4 additions & 2 deletions docs/date.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Returns the seconds since the unix epoch for a `time.Time`.
now | unixEpoch
```

## dateModify
## dateModify, mustDateModify

The `dateModify` takes a modification and a date and returns the timestamp.

Expand All @@ -64,6 +64,7 @@ Subtract an hour and thirty minutes from the current time:
```
now | date_modify "-1.5h"
```
If the modification format is wrong `dateModify` will return the date unmodified. `mustDateModify` will return an error otherwise.

## htmlDate

Expand All @@ -82,11 +83,12 @@ Same as htmlDate, but with a timezone.
htmlDate (now) "UTC"
```

## toDate
## toDate, mustToDate

`toDate` converts a string to a date. The first argument is the date layout and
the second the date string. If the string can't be convert it returns the zero
value.
`mustToDate` will return an error in case the string cannot be converted.

This is useful when you want to convert a string date to another format
(using pipe). The example below converts "2017-12-31" to "31/12/2017".
Expand Down
7 changes: 4 additions & 3 deletions docs/defaults.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,18 @@ The above will first check to see if `.name` is empty. If it is not, it will ret
that value. If it _is_ empty, `coalesce` will evaluate `.parent.name` for emptiness.
Finally, if both `.name` and `.parent.name` are empty, it will return `Matt`.

## toJson
## toJson, mustToJson

The `toJson` function encodes an item into a JSON string.
The `toJson` function encodes an item into a JSON string. If the item cannot be converted to JSON the function will return an empty string.
`mustToJson` will return an error in case the item cannot be encoded in JSON.

```
toJson .Item
```

The above returns JSON string representation of `.Item`.

## toPrettyJson
## toPrettyJson, mustToPrettyJson

The `toPrettyJson` function encodes an item into a pretty (indented) JSON string.

Expand Down
8 changes: 6 additions & 2 deletions docs/dicts.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ inserted.
A common idiom in Sprig templates is to uses `pluck... | first` to get the first
matching key out of a collection of dictionaries.

## merge
## merge, mustMerge

Merge two or more dictionaries into one, giving precedence to the dest dictionary:

Expand All @@ -85,7 +85,9 @@ $newdict := merge $dest $source1 $source2

This is a deep merge operation.

## mergeOverwrite
`mustMerge` will return an error in case of unsuccessful merge.

## mergeOverwrite, mustMergeOverwrite

Merge two or more dictionaries into one, giving precedence from **right to left**, effectively
overwriting values in the dest dictionary:
Expand Down Expand Up @@ -118,6 +120,8 @@ $newdict := mergeOverwrite $dest $source1 $source2

This is a deep merge operation.

`mustMergeOverwrite` will return an error in case of unsuccessful merge.

## keys

The `keys` function will return a `list` of all of the keys in one or more `dict`
Expand Down
Loading