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

Refactor Fastly token #1

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 0 additions & 22 deletions fastlyExp.go

This file was deleted.

39 changes: 39 additions & 0 deletions fastly_exp.go
Original file line number Diff line number Diff line change
@@ -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
}
52 changes: 52 additions & 0 deletions fastly_exp_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}