]> git.giacomolli.uk - onechat/blob - chatgpt_fake_helper_test.go
Share general review and documentation rules
[onechat] / chatgpt_fake_helper_test.go
1 package main
2
3 import (
4 "encoding/base64"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "path/filepath"
11 "sync"
12 "testing"
13 "time"
14
15 "github.com/stretchr/testify/require"
16 )
17
18 // chatgptTestAccount is the fake ChatGPT account ID in the fake tokens.
19 const chatgptTestAccount = "account-test"
20
21 // ChatGPTFake is an httptest login service. The device token endpoint answers
22 // 403 pending times before it grants the code. Each token answer has a new
23 // access token, kept in access.
24 type ChatGPTFake struct {
25 *httptest.Server
26 mutex sync.Mutex
27 pending int
28 deny bool
29 polls int
30 exchange url.Values
31 refreshes int
32 refreshed string
33 newRefresh string
34 failRefresh bool
35 access []string
36 }
37
38 func newChatGPTFake(t *testing.T) *ChatGPTFake {
39 t.Helper()
40
41 f := &ChatGPTFake{}
42 mux := http.NewServeMux()
43 mux.HandleFunc("POST /api/accounts/deviceauth/usercode", f.userCode)
44 mux.HandleFunc("POST /api/accounts/deviceauth/token", f.deviceToken)
45 mux.HandleFunc("POST /oauth/token", f.oauthToken)
46
47 f.Server = httptest.NewServer(mux)
48 t.Cleanup(f.Close)
49
50 return f
51 }
52
53 func newTestChatGPTAuth(t *testing.T, server *ChatGPTFake) *ChatGPTAuth {
54 t.Helper()
55
56 return newChatGPTAuth(filepath.Join(t.TempDir(), chatgptTokenFileName), server.URL)
57 }
58
59 func (f *ChatGPTFake) userCode(w http.ResponseWriter, r *http.Request) {
60 var body map[string]string
61
62 err := json.NewDecoder(r.Body).Decode(&body)
63 if err != nil || body["client_id"] != chatgptClientID {
64 http.Error(w, "bad client", http.StatusBadRequest)
65
66 return
67 }
68
69 chatgptWriteJSON(w, map[string]any{
70 "device_auth_id": "device-1",
71 "user_code": "CODE-1234",
72 "interval": "0",
73 })
74 }
75
76 func (f *ChatGPTFake) deviceToken(w http.ResponseWriter, r *http.Request) {
77 f.mutex.Lock()
78 defer f.mutex.Unlock()
79
80 var body map[string]string
81
82 err := json.NewDecoder(r.Body).Decode(&body)
83 if err != nil || body["device_auth_id"] != "device-1" || body["user_code"] != "CODE-1234" {
84 http.Error(w, "bad device", http.StatusBadRequest)
85
86 return
87 }
88
89 f.polls++
90 if f.deny {
91 http.Error(w, "denied", http.StatusBadRequest)
92
93 return
94 }
95
96 if f.polls <= f.pending {
97 http.Error(w, "pending", http.StatusForbidden)
98
99 return
100 }
101
102 chatgptWriteJSON(w, map[string]any{
103 "authorization_code": "auth-code",
104 "code_challenge": "challenge",
105 "code_verifier": "verifier",
106 })
107 }
108
109 func (f *ChatGPTFake) oauthToken(w http.ResponseWriter, r *http.Request) {
110 f.mutex.Lock()
111 defer f.mutex.Unlock()
112
113 if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
114 err := r.ParseForm()
115 if err != nil {
116 http.Error(w, err.Error(), http.StatusBadRequest)
117
118 return
119 }
120
121 f.exchange = r.PostForm
122 chatgptWriteJSON(w, map[string]any{
123 "access_token": f.newToken(time.Hour),
124 "refresh_token": "refresh-1",
125 "id_token": f.newToken(time.Hour),
126 })
127
128 return
129 }
130
131 var body map[string]string
132
133 err := json.NewDecoder(r.Body).Decode(&body)
134 if err != nil || body["grant_type"] != "refresh_token" || body["client_id"] != chatgptClientID {
135 http.Error(w, "bad refresh", http.StatusBadRequest)
136
137 return
138 }
139
140 f.refreshes++
141 f.refreshed = body["refresh_token"]
142 if f.failRefresh {
143 http.Error(w, `{"error": "invalid_grant", "token": "`+body["refresh_token"]+`"}`, http.StatusUnauthorized)
144
145 return
146 }
147
148 answer := map[string]any{
149 "access_token": f.newToken(time.Hour),
150 "id_token": f.newToken(time.Hour),
151 }
152
153 if f.newRefresh != "" {
154 answer["refresh_token"] = f.newRefresh
155 }
156
157 chatgptWriteJSON(w, answer)
158 }
159
160 // newToken returns a new fake JWT with the expiry and the account claim, and
161 // keeps it in access. The caller holds the mutex.
162 func (f *ChatGPTFake) newToken(ttl time.Duration) string {
163 claims, err := json.Marshal(map[string]any{
164 "exp": time.Now().Add(ttl).Unix(),
165 chatgptAuthClaim: map[string]any{
166 "chatgpt_account_id": chatgptTestAccount,
167 },
168 "serial": len(f.access),
169 })
170 if err != nil {
171 panic(err)
172 }
173
174 encode := base64.RawURLEncoding.EncodeToString
175 token := encode([]byte(`{"alg":"none"}`)) + "." + encode(claims) + "." + encode([]byte("fake"))
176 f.access = append(f.access, token)
177
178 return token
179 }
180
181 // token returns a new access token that expires after ttl, for a token file
182 // that a test writes.
183 func (f *ChatGPTFake) token(ttl time.Duration) string {
184 f.mutex.Lock()
185 defer f.mutex.Unlock()
186
187 return f.newToken(ttl)
188 }
189
190 func chatgptWriteJSON(w http.ResponseWriter, value any) {
191 w.Header().Set("Content-Type", "application/json")
192
193 err := json.NewEncoder(w).Encode(value)
194 if err != nil {
195 panic(fmt.Sprint("encode answer: ", err))
196 }
197 }
198
199 func chatgptWriteTestTokens(t *testing.T, auth *ChatGPTAuth, access, refresh string) {
200 t.Helper()
201
202 err := auth.write(ChatGPTTokenFile{
203 AccessToken: access,
204 RefreshToken: refresh,
205 IDToken: access,
206 AccountID: chatgptTestAccount,
207 })
208 require.NoError(t, err)
209 }