-
Notifications
You must be signed in to change notification settings - Fork 0
/
mini.go
184 lines (151 loc) · 4.54 KB
/
mini.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package tmpauth
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"sync"
"time"
)
type MiniConfig struct {
PublicKey string `json:"publicKey"`
Secret string `json:"secret"`
AllowedUsers []string `json:"allowedUsers"`
IDFormats []string `json:"idFormats"`
Except []string `json:"except"`
Include []string `json:"include"`
Headers map[string]*HeaderOption `json:"headers"`
Redirect string `json:"redirect"`
Host string `json:"host"`
Debug bool `json:"debug"`
CaseSensitiveMatching bool `json:"caseSensitiveMatching"`
MiniServerHost string `json:"miniServerHost,omitempty"`
}
type RemoteConfig struct {
ConfigID string
ClientID string
Secret []byte
}
func NewMini(config MiniConfig, next CaddyHandleFunc) (*Tmpauth, error) {
var lastErr error
var remoteConfig RemoteConfig
miniServerHost := config.MiniServerHost
config.MiniServerHost = ""
if miniServerHost == "" {
return nil, fmt.Errorf("miniServerHost is empty and must be set")
}
tmpauthConfig, err := json.Marshal(config)
if err != nil {
return nil, fmt.Errorf("failed to marshal config: %w", err)
}
for i := 0; i < 5; i++ {
req, err := http.NewRequest(http.MethodPut, miniServerHost+"/config", bytes.NewReader(tmpauthConfig))
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
lastErr = err
time.Sleep(3 * time.Second)
continue
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
lastErr = fmt.Errorf("unexpected status code: %d", resp.StatusCode)
time.Sleep(3 * time.Second)
continue
}
lastErr = json.NewDecoder(resp.Body).Decode(&remoteConfig)
if lastErr != nil {
time.Sleep(3 * time.Second)
continue
}
break
}
if lastErr != nil {
return nil, lastErr
}
log.Println("registered mini client with config ID:", remoteConfig.ConfigID)
t := &Tmpauth{
Next: next,
Config: &Config{
Secret: remoteConfig.Secret,
ClientID: remoteConfig.ClientID,
Token: config.Secret,
AllowedUsers: config.AllowedUsers,
IDFormats: config.IDFormats,
Except: config.Except,
Include: config.Include,
Headers: config.Headers,
Redirect: config.Redirect,
Debug: config.Debug,
CaseSensitiveMatching: config.CaseSensitiveMatching,
Logger: DefaultLogger,
},
TokenCache: make(map[[32]byte]*CachedToken),
HttpClient: nil, // unused in mini mode
stateIDCache: make(map[string]*StateIDSession),
stateIDMutex: sync.Mutex{},
tokenCacheMutex: sync.RWMutex{},
hmacMutex: sync.Mutex{},
janitorOnce: sync.Once{},
miniServerHost: miniServerHost,
miniConfigID: remoteConfig.ConfigID,
miniConfigJSON: tmpauthConfig,
done: make(chan struct{}),
doneOnce: sync.Once{},
}
transport := &MiniTransport{
base: http.DefaultTransport,
tmpauth: t,
}
t.miniClient = transport.Do
return t, nil
}
func (t *Tmpauth) ReauthMini() error {
log.Println("reauthenticating with mini...")
req, err := http.NewRequest(http.MethodPut, t.miniServerHost+"/config",
bytes.NewReader(t.miniConfigJSON))
if err != nil {
return fmt.Errorf("reauth create request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("reauth error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return nil
}
type MiniTransport struct {
base http.RoundTripper
tmpauth *Tmpauth
}
func (t *MiniTransport) Do(req *http.Request, depth int) (*http.Response, error) {
var body []byte
if req.Body != nil {
var err error
body, err = io.ReadAll(req.Body)
if err != nil {
return nil, fmt.Errorf("mini transport read body: %w", err)
}
req.Body = io.NopCloser(bytes.NewReader(body))
}
resp, err := t.base.RoundTrip(req)
if resp.StatusCode == http.StatusPreconditionFailed {
// our config ID is wrong
err := t.tmpauth.ReauthMini()
if err != nil {
return nil, fmt.Errorf("tmpauth: mini server reauth failed %w", err)
}
if body != nil {
req.Body = io.NopCloser(bytes.NewReader(body))
}
return t.Do(req, depth+1)
}
return resp, err
}