diff --git a/fastlyExp.go b/fastlyExp.go deleted file mode 100644 index 19a99e7..0000000 --- a/fastlyExp.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "encoding/base64" - "encoding/binary" - "encoding/hex" - "fmt" - "os" - "strings" - "time" -) - -func main() { - if len(os.Args) > 1 { - decoded, _ := base64.StdEncoding.DecodeString(strings.Replace(os.Args[1], "%3D", "=", -1)) - token := string(decoded) - byteTime, _ := hex.DecodeString(token[:strings.Index(token, "_")]) - fmt.Println("Token expires:", time.Unix(int64(binary.BigEndian.Uint32(byteTime)), 0)) - } else { - fmt.Println("Missing token.") - } -} diff --git a/fastly_exp.go b/fastly_exp.go new file mode 100644 index 0000000..8b1beb3 --- /dev/null +++ b/fastly_exp.go @@ -0,0 +1,39 @@ +package main + +import ( + "encoding/base64" + "encoding/binary" + "encoding/hex" + "fmt" + "os" + "strings" + "time" +) + +func main() { + if len(os.Args) > 1 { + token, err := decode(os.Args[1]) + if err != nil { + fmt.Printf("Error: %s", err.Error()) + } + fmt.Printf("Token expires: %s", token) + } else { + fmt.Println("Missing token.") + } +} + +// decode a Fastly Token. Returns expiration or error. +func decode(token string) (string, error) { + decoded, err := base64.StdEncoding.DecodeString(strings.Replace(token, "%3D", "=", -1)) + if err != nil { + return "", err + } + + decToken := string(decoded) + byteTime, err := hex.DecodeString(decToken[:strings.Index(decToken, "_")]) + if err != nil { + return "", err + } + + return time.Unix(int64(binary.BigEndian.Uint32(byteTime)), 0).UTC().String(), nil +} diff --git a/fastly_exp_test.go b/fastly_exp_test.go new file mode 100644 index 0000000..658d65e --- /dev/null +++ b/fastly_exp_test.go @@ -0,0 +1,52 @@ +package main + +import "testing" + +func Test_decode(t *testing.T) { + type args struct { + token string + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + { + "success", + args{ + "NWZmY2U4MWFfY2ViMDViZWRkOWYwZTRkY2NkYTIxOWE3NjRhYmNlMjczZWViMWNmYWQ2ZTc4OTQzYmViNTE0YWMwZjBlMjFjNQ%3D%3D", + }, + "2021-01-12 00:06:50 +0000 UTC", + false, + }, + { + "error (not base64)", + args{ + "NWZmY2U4MWFfY2ViM", + }, + "", + true, + }, + { + "error (not hex)", + args{ + "aGVsbG9fdGhlcmU=", + }, + "", + true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := decode(tt.args.token) + if (err != nil) != tt.wantErr { + t.Errorf("decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("decode() = %v, want %v", got, tt.want) + } + }) + } +}