ZoneCloudflareServer.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. package server
  2. import (
  3. "bytes"
  4. "cfTest/cloudflareApi/zone"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "github.com/cloudflare/cloudflare-go"
  10. "github.com/samber/lo"
  11. "io"
  12. "io/ioutil"
  13. "log"
  14. "net/http"
  15. "strings"
  16. "time"
  17. )
  18. type ZoneServer struct {
  19. zone.UnimplementedZoneCloudflareServer
  20. }
  21. type Subscription struct {
  22. ID string `json:"id"`
  23. RatePlan struct {
  24. ID string `json:"id"`
  25. PublicName string `json:"public_name"`
  26. Currency string `json:"currency"`
  27. Scope string `json:"scope"`
  28. ExternallyManaged bool `json:"externally_managed"`
  29. Sets []string `json:"sets"`
  30. IsContract bool `json:"is_contract"`
  31. } `json:"rate_plan"`
  32. ComponentValues []struct {
  33. Name string `json:"name"`
  34. Value int `json:"value"`
  35. Default int `json:"default,omitempty"`
  36. } `json:"component_values"`
  37. Zone struct {
  38. ID string `json:"id"`
  39. Name string `json:"name"`
  40. } `json:"zone"`
  41. Frequency string `json:"frequency"`
  42. Currency string `json:"currency"`
  43. Price int `json:"price"`
  44. Product struct {
  45. Name string `json:"name"`
  46. Period string `json:"period"`
  47. Billing string `json:"billing"`
  48. PublicName string `json:"public_name"`
  49. Duration int `json:"duration"`
  50. } `json:"product"`
  51. CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
  52. CreatedDate time.Time `json:"created_date"`
  53. }
  54. var ArgoSubscriptionId = "argo_zone_ent_tryout"
  55. const TOKEN_PREFIX = "#pt"
  56. const TOKEN_PREFIX_LENGTH = 3
  57. var (
  58. api *cloudflare.API
  59. err error
  60. )
  61. func (s *ZoneServer) GetArgoSettingSubscription(ctx context.Context, request *zone.IdRequest) (*zone.ArgoSetting, error) {
  62. //设置HTTP请求
  63. client := &http.Client{}
  64. req, err := http.NewRequest("GET", "https://api.cloudflare.com/client/v4/zones/"+request.ZoneId+"/subscriptions", nil)
  65. if err != nil {
  66. return nil, err
  67. }
  68. if strings.HasPrefix(request.GetApiKey(), TOKEN_PREFIX) {
  69. req.Header.Add("Authorization", ApiToken2Authorization(request.GetApiKey()[TOKEN_PREFIX_LENGTH:]))
  70. } else {
  71. req.Header.Add("X-Auth-Key", request.GetApiKey())
  72. req.Header.Add("X-Auth-Email", request.GetApiEmail())
  73. }
  74. //执行HTTP请求
  75. resp, err := client.Do(req)
  76. if err != nil {
  77. return nil, err
  78. }
  79. defer func(Body io.ReadCloser) {
  80. _ = Body.Close()
  81. }(resp.Body)
  82. body, _ := ioutil.ReadAll(resp.Body)
  83. type ResponseType struct {
  84. Errors []interface{} `json:"errors"`
  85. Messages []interface{} `json:"messages"`
  86. Result []Subscription `json:"result"`
  87. ResultInfo struct {
  88. NextPage bool `json:"next_page"`
  89. } `json:"result_info"`
  90. Success bool `json:"success"`
  91. }
  92. var r ResponseType
  93. err = json.Unmarshal(body, &r)
  94. //处理返回逻辑
  95. if err != nil {
  96. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  97. }
  98. if r.Success != true {
  99. return nil, fmt.Errorf("%s", r.Errors)
  100. }
  101. log.Printf("Response: %v", r)
  102. for _, v := range r.Result {
  103. if v.RatePlan.ID == ArgoSubscriptionId {
  104. return &zone.ArgoSetting{Enabled: true}, nil
  105. }
  106. }
  107. return &zone.ArgoSetting{Enabled: false}, nil
  108. }
  109. func (s *ZoneServer) CreateArgoSettingSubscription(ctx context.Context, request *zone.IdRequest) (*zone.ArgoSetting, error) {
  110. type RequestType struct {
  111. RatePlan struct {
  112. ID string `json:"id"`
  113. } `json:"rate_plan"`
  114. Zone struct {
  115. ID string `json:"id"`
  116. Name string `json:"name"`
  117. } `json:"zone"`
  118. }
  119. type ResponseType struct {
  120. Errors []interface{} `json:"errors"`
  121. Messages []interface{} `json:"messages"`
  122. Result Subscription `json:"result"`
  123. Success bool `json:"success"`
  124. }
  125. bytesData, err := json.Marshal(RequestType{
  126. RatePlan: struct {
  127. ID string `json:"id"`
  128. }{
  129. ID: ArgoSubscriptionId,
  130. },
  131. Zone: struct {
  132. ID string `json:"id"`
  133. Name string `json:"name"`
  134. }{
  135. ID: request.ZoneId,
  136. },
  137. })
  138. if err != nil {
  139. return nil, err
  140. }
  141. //设置HTTP请求
  142. client := &http.Client{}
  143. req, err := http.NewRequest("POST", "https://api.cloudflare.com/client/v4/zones/"+request.ZoneId+"/subscription", bytes.NewReader(bytesData))
  144. if err != nil {
  145. return nil, err
  146. }
  147. if strings.HasPrefix(request.GetApiKey(), TOKEN_PREFIX) {
  148. req.Header.Add("Authorization", ApiToken2Authorization(request.GetApiKey()[TOKEN_PREFIX_LENGTH:]))
  149. } else {
  150. req.Header.Add("X-Auth-Key", request.GetApiKey())
  151. req.Header.Add("X-Auth-Email", request.GetApiEmail())
  152. }
  153. //执行HTTP请求
  154. resp, err := client.Do(req)
  155. if err != nil {
  156. return nil, err
  157. }
  158. defer func(Body io.ReadCloser) {
  159. _ = Body.Close()
  160. }(resp.Body)
  161. body, _ := ioutil.ReadAll(resp.Body)
  162. var r ResponseType
  163. err = json.Unmarshal(body, &r)
  164. //处理返回逻辑
  165. if err != nil {
  166. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  167. }
  168. if r.Success != true {
  169. return nil, fmt.Errorf("%s", r.Errors)
  170. }
  171. log.Printf("Response: %v", r)
  172. if r.Result.RatePlan.ID == ArgoSubscriptionId {
  173. return &zone.ArgoSetting{Enabled: true}, nil
  174. }
  175. return &zone.ArgoSetting{Enabled: false}, nil
  176. }
  177. func (s *ZoneServer) UpdateArgoSetting(ctx context.Context, requestCloudflare *zone.UpdateArgoRequestCloudflare) (*zone.ArgoSetting, error) {
  178. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  179. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  180. } else {
  181. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  182. }
  183. if err != nil {
  184. return nil, err
  185. }
  186. settingValue := Proto2GoArgoSetting(requestCloudflare.GetArgoSetting())
  187. setting, err := api.UpdateArgoSmartRouting(ctx, requestCloudflare.ZoneId, settingValue)
  188. if err != nil {
  189. return nil, err
  190. }
  191. return Go2ProtoArgoSetting(setting.Value), nil
  192. }
  193. func (s *ZoneServer) GetArgoSetting(ctx context.Context, requestCloudflare *zone.IdRequest) (*zone.ArgoSetting, error) {
  194. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  195. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  196. } else {
  197. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  198. }
  199. if err != nil {
  200. return nil, err
  201. }
  202. setting, err := api.ArgoSmartRouting(ctx, requestCloudflare.ZoneId)
  203. if err != nil {
  204. return nil, err
  205. }
  206. return Go2ProtoArgoSetting(setting.Value), nil
  207. }
  208. func (s *ZoneServer) ZoneIDByNameCloudflare(ctx context.Context, requestCloudflare *zone.ZoneIDByNameRequestCloudflare) (*zone.ZoneIDByNameReplyCloudflare, error) {
  209. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  210. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  211. } else {
  212. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  213. }
  214. if err != nil {
  215. return nil, err
  216. }
  217. id, err := api.ZoneIDByName(requestCloudflare.ZoneName)
  218. if err != nil {
  219. return nil, err
  220. }
  221. return &zone.ZoneIDByNameReplyCloudflare{ZoneId: id}, err
  222. }
  223. func (s *ZoneServer) ZoneDetails(ctx context.Context, requestCloudflare *zone.ZoneDetailsRequestCloudflare) (*zone.ZoneDetailsReplyCloudflare, error) {
  224. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  225. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  226. } else {
  227. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  228. }
  229. if err != nil {
  230. return nil, err
  231. }
  232. ctxAPI := context.Background()
  233. details, err := api.ZoneDetails(ctxAPI, requestCloudflare.GetZoneId())
  234. if err != nil {
  235. return nil, err
  236. }
  237. return &zone.ZoneDetailsReplyCloudflare{
  238. Result: Go2ProtoZone(details),
  239. }, err
  240. }
  241. func (s *ZoneServer) GetZones(ctx context.Context, requestCloudflare *zone.GetZonesRequestCloudflare) (*zone.GetZonesReplyCloudflare, error) {
  242. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  243. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  244. } else {
  245. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  246. }
  247. if err != nil {
  248. return nil, err
  249. }
  250. details, err := api.ListZones(ctx, "name", requestCloudflare.GetDomain())
  251. if err != nil {
  252. return nil, err
  253. }
  254. list := make([]*zone.ZoneCloudflareEntity, len(details))
  255. for i, detail := range details {
  256. list[i] = Go2ProtoZone(detail)
  257. }
  258. return &zone.GetZonesReplyCloudflare{
  259. Result: list,
  260. Success: true,
  261. }, err
  262. }
  263. func (s *ZoneServer) ListZones(ctx context.Context, requestCloudflare *zone.ListZonesRequestCloudflare) (*zone.ZonesList, error) {
  264. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  265. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  266. } else {
  267. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  268. }
  269. if err != nil {
  270. return nil, fmt.Errorf("failed to initialize Cloudflare API: %w", err)
  271. }
  272. ctxAPI := context.Background()
  273. details, err := api.ListZones(ctxAPI)
  274. if err != nil {
  275. return nil, err
  276. }
  277. list := make([]*zone.ZoneCloudflareEntity, len(details))
  278. for i, detail := range details {
  279. list[i] = Go2ProtoZone(detail)
  280. }
  281. return &zone.ZonesList{
  282. Result: list,
  283. }, err
  284. }
  285. func (s *ZoneServer) ListZonesByAccountId(ctx context.Context, requestCloudflare *zone.ListZonesByAccountIdRequestCloudflare) (*zone.ZonesList, error) {
  286. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  287. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  288. } else {
  289. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  290. }
  291. if err != nil {
  292. return nil, err
  293. }
  294. ctxAPI := context.Background()
  295. opt := cloudflare.WithZoneFilters("", requestCloudflare.AccountId, "")
  296. details, err := api.ListZonesContext(ctxAPI, opt)
  297. if err != nil {
  298. return nil, err
  299. }
  300. list := make([]*zone.ZoneCloudflareEntity, len(details.Result))
  301. for i, detail := range details.Result {
  302. list[i] = Go2ProtoZone(detail)
  303. }
  304. return &zone.ZonesList{
  305. Result: list,
  306. }, err
  307. }
  308. func (s *ZoneServer) EditZone(ctx context.Context, requestCloudflare *zone.EditZoneRequestCloudflare) (*zone.EditZoneReplyCloudflare, error) {
  309. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  310. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  311. } else {
  312. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  313. }
  314. if err != nil {
  315. return nil, err
  316. }
  317. ctxAPI := context.Background()
  318. opts := cloudflare.ZoneOptions{}
  319. opts.Paused = requestCloudflare.Paused
  320. if requestCloudflare.PlanId != nil {
  321. opts.Plan = &cloudflare.ZonePlan{
  322. ZonePlanCommon: cloudflare.ZonePlanCommon{
  323. ID: requestCloudflare.GetPlanId(),
  324. },
  325. }
  326. }
  327. if requestCloudflare.Type != nil {
  328. opts.Type = requestCloudflare.GetType()
  329. }
  330. editZone, err := api.EditZone(ctxAPI, requestCloudflare.GetZoneId(), opts)
  331. if err != nil {
  332. return nil, err
  333. }
  334. return &zone.EditZoneReplyCloudflare{
  335. Result: Go2ProtoZone(editZone),
  336. Success: true,
  337. }, nil
  338. }
  339. func (s *ZoneServer) DeleteZone(ctx context.Context, requestCloudflare *zone.DeleteZoneRequestCloudflare) (*zone.DeleteZoneReplyCloudflare, error) {
  340. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  341. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  342. } else {
  343. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  344. }
  345. if err != nil {
  346. return nil, err
  347. }
  348. ctxAPI := context.Background()
  349. deleteZone, err := api.DeleteZone(ctxAPI, requestCloudflare.GetZoneId())
  350. if err != nil {
  351. return nil, err
  352. }
  353. return &zone.DeleteZoneReplyCloudflare{
  354. Success: true,
  355. Id: deleteZone.ID,
  356. }, nil
  357. }
  358. func (s *ZoneServer) CreateZone(ctx context.Context, requestCloudflare *zone.CreateZoneRequestCloudflare) (*zone.CreateZoneReplyCloudflare, error) {
  359. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  360. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  361. } else {
  362. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  363. }
  364. if err != nil {
  365. return nil, err
  366. }
  367. ctxAPI := context.Background()
  368. account, _, err := api.Account(ctxAPI, requestCloudflare.GetAccountId())
  369. if err != nil {
  370. return nil, err
  371. }
  372. createZone, err := api.CreateZone(ctxAPI, requestCloudflare.GetDomain(), false, account, "full")
  373. if err != nil {
  374. return nil, err
  375. }
  376. return &zone.CreateZoneReplyCloudflare{
  377. Success: true,
  378. Id: createZone.ID,
  379. }, nil
  380. }
  381. func (s *ZoneServer) SetZonePlan(ctx context.Context, requestCloudflare *zone.SetZonePlanRequestCloudflare) (*zone.SetZonePlanReplyCloudflare, error) {
  382. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  383. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  384. } else {
  385. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  386. }
  387. if err != nil {
  388. return nil, err
  389. }
  390. ctxAPI := context.Background()
  391. err = api.ZoneSetPlan(ctxAPI, requestCloudflare.GetZoneId(), requestCloudflare.GetZonePlan())
  392. if err != nil {
  393. return nil, err
  394. }
  395. return &zone.SetZonePlanReplyCloudflare{
  396. Success: true,
  397. }, nil
  398. }
  399. func (s *ZoneServer) ActivationCheck(ctx context.Context, requestCloudflare *zone.ActivationCheckRequestCloudflare) (*zone.ActivationCheckReplyCloudflare, error) {
  400. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  401. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  402. } else {
  403. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  404. }
  405. if err != nil {
  406. return nil, err
  407. }
  408. ctxAPI := context.Background()
  409. activationCheck, err := api.ZoneActivationCheck(ctxAPI, requestCloudflare.GetZoneId())
  410. if err != nil {
  411. return nil, err
  412. }
  413. return &zone.ActivationCheckReplyCloudflare{
  414. Success: activationCheck.Success,
  415. }, nil
  416. }
  417. var phaseMap = map[zone.Phase]string{
  418. zone.Phase_http_request_sanitize: "http_request_sanitize",
  419. zone.Phase_http_request_transform: "http_request_transform",
  420. zone.Phase_http_request_origin: "http_request_origin",
  421. zone.Phase_http_request_cache_settings: "http_request_cache_settings",
  422. zone.Phase_http_config_settings: "http_config_settings",
  423. //zone.Phase_http_request_dynamic_redirect: "http_request_dynamic_redirect",
  424. //zone.Phase_ddos_l7: "ddos_l7",
  425. //zone.Phase_http_request_firewall_custom: "http_request_firewall_custom",
  426. //zone.Phase_http_ratelimit: "http_ratelimit",
  427. //zone.Phase_http_request_firewall_managed: "http_request_firewall_managed",
  428. //zone.Phase_http_request_sbfm: "http_request_sbfm",
  429. //zone.Phase_http_request_redirect: "http_request_redirect",
  430. zone.Phase_http_request_late_transform: "http_request_late_transform",
  431. //zone.Phase_http_custom_errors: "http_custom_errors",
  432. zone.Phase_http_response_headers_transform: "http_response_headers_transform",
  433. //zone.Phase_http_response_firewall_managed: "http_response_firewall_managed",
  434. //zone.Phase_http_log_custom_fields: "http_log_custom_fields",
  435. }
  436. func (s *ZoneServer) ListZoneRuleSets(ctx context.Context, requestCloudflare *zone.ListZoneRuleSetsRequestCloudflare) (*zone.RuleSetList, error) {
  437. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  438. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  439. } else {
  440. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  441. }
  442. if err != nil {
  443. return nil, err
  444. }
  445. ctxAPI := context.Background()
  446. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  447. ListRulesetsParams := cloudflare.ListRulesetsParams{}
  448. goRuleSets, err := api.ListRulesets(ctxAPI, zoneIdentifier, ListRulesetsParams)
  449. if err != nil {
  450. return nil, err
  451. }
  452. filterMap := lo.FilterMap[cloudflare.Ruleset, *zone.RuleSet](goRuleSets, func(goRuleSet cloudflare.Ruleset, _ int) (*zone.RuleSet, bool) {
  453. protoRuleSet := Go2ProtoRuleSet(&goRuleSet)
  454. return protoRuleSet, true
  455. })
  456. return &zone.RuleSetList{RuleSets: filterMap}, nil
  457. }
  458. func (s *ZoneServer) CreateZoneRuleSet(ctx context.Context, requestCloudflare *zone.CreateZoneRuleSetRequestCloudflare) (*zone.CreateZoneRuleSetReplyCloudflare, error) {
  459. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  460. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  461. } else {
  462. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  463. }
  464. if err != nil {
  465. return nil, err
  466. }
  467. ctxAPI := context.Background()
  468. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  469. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.RuleSet.Phase)
  470. if err != nil || ruleResult == nil {
  471. return cloudflare.RulesetRule{}, false
  472. }
  473. return *ruleResult, true
  474. })
  475. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  476. createRulesetParams := cloudflare.CreateRulesetParams{
  477. Name: requestCloudflare.RuleSet.Name,
  478. Kind: requestCloudflare.RuleSet.Kind,
  479. Phase: phaseMap[requestCloudflare.RuleSet.Phase],
  480. Rules: filterMap,
  481. }
  482. _, err = api.CreateRuleset(ctxAPI, zoneIdentifier, createRulesetParams)
  483. if err != nil {
  484. return &zone.CreateZoneRuleSetReplyCloudflare{Success: false}, err
  485. }
  486. //protoRuleSet := Go2ProtoRuleSet(&goRuleSet)
  487. return &zone.CreateZoneRuleSetReplyCloudflare{Success: true}, nil
  488. }
  489. func (s *ZoneServer) DeleteZoneRuleSet(ctx context.Context, requestCloudflare *zone.DeleteZoneRuleSetRequestCloudflare) (*zone.DeleteZoneRuleSetReplyCloudflare, error) {
  490. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  491. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  492. } else {
  493. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  494. }
  495. if err != nil {
  496. return nil, err
  497. }
  498. ctxAPI := context.Background()
  499. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  500. err = api.DeleteRuleset(ctxAPI, zoneIdentifier, requestCloudflare.GetRuleSetId())
  501. if err != nil {
  502. return &zone.DeleteZoneRuleSetReplyCloudflare{Success: false}, err
  503. }
  504. return &zone.DeleteZoneRuleSetReplyCloudflare{Success: true}, nil
  505. }
  506. func (s *ZoneServer) UpdateRuleSetByRuleSetId(ctx context.Context, requestCloudflare *zone.UpdateRuleSetByRuleSetIdRequestCloudflare) (*zone.RuleSet, error) {
  507. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  508. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  509. } else {
  510. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  511. }
  512. if err != nil {
  513. return nil, err
  514. }
  515. ctxAPI := context.Background()
  516. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  517. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  518. if err != nil || ruleResult == nil {
  519. return cloudflare.RulesetRule{}, false
  520. }
  521. return *ruleResult, true
  522. })
  523. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  524. updateRulesetParams := cloudflare.UpdateRulesetParams{
  525. ID: requestCloudflare.RuleSetId,
  526. Rules: filterMap,
  527. }
  528. goRuleSet, err := api.UpdateRuleset(ctxAPI, zoneIdentifier, updateRulesetParams)
  529. if err != nil {
  530. return nil, err
  531. }
  532. protoRuleSet := Go2ProtoRuleSet(&goRuleSet)
  533. return protoRuleSet, nil
  534. }
  535. func (s *ZoneServer) GetRuleSet(ctx context.Context, requestCloudflare *zone.GetRuleSetRequestCloudflare) (*zone.RuleList, error) {
  536. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  537. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  538. } else {
  539. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  540. }
  541. if err != nil {
  542. return nil, err
  543. }
  544. ctxAPI := context.Background()
  545. switch phaseMap[requestCloudflare.Phase] {
  546. case "http_request_origin", "http_request_cache_settings", "http_config_settings":
  547. case "http_request_transform", "http_request_late_transform", "http_response_headers_transform":
  548. default:
  549. return nil, errors.New("未定义规则阶段")
  550. }
  551. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  552. ruleset, err := api.GetEntrypointRuleset(ctxAPI, zoneIdentifier, phaseMap[requestCloudflare.Phase])
  553. if err != nil {
  554. _, ok := err.(*cloudflare.NotFoundError)
  555. if ok {
  556. ruleset.Rules = make([]cloudflare.RulesetRule, 0)
  557. err = nil
  558. } else {
  559. return nil, err
  560. }
  561. }
  562. filterMap := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  563. phase, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  564. if err != nil {
  565. return nil, false
  566. }
  567. return phase, true
  568. })
  569. return &zone.RuleList{Rules: filterMap}, nil
  570. }
  571. func (s *ZoneServer) UpdateRuleSet(ctx context.Context, requestCloudflare *zone.UpdateRuleSetRequestCloudflare) (*zone.RuleList, error) {
  572. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  573. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  574. } else {
  575. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  576. }
  577. if err != nil {
  578. return nil, err
  579. }
  580. ctxAPI := context.Background()
  581. phase := phaseMap[requestCloudflare.Phase]
  582. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  583. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  584. if err != nil || ruleResult == nil {
  585. return cloudflare.RulesetRule{}, false
  586. }
  587. return *ruleResult, true
  588. })
  589. //for _, rule := range requestCloudflare.Rules {
  590. // ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  591. // if err != nil {
  592. // return nil, err
  593. // }
  594. // if ruleResult != nil {
  595. // ruleSet.Rules = append(ruleSet.Rules, *ruleResult)
  596. // }
  597. //}
  598. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  599. updateEntrypointRulesetParams := cloudflare.UpdateEntrypointRulesetParams{
  600. Phase: phase,
  601. Rules: filterMap,
  602. }
  603. ruleset, err := api.UpdateEntrypointRuleset(ctxAPI, zoneIdentifier, updateEntrypointRulesetParams)
  604. if err != nil {
  605. return nil, err
  606. }
  607. rulesReturn := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  608. ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  609. if err != nil {
  610. return nil, false
  611. }
  612. return ruleReturn, true
  613. })
  614. //var rulesReturn []*zone.Rule
  615. //for _, rule := range rulesetResult.Rules {
  616. // ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, rulesetResult.Phase)
  617. // if err != nil {
  618. // return nil, err
  619. // }
  620. // if ruleReturn != nil {
  621. // rulesReturn = append(rulesReturn, ruleReturn)
  622. // }
  623. //}
  624. return &zone.RuleList{Rules: rulesReturn}, nil
  625. }
  626. //func UpdateRuleSet(apiKey, apiEmail, zoneID, rulesetPhase string, ruleset cloudflare.Ruleset) (*cloudflare.Ruleset, error) {
  627. // api, err := cloudflare.New(apiKey, apiEmail)
  628. // if err != nil {
  629. // return nil, err
  630. // }
  631. // ctxAPI := context.Background()
  632. // phase, err := api.UpdateZoneRulesetPhase(ctxAPI, zoneID, rulesetPhase, ruleset)
  633. // if err != nil {
  634. // return nil, err
  635. // }
  636. // return &phase, nil
  637. //}
  638. //PageRule CURD
  639. func (s *ZoneServer) ListPageRule(ctx context.Context, requestCloudflare *zone.ListPageRuleRequestCloudflare) (*zone.PageRuleList, error) {
  640. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  641. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  642. } else {
  643. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  644. }
  645. if err != nil {
  646. return nil, err
  647. }
  648. ctxAPI := context.Background()
  649. rules, err := api.ListPageRules(ctxAPI, requestCloudflare.GetZoneId())
  650. if err != nil {
  651. return nil, err
  652. }
  653. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  654. pageRule := Go2ProtoPageRule(&rule)
  655. return pageRule, true
  656. })
  657. return &zone.PageRuleList{PageRules: filterMap}, nil
  658. }
  659. func (s *ZoneServer) CreatePageRule(ctx context.Context, requestCloudflare *zone.CreatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  660. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  661. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  662. } else {
  663. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  664. }
  665. if err != nil {
  666. return nil, err
  667. }
  668. ctxAPI := context.Background()
  669. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  670. if err != nil {
  671. return nil, err
  672. }
  673. pageRule, err := api.CreatePageRule(ctxAPI, requestCloudflare.GetZoneId(), *rule)
  674. if err != nil {
  675. return nil, err
  676. }
  677. return Go2ProtoPageRule(pageRule), nil
  678. }
  679. func (s *ZoneServer) UpdatePageRule(ctx context.Context, requestCloudflare *zone.UpdatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  680. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  681. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  682. } else {
  683. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  684. }
  685. if err != nil {
  686. return nil, err
  687. }
  688. ctxAPI := context.Background()
  689. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  690. if err != nil {
  691. return nil, err
  692. }
  693. err = api.UpdatePageRule(ctxAPI, requestCloudflare.GetZoneId(), rule.ID, *rule)
  694. if err != nil {
  695. return nil, err
  696. }
  697. return requestCloudflare.PageRule, nil
  698. }
  699. func (s *ZoneServer) DeletePageRule(ctx context.Context, requestCloudflare *zone.DeletePageRuleRequestCloudflare) (*zone.PageRule, error) {
  700. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  701. api, err = cloudflare.NewWithAPIToken(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:])
  702. } else {
  703. api, err = cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  704. }
  705. if err != nil {
  706. return nil, err
  707. }
  708. ctxAPI := context.Background()
  709. err = api.DeletePageRule(ctxAPI, requestCloudflare.ZoneId, requestCloudflare.PageRuleId)
  710. if err != nil {
  711. return nil, err
  712. }
  713. return &zone.PageRule{}, nil
  714. }
  715. //func UpdatePageRule(apiKey, apiEmail, zoneID string, rule *zone.PageRule) (*zone.PageRule, error) {
  716. // api, err := cloudflare.New(apiKey, apiEmail)
  717. // if err != nil {
  718. // return nil, err
  719. // }
  720. //
  721. // ctxAPI := context.Background()
  722. // goPageRule, err := Proto2GoPageRule(rule)
  723. // if err != nil {
  724. // return nil, err
  725. // }
  726. // pageRule, err := api.CreatePageRule(ctxAPI, zoneID, *goPageRule)
  727. // if err != nil {
  728. // return nil, err
  729. // }
  730. //
  731. // protoPageRule := Go2ProtoPageRule(pageRule)
  732. //
  733. // return protoPageRule, nil
  734. //}
  735. type PageRuleActionCacheKeyFieldsQueryString struct {
  736. Exclude interface{} `json:"exclude"`
  737. Include interface{} `json:"include"`
  738. }
  739. type PageRuleActionCacheKeyFields struct {
  740. QueryString PageRuleActionCacheKeyFieldsQueryString `json:"query_string"`
  741. }
  742. type UpdatePageRulesPrioritiesStruct struct {
  743. Id string `json:"id"`
  744. Priority int `json:"priority"`
  745. }
  746. func (s *ZoneServer) UpdatePageRulesPriorities(ctx context.Context, requestCloudflare *zone.UpdatePageRulesPrioritiesRequestCloudflare) (*zone.PageRuleList, error) {
  747. //TODO 参数检查
  748. //设置HTTP请求
  749. client := &http.Client{}
  750. bytesData, err := json.Marshal(requestCloudflare.Data)
  751. if err != nil {
  752. return nil, err
  753. }
  754. req, err := http.NewRequest("PUT", "https://api.cloudflare.com/client/v4/zones/"+requestCloudflare.ZoneId+"/pagerules/priorities", bytes.NewReader(bytesData))
  755. if err != nil {
  756. return nil, err
  757. }
  758. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  759. req.Header.Add("Authorization", ApiToken2Authorization(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:]))
  760. } else {
  761. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  762. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  763. }
  764. //执行HTTP请求
  765. resp, err := client.Do(req)
  766. if err != nil {
  767. return nil, err
  768. }
  769. defer func(Body io.ReadCloser) {
  770. _ = Body.Close()
  771. }(resp.Body)
  772. body, _ := ioutil.ReadAll(resp.Body)
  773. //解析HTTP返回数据
  774. var r cloudflare.PageRulesResponse
  775. err = json.Unmarshal(body, &r)
  776. //处理返回逻辑
  777. if err != nil {
  778. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  779. }
  780. if r.Success != true {
  781. return nil, fmt.Errorf("%s", r.Errors)
  782. }
  783. rules := r.Result
  784. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  785. pageRule := Go2ProtoPageRule(&rule)
  786. return pageRule, true
  787. })
  788. return &zone.PageRuleList{PageRules: filterMap}, nil
  789. }
  790. // 默认开启Smarttiered cache
  791. func (s *ZoneServer) SetSmartTieredCache(ctx context.Context, requestCloudflare *zone.SetSmartTieredCacheRequestCloudflare) (*zone.SetSmartTieredCacheReplyCloudflare, error) {
  792. type ResponseType struct {
  793. Errors []interface{} `json:"errors"`
  794. Messages []interface{} `json:"messages"`
  795. Result interface{} `json:"result"`
  796. Success bool `json:"success"`
  797. }
  798. //设置HTTP请求
  799. client := &http.Client{}
  800. url := "https://api.cloudflare.com/client/v4/zones/" + requestCloudflare.ZoneId + "/cache/tiered_cache_smart_topology_enable"
  801. payload := strings.NewReader("{\n \"value\": \"on\"\n}")
  802. req, err := http.NewRequest("PATCH", url, payload)
  803. if err != nil {
  804. return nil, err
  805. }
  806. req.Header.Add("Content-Type", "application/json")
  807. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  808. req.Header.Add("Authorization", ApiToken2Authorization(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:]))
  809. } else {
  810. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  811. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  812. }
  813. //执行HTTP请求
  814. resp, err := client.Do(req)
  815. if err != nil {
  816. return nil, err
  817. }
  818. defer func(Body io.ReadCloser) {
  819. _ = Body.Close()
  820. }(resp.Body)
  821. body, _ := ioutil.ReadAll(resp.Body)
  822. print(body)
  823. //解析HTTP返回数据
  824. var r ResponseType
  825. err = json.Unmarshal(body, &r)
  826. if err != nil {
  827. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  828. }
  829. if r.Success != true {
  830. print(fmt.Errorf("%s", r.Errors))
  831. }
  832. return &zone.SetSmartTieredCacheReplyCloudflare{Enabled: r.Success}, nil
  833. }
  834. // 开启强制使用https
  835. func (s *ZoneServer) UpdateAlwaysUseHttps(ctx context.Context, requestCloudflare *zone.UpdateAlwaysUseHttpsRequestCloudflare) (*zone.UpdateAlwaysUseHttpsReplyCloudflare, error) {
  836. type ResponseType struct {
  837. Errors []interface{} `json:"errors"`
  838. Messages []interface{} `json:"messages"`
  839. Result interface{} `json:"result"`
  840. Success bool `json:"success"`
  841. }
  842. //设置HTTP请求
  843. client := &http.Client{}
  844. url := "https://api.cloudflare.com/client/v4/zones/" + requestCloudflare.ZoneId + "/settings/always_use_https"
  845. var payload io.Reader
  846. if requestCloudflare.Enabled {
  847. payload = strings.NewReader("{\n \"value\": \"on\"\n}")
  848. } else {
  849. payload = strings.NewReader("{\n \"value\": \"off\"\n}")
  850. }
  851. req, err := http.NewRequest("PATCH", url, payload)
  852. if err != nil {
  853. return nil, err
  854. }
  855. req.Header.Add("Content-Type", "application/json")
  856. if strings.HasPrefix(requestCloudflare.GetApiKey(), TOKEN_PREFIX) {
  857. req.Header.Add("Authorization", ApiToken2Authorization(requestCloudflare.GetApiKey()[TOKEN_PREFIX_LENGTH:]))
  858. } else {
  859. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  860. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  861. }
  862. //执行HTTP请求
  863. resp, err := client.Do(req)
  864. if err != nil {
  865. return nil, err
  866. }
  867. defer func(Body io.ReadCloser) {
  868. _ = Body.Close()
  869. }(resp.Body)
  870. body, _ := ioutil.ReadAll(resp.Body)
  871. print(body)
  872. //解析HTTP返回数据
  873. var r ResponseType
  874. err = json.Unmarshal(body, &r)
  875. if err != nil {
  876. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  877. }
  878. if r.Success != true {
  879. print(fmt.Errorf("%s", r.Errors))
  880. }
  881. return &zone.UpdateAlwaysUseHttpsReplyCloudflare{Success: r.Success}, nil
  882. }