-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathadmin_egress_ips.go
More file actions
329 lines (290 loc) · 10.9 KB
/
Copy pathadmin_egress_ips.go
File metadata and controls
329 lines (290 loc) · 10.9 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package http
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net"
nethttp "net/http"
"strings"
"database/sql"
"github.com/zanel1u/cloud-cli-proxy/internal/store/repository"
)
type AdminEgressIPStore interface {
ListEgressIPs(context.Context) ([]repository.EgressIP, error)
GetEgressIP(context.Context, string) (repository.EgressIP, error)
CreateEgressIP(context.Context, repository.CreateEgressIPParams) (repository.EgressIP, error)
UpdateEgressIP(context.Context, string, repository.UpdateEgressIPParams) (repository.EgressIP, error)
UpdateEgressIPDetectedAddress(ctx context.Context, egressIPID string, detectedIP string) error
DeleteEgressIP(context.Context, string) error
}
type AdminEgressIPsHandler struct {
logger *slog.Logger
store AdminEgressIPStore
events EventRecorder
}
func NewAdminEgressIPsHandler(logger *slog.Logger, store AdminEgressIPStore, events EventRecorder) *AdminEgressIPsHandler {
return &AdminEgressIPsHandler{logger: logger, store: store, events: events}
}
var allowedOutboundTypes = map[string]bool{
"socks": true, "vmess": true, "vless": true, "shadowsocks": true, "trojan": true, "http": true,
}
func validateProxyConfig(raw json.RawMessage) error {
if len(raw) == 0 {
return fmt.Errorf("proxy_config is required for proxy tunnel type")
}
var parsed map[string]any
if err := json.Unmarshal(raw, &parsed); err != nil {
return fmt.Errorf("proxy_config is not valid JSON: %w", err)
}
outboundType, _ := parsed["type"].(string)
if !allowedOutboundTypes[outboundType] {
return fmt.Errorf("unsupported outbound type %q, allowed: socks, vmess, vless, shadowsocks, trojan, http", outboundType)
}
server, _ := parsed["server"].(string)
if server == "" {
return fmt.Errorf("proxy_config.server is required")
}
port, _ := parsed["server_port"].(float64)
if port <= 0 || port > 65535 {
return fmt.Errorf("proxy_config.server_port must be a positive integer (1-65535)")
}
switch outboundType {
case "vmess", "vless":
if uuid, _ := parsed["uuid"].(string); uuid == "" {
return fmt.Errorf("proxy_config.uuid is required for %s", outboundType)
}
case "shadowsocks":
if method, _ := parsed["method"].(string); method == "" {
return fmt.Errorf("proxy_config.method is required for shadowsocks")
}
if password, _ := parsed["password"].(string); password == "" {
return fmt.Errorf("proxy_config.password is required for shadowsocks")
}
case "trojan":
if password, _ := parsed["password"].(string); password == "" {
return fmt.Errorf("proxy_config.password is required for trojan")
}
}
return nil
}
func sanitizeProxyConfig(raw json.RawMessage) json.RawMessage {
if raw == nil {
return nil
}
var parsed map[string]any
if err := json.Unmarshal(raw, &parsed); err != nil {
return nil
}
if _, ok := parsed["password"]; ok {
parsed["password"] = "***"
}
sanitized, _ := json.Marshal(parsed)
return sanitized
}
func sanitizeEgressIP(ip *repository.EgressIP) {
ip.ProxyConfig = sanitizeProxyConfig(ip.ProxyConfig)
}
func mergeProxyPassword(ctx context.Context, store AdminEgressIPStore, ipID string, incoming json.RawMessage) json.RawMessage {
var newCfg map[string]any
if err := json.Unmarshal(incoming, &newCfg); err != nil {
return incoming
}
pwd, hasPwd := newCfg["password"]
if !hasPwd || pwd == "***" {
existing, err := store.GetEgressIP(ctx, ipID)
if err != nil || existing.ProxyConfig == nil {
return incoming
}
var oldCfg map[string]any
if err := json.Unmarshal(existing.ProxyConfig, &oldCfg); err != nil {
return incoming
}
if origPwd, ok := oldCfg["password"]; ok {
newCfg["password"] = origPwd
merged, _ := json.Marshal(newCfg)
return merged
}
}
return incoming
}
func (h *AdminEgressIPsHandler) List() nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
ips, err := h.store.ListEgressIPs(r.Context())
if err != nil {
h.logger.Error("list egress ips failed", "error", err)
writeJSON(w, nethttp.StatusInternalServerError, map[string]string{"error": "list egress ips failed"})
return
}
for i := range ips {
sanitizeEgressIP(&ips[i])
}
writeJSON(w, nethttp.StatusOK, map[string]any{"egress_ips": ips})
})
}
func (h *AdminEgressIPsHandler) Get() nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
ipID := r.PathValue("ipID")
ip, err := h.store.GetEgressIP(r.Context(), ipID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
writeJSON(w, nethttp.StatusNotFound, map[string]string{"error": "egress ip not found"})
return
}
h.logger.Error("get egress ip failed", "ip_id", ipID, "error", err)
writeJSON(w, nethttp.StatusInternalServerError, map[string]string{"error": "get egress ip failed"})
return
}
sanitizeEgressIP(&ip)
writeJSON(w, nethttp.StatusOK, map[string]any{"egress_ip": ip})
})
}
type createEgressIPRequest struct {
Label string `json:"label"`
IPAddress string `json:"ip_address"`
Provider string `json:"provider"`
ProxyConfig json.RawMessage `json:"proxy_config,omitempty"`
}
func (h *AdminEgressIPsHandler) Create() nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
var req createEgressIPRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, nethttp.StatusBadRequest, map[string]string{"error": "invalid request body"})
return
}
req.Label = strings.TrimSpace(req.Label)
if req.Label == "" {
writeJSON(w, nethttp.StatusBadRequest, map[string]string{"error": "label is required"})
return
}
req.IPAddress = strings.TrimSpace(req.IPAddress)
if req.IPAddress != "" && net.ParseIP(req.IPAddress) == nil {
writeJSON(w, nethttp.StatusBadRequest, map[string]string{"error": "invalid ip address"})
return
}
if req.Provider == "" {
req.Provider = "manual"
}
if err := validateProxyConfig(req.ProxyConfig); err != nil {
writeJSON(w, nethttp.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
ip, err := h.store.CreateEgressIP(r.Context(), repository.CreateEgressIPParams{
Label: req.Label,
IPAddress: req.IPAddress,
Provider: req.Provider,
ProxyConfig: req.ProxyConfig,
})
if err != nil {
errMsg := strings.ToLower(err.Error())
if strings.Contains(errMsg, "unique") || strings.Contains(errMsg, "constraint failed") || strings.Contains(errMsg, "duplicate") {
writeJSON(w, nethttp.StatusConflict, map[string]string{"error": "label already exists"})
return
}
h.logger.Error("create egress ip failed", "error", err)
writeJSON(w, nethttp.StatusInternalServerError, map[string]string{"error": "create egress ip failed"})
return
}
if h.events != nil {
if _, err := h.events.RecordEvent(r.Context(), repository.RecordEventParams{
Level: "info",
Type: "admin.egress_ip.created",
Message: "管理员创建出口 IP 资源",
Metadata: map[string]any{"operator": "admin", "egress_ip_id": ip.ID, "label": ip.Label, "ip_address": ip.IPAddress},
}); err != nil {
h.logger.Error("record event failed", "type", "admin.egress_ip.created", "error", err)
}
}
sanitizeEgressIP(&ip)
writeJSON(w, nethttp.StatusCreated, map[string]any{"egress_ip": ip})
})
}
type updateEgressIPRequest struct {
Label string `json:"label"`
IPAddress string `json:"ip_address"`
Provider string `json:"provider"`
Status string `json:"status"`
ProxyConfig json.RawMessage `json:"proxy_config,omitempty"`
}
func (h *AdminEgressIPsHandler) Update() nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
ipID := r.PathValue("ipID")
var req updateEgressIPRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, nethttp.StatusBadRequest, map[string]string{"error": "invalid request body"})
return
}
if req.Status != "" && req.Status != "available" && req.Status != "disabled" {
writeJSON(w, nethttp.StatusBadRequest, map[string]string{"error": "status must be available or disabled"})
return
}
req.ProxyConfig = mergeProxyPassword(r.Context(), h.store, ipID, req.ProxyConfig)
if err := validateProxyConfig(req.ProxyConfig); err != nil {
writeJSON(w, nethttp.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
ip, err := h.store.UpdateEgressIP(r.Context(), ipID, repository.UpdateEgressIPParams{
Label: req.Label,
IPAddress: req.IPAddress,
Provider: req.Provider,
Status: req.Status,
ProxyConfig: req.ProxyConfig,
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
writeJSON(w, nethttp.StatusNotFound, map[string]string{"error": "egress ip not found"})
return
}
errMsg := strings.ToLower(err.Error())
if strings.Contains(errMsg, "unique") || strings.Contains(errMsg, "constraint failed") || strings.Contains(errMsg, "duplicate") {
writeJSON(w, nethttp.StatusConflict, map[string]string{"error": "label already exists"})
return
}
h.logger.Error("update egress ip failed", "ip_id", ipID, "error", err)
writeJSON(w, nethttp.StatusInternalServerError, map[string]string{"error": "update egress ip failed"})
return
}
if h.events != nil {
if _, err := h.events.RecordEvent(r.Context(), repository.RecordEventParams{
Level: "info",
Type: "admin.egress_ip.updated",
Message: "管理员更新出口 IP 资源",
Metadata: map[string]any{"operator": "admin", "egress_ip_id": ipID},
}); err != nil {
h.logger.Error("record event failed", "type", "admin.egress_ip.updated", "error", err)
}
}
sanitizeEgressIP(&ip)
writeJSON(w, nethttp.StatusOK, map[string]any{"egress_ip": ip})
})
}
func (h *AdminEgressIPsHandler) Delete() nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
ipID := r.PathValue("ipID")
if err := h.store.DeleteEgressIP(r.Context(), ipID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
writeJSON(w, nethttp.StatusNotFound, map[string]string{"error": "egress ip not found"})
return
}
if strings.Contains(err.Error(), "violates foreign key") || strings.Contains(err.Error(), "restrict") {
writeJSON(w, nethttp.StatusConflict, map[string]string{"error": "egress IP is bound to a host, unbind first"})
return
}
h.logger.Error("delete egress ip failed", "ip_id", ipID, "error", err)
writeJSON(w, nethttp.StatusInternalServerError, map[string]string{"error": "delete egress ip failed"})
return
}
if h.events != nil {
if _, err := h.events.RecordEvent(r.Context(), repository.RecordEventParams{
Level: "info",
Type: "admin.egress_ip.deleted",
Message: "管理员删除出口 IP 资源",
Metadata: map[string]any{"operator": "admin", "egress_ip_id": ipID},
}); err != nil {
h.logger.Error("record event failed", "type", "admin.egress_ip.deleted", "error", err)
}
}
w.WriteHeader(nethttp.StatusNoContent)
})
}