-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthentication_test.go
165 lines (141 loc) · 4.75 KB
/
authentication_test.go
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
31
32
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package webauthn
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/assert"
)
func TestBeginAuthentication(t *testing.T) {
// Setup
app := fiber.New()
config := Config{
RPDisplayName: "Test App",
RPID: "localhost",
RPOrigins: []string{"http://localhost"},
CredentialStore: &mockCredentialStore{
credentials: map[string][]*Credential{
"test-user": {
{
ID: []byte("test-credential-id"),
PublicKey: []byte("test-public-key"),
AttestationType: "none",
},
},
},
},
}
mw := New(config)
app.Post("/login/begin", mw.BeginAuthentication())
// Test case 1: Successful authentication initiation
reqBody := `{"userId": "test-user"}`
req := httptest.NewRequest("POST", "/login/begin", bytes.NewBufferString(reqBody))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
var result map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
assert.NoError(t, err)
// Verify response contains required fields
assert.Contains(t, result, "publicKey")
publicKey := result["publicKey"].(map[string]interface{})
assert.Contains(t, publicKey, "challenge")
assert.Contains(t, publicKey, "allowCredentials")
// Test case 2: User with no credentials
reqBody = `{"userId": "user-without-creds"}`
req = httptest.NewRequest("POST", "/login/begin", bytes.NewBufferString(reqBody))
req.Header.Set("Content-Type", "application/json")
resp, err = app.Test(req)
assert.NoError(t, err)
assert.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
var errorResult map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&errorResult)
assert.NoError(t, err)
assert.Equal(t, "no credentials found for user", errorResult["error"])
}
func TestFinishAuthentication(t *testing.T) {
// Setup
app := fiber.New()
config := Config{
RPDisplayName: "Test App",
RPID: "localhost",
RPOrigins: []string{"http://localhost"},
CredentialStore: &mockCredentialStore{
credentials: map[string][]*Credential{
"test-user": {
{
ID: []byte("test-credential-id"),
PublicKey: []byte("test-public-key"),
AttestationType: "none",
SignCount: 0,
},
},
},
},
}
mw := New(config)
// Store test session
sessionID := "test-session"
sessionData := &webauthn.SessionData{
Challenge: "test-challenge",
UserID: []byte("test-user"),
}
err := mw.sessions.StoreSession(sessionID, &SessionData{
UserID: "test-user",
Challenge: sessionData.Challenge,
SessionData: *sessionData,
ExpiresAt: time.Now().Add(5 * time.Minute),
})
assert.NoError(t, err)
app.Post("/login/finish", mw.FinishAuthentication())
// Create mock assertion response
mockResponse := createMockAssertionResponse(t, sessionData.Challenge)
// Test case 1: Successful authentication completion
req := httptest.NewRequest("POST", "/login/finish", bytes.NewReader(mockResponse))
req.AddCookie(&http.Cookie{
Name: "webauthn_session",
Value: sessionID,
})
resp, err := app.Test(req)
assert.NoError(t, err)
// Note: The actual status will be unauthorized because we're using mock data
// In a real scenario, the webauthn library would validate the credential
assert.Equal(t, fiber.StatusUnauthorized, resp.StatusCode)
// Test case 2: Missing session cookie
req = httptest.NewRequest("POST", "/login/finish", bytes.NewReader(mockResponse))
resp, err = app.Test(req)
assert.NoError(t, err)
assert.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
var errorResult map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&errorResult)
assert.NoError(t, err)
assert.Equal(t, "no session found", errorResult["error"])
}
// Helper function to create mock assertion response
func createMockAssertionResponse(t *testing.T, challenge string) []byte {
response := map[string]interface{}{
"id": base64.URLEncoding.EncodeToString([]byte("test-credential-id")),
"rawId": base64.URLEncoding.EncodeToString([]byte("test-credential-id")),
"type": "public-key",
"response": map[string]interface{}{
"authenticatorData": base64.URLEncoding.EncodeToString([]byte("test-auth-data")),
"clientDataJSON": base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`{
"type": "webauthn.get",
"challenge": "%s",
"origin": "http://localhost"
}`, challenge))),
"signature": base64.URLEncoding.EncodeToString([]byte("test-signature")),
"userHandle": base64.URLEncoding.EncodeToString([]byte("test-user")),
},
}
data, err := json.Marshal(response)
assert.NoError(t, err)
return data
}