(method, apiURL string, body interface{})
| 622 | } |
| 623 | |
| 624 | func (h *CronitorMCPHandler) makeAuthenticatedRequest(method, apiURL string, body interface{}) ([]byte, error) { |
| 625 | // For state-changing requests, we need to get a CSRF token first |
| 626 | if method == "POST" || method == "PUT" || method == "DELETE" { |
| 627 | // First, make a GET request to get a CSRF token |
| 628 | getReq, err := http.NewRequest("GET", h.apiURL+"/api/settings", nil) |
| 629 | if err != nil { |
| 630 | return nil, fmt.Errorf("failed to create CSRF token request: %v", err) |
| 631 | } |
| 632 | |
| 633 | // Set auth header for the GET request |
| 634 | if h.username != "" && h.password != "" { |
| 635 | getReq.SetBasicAuth(h.username, h.password) |
| 636 | } |
| 637 | |
| 638 | getResp, err := httpClient.Do(getReq) |
| 639 | if err != nil { |
| 640 | return nil, fmt.Errorf("failed to get CSRF token: %v", err) |
| 641 | } |
| 642 | defer getResp.Body.Close() |
| 643 | |
| 644 | // Check for authentication error |
| 645 | if getResp.StatusCode == 401 { |
| 646 | return nil, fmt.Errorf("authentication failed - check username and password for instance '%s'", h.instanceName) |
| 647 | } |
| 648 | |
| 649 | // Read the response body to ensure cookies are set |
| 650 | io.ReadAll(getResp.Body) |
| 651 | |
| 652 | // Extract CSRF token from response header |
| 653 | csrfToken := getResp.Header.Get("X-CSRF-Token") |
| 654 | |
| 655 | // If no token in header, try to extract from cookies |
| 656 | if csrfToken == "" { |
| 657 | parsedURL, _ := url.Parse(h.apiURL) |
| 658 | for _, cookie := range httpClient.Jar.Cookies(parsedURL) { |
| 659 | if cookie.Name == "csrf_token" { |
| 660 | csrfToken = cookie.Value |
| 661 | break |
| 662 | } |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | if csrfToken == "" { |
| 667 | return nil, fmt.Errorf("failed to obtain CSRF token") |
| 668 | } |
| 669 | |
| 670 | // Now make the actual request with the CSRF token |
| 671 | var reqBody io.Reader |
| 672 | if body != nil { |
| 673 | jsonBody, err := json.Marshal(body) |
| 674 | if err != nil { |
| 675 | return nil, err |
| 676 | } |
| 677 | reqBody = bytes.NewReader(jsonBody) |
| 678 | } |
| 679 | |
| 680 | req, err := http.NewRequest(method, apiURL, reqBody) |
| 681 | if err != nil { |
no test coverage detected