protocol_test.go 1.92 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
package auth

import (
	"encoding/json"
	"reflect"
	"testing"

	"github.com/tstranex/u2f"
)

func TestProtocol_SerializeRequest(t *testing.T) {
	c := &kvCodec{}

	req := &Request{
		Service:  "service",
		Username: "username",
		Password: []byte("password"),
		OTP:      "123456",
		U2FAppID: "https://appid",
		U2FResponse: &u2f.SignResponse{
			KeyHandle:     "keyHandle",
			SignatureData: "signatureData",
			ClientData:    "clientData",
		},
		DeviceInfo: &DeviceInfo{
			ID:         "ah9hf3kh2",
			RemoteAddr: "1.2.3.4",
			RemoteZone: "cc",
			Browser:    "IE9",
			OS:         "Windows",
ale's avatar
ale committed
31 32
			UserAgent:  "MSIE/9.1 foo/12 bar/13",
			Mobile:     true,
ale's avatar
ale committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
		},
	}

	b := c.Encode(req)

	var req2 Request
	err := c.Decode(b, &req2)
	if err != nil {
		t.Fatal("Decode():", err)
	}
	if !reflect.DeepEqual(req, &req2) {
		d1, _ := json.MarshalIndent(req, "", "    ")
		d2, _ := json.MarshalIndent(req2, "", "    ")
		t.Errorf("decode results differ: %+v vs %+v", string(d1), string(d2))
	}
}

func TestProtocol_SerializeResponse(t *testing.T) {
	c := &kvCodec{}

	resp := &Response{
		Status:    StatusInsufficientCredentials,
		TFAMethod: TFAMethodU2F,
		U2FSignRequest: &u2f.WebSignRequest{
			AppID:     "https://some-app-id",
			Challenge: "u2fChallenge",
			RegisteredKeys: []u2f.RegisteredKey{
				{
					Version:   "v1",
					KeyHandle: "key1",
					AppID:     "https://other-app-id",
				},
				{
					Version:   "v2",
					KeyHandle: "key2",
					AppID:     "https://some-app-id",
				},
			},
		},
		UserInfo: &UserInfo{
			Email:  "test@example.com",
ale's avatar
ale committed
74
			Shard:  "42",
ale's avatar
ale committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
			Groups: []string{"group1", "group2", "group3"},
		},
	}

	b := c.Encode(resp)

	var resp2 Response
	err := c.Decode(b, &resp2)
	if err != nil {
		t.Fatal("Decode():", err)
	}
	if !reflect.DeepEqual(resp, &resp2) {
		d1, _ := json.MarshalIndent(resp, "", "    ")
		d2, _ := json.MarshalIndent(resp2, "", "    ")
		t.Errorf("decode results differ: %+v vs %+v", string(d1), string(d2))
	}
}