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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
diff --git a/oauth/handler.go b/oauth/handler.go
index cfb8862..49998c3 100644
--- a/oauth/handler.go
+++ b/oauth/handler.go
@@ -7,6 +7,7 @@ import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
+ "crypto/subtle"
"encoding/base64"
"encoding/json"
"fmt"
@@ -502,6 +503,26 @@ func (h *Handler) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(html))
}
+// validateAuthCode binds an authorization code to its client and S256 PKCE verifier.
+func validateAuthCode(code *database.AuthCode, clientID, verifier string) error {
+ if clientID == "" || clientID != code.ClientID {
+ return fmt.Errorf("client_id does not match authorization code")
+ }
+ if code.CodeChallengeMethod != "S256" {
+ return fmt.Errorf("authorization code requires S256 PKCE")
+ }
+ if len(verifier) < 43 || len(verifier) > 128 ||
+ strings.Trim(verifier, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") != "" {
+ return fmt.Errorf("invalid PKCE verifier")
+ }
+ hash := sha256.Sum256([]byte(verifier))
+ challenge := base64.RawURLEncoding.EncodeToString(hash[:])
+ if subtle.ConstantTimeCompare([]byte(challenge), []byte(code.CodeChallenge)) != 1 {
+ return fmt.Errorf("PKCE verifier does not match authorization code")
+ }
+ return nil
+}
+
func (h *Handler) handleToken(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
@@ -524,6 +545,9 @@ func (h *Handler) handleToken(w http.ResponseWriter, r *http.Request) {
if result.Error != nil {
return result.Error
}
+ if err := validateAuthCode(&authCode, r.FormValue("client_id"), r.FormValue("code_verifier")); err != nil {
+ return err
+ }
// Delete the auth code immediately to prevent reuse
if err := tx.Delete(&authCode).Error; err != nil {
@@ -1050,6 +1074,9 @@ func (h *Handler) handleAuthToken(w http.ResponseWriter, r *http.Request) {
if err := tx.Where("code = ? AND expires_at > ?", req.Code, time.Now()).First(&authCode).Error; err != nil {
return err
}
+ if err := validateAuthCode(&authCode, req.ClientID, req.CodeVerifier); err != nil {
+ return err
+ }
// Delete the auth code immediately to prevent reuse
if err := tx.Delete(&authCode).Error; err != nil {
diff --git a/oauth/handler_test.go b/oauth/handler_test.go
new file mode 100644
index 0000000..8b1be2a
--- /dev/null
+++ b/oauth/handler_test.go
@@ -0,0 +1,166 @@
+package oauth
+
+import (
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/ahyattdev/minimal-fxa-server/database"
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+)
+
+// RFC 7636, Appendix B.
+const testVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
+const testChallenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
+
+func TestValidateAuthCode(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ verifier string
+ valid bool
+ }{
+ {"RFC 7636 vector", testVerifier, true},
+ {"maximum length", strings.Repeat("a", 128), true},
+ {"all unreserved characters", strings.Repeat("a", 43) + "AZaz09-._~", true},
+ {"empty", "", false},
+ {"too short", strings.Repeat("a", 42), false},
+ {"too long", strings.Repeat("a", 129), false},
+ {"invalid character", strings.Repeat("a", 43) + "+", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ hash := sha256.Sum256([]byte(tc.verifier))
+ challenge := base64.RawURLEncoding.EncodeToString(hash[:])
+ if tc.verifier == testVerifier && challenge != testChallenge {
+ t.Fatal("incorrect RFC 7636 test vector")
+ }
+ code := database.AuthCode{ClientID: "firefox", CodeChallenge: challenge, CodeChallengeMethod: "S256"}
+ if err := validateAuthCode(&code, "firefox", tc.verifier); (err == nil) != tc.valid {
+ t.Fatalf("valid = %v, error = %v", tc.valid, err)
+ }
+ })
+ }
+}
+
+// Run with FXA_TEST_DATABASE_URI pointing to a disposable PostgreSQL database.
+// The tables are migrated once; each case runs in a rolled-back transaction.
+func TestAuthorizationCodeExchange(t *testing.T) {
+ dsn := os.Getenv("FXA_TEST_DATABASE_URI")
+ if dsn == "" {
+ t.Skip("set FXA_TEST_DATABASE_URI to a disposable PostgreSQL database")
+ }
+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ sqlDB, err := db.DB()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { sqlDB.Close() })
+ if err := db.AutoMigrate(&database.AuthCode{}, &database.User{}, &database.OAuthToken{}); err != nil {
+ t.Fatal(err)
+ }
+ key, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, endpoint := range []string{"/oauth/v1/token", "/auth/v1/oauth/token"} {
+ for _, tc := range []struct {
+ name string
+ clientID string
+ verifier string
+ challenge string
+ method string
+ status int
+ }{
+ {"valid S256", "firefox", testVerifier, testChallenge, "S256", http.StatusOK},
+ {"wrong verifier", "firefox", strings.Repeat("x", 43), testChallenge, "S256", http.StatusBadRequest},
+ {"missing verifier", "firefox", "", testChallenge, "S256", http.StatusBadRequest},
+ {"wrong client", "another-client", testVerifier, testChallenge, "S256", http.StatusBadRequest},
+ {"missing client", "", testVerifier, testChallenge, "S256", http.StatusBadRequest},
+ {"missing challenge", "firefox", testVerifier, "", "S256", http.StatusBadRequest},
+ {"missing method", "firefox", testVerifier, testChallenge, "", http.StatusBadRequest},
+ {"plain downgrade", "firefox", testVerifier, testVerifier, "plain", http.StatusBadRequest},
+ } {
+ t.Run(endpoint+"/"+tc.name, func(t *testing.T) {
+ tx := db.Begin()
+ if tx.Error != nil {
+ t.Fatal(tx.Error)
+ }
+ t.Cleanup(func() { tx.Rollback() })
+ code := database.AuthCode{
+ Code: "test-code", ClientID: "firefox", UserID: "test-user",
+ CodeChallenge: tc.challenge, CodeChallengeMethod: tc.method,
+ ExpiresAt: time.Now().Add(time.Minute),
+ }
+ if err := tx.Create(&code).Error; err != nil {
+ t.Fatal(err)
+ }
+ mux := http.NewServeMux()
+ NewHandler("https://example.invalid", nil, tx, key, VAPIDConfig{}).RegisterRoutes(mux)
+ values := url.Values{
+ "grant_type": {"authorization_code"}, "code": {code.Code},
+ "client_id": {tc.clientID}, "code_verifier": {tc.verifier},
+ }
+ body, contentType := values.Encode(), "application/x-www-form-urlencoded"
+ if endpoint == "/auth/v1/oauth/token" {
+ payload := make(map[string]string)
+ for k := range values {
+ payload[k] = values.Get(k)
+ }
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, contentType = string(encoded), "application/json"
+ }
+ r := httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(body))
+ r.Header.Set("Content-Type", contentType)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, r)
+ if w.Code != tc.status {
+ t.Fatalf("status = %d, want %d", w.Code, tc.status)
+ }
+ var response map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ var remaining, tokens int64
+ if err := tx.Model(&database.AuthCode{}).Where("code = ?", code.Code).Count(&remaining).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Model(&database.OAuthToken{}).Where("user_id = ?", code.UserID).Count(&tokens).Error; err != nil {
+ t.Fatal(err)
+ }
+ if tc.status == http.StatusOK {
+ if response["access_token"] == nil || remaining != 0 || tokens != 1 {
+ t.Fatal("valid exchange must issue a token and consume the code")
+ }
+ replay := httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(body))
+ replay.Header.Set("Content-Type", contentType)
+ replayResponse := httptest.NewRecorder()
+ mux.ServeHTTP(replayResponse, replay)
+ if replayResponse.Code != http.StatusBadRequest {
+ t.Fatal("consumed authorization code must not be reusable")
+ }
+ if err := tx.Model(&database.OAuthToken{}).Where("user_id = ?", code.UserID).Count(&tokens).Error; err != nil || tokens != 1 {
+ t.Fatalf("replay issued another token: count=%d, error=%v", tokens, err)
+ }
+ } else if response["error"] != "invalid_grant" || remaining != 1 || tokens != 0 {
+ t.Fatal("invalid exchange must preserve the code and issue no tokens")
+ }
+ })
+ }
+ }
+}