Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions support/datastore/datastore.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ func NewDataStore(ctx context.Context, datastoreConfig DataStoreConfig) (DataSto
return NewGCSDataStore(ctx, datastoreConfig)
case "S3":
return NewS3DataStore(ctx, datastoreConfig)
case "HTTP":
return NewHTTPDataStore(datastoreConfig)

default:
return nil, fmt.Errorf("invalid datastore type %v, not supported", datastoreConfig.Type)
Expand Down
220 changes: 220 additions & 0 deletions support/datastore/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
package datastore

import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"

"github.com/stellar/go/support/log"

Check failure on line 15 in support/datastore/http.go

View workflow job for this annotation

GitHub Actions / golangci

import 'github.com/stellar/go/support/log' is not allowed from list 'Main' (depguard)
)

// HTTPDataStore implements DataStore for HTTP(S) endpoints.
// This is designed for read-only access to publicly available files.
type HTTPDataStore struct {
client *http.Client
baseURL string
headers map[string]string
}

func NewHTTPDataStore(datastoreConfig DataStoreConfig) (DataStore, error) {
baseURL, ok := datastoreConfig.Params["base_url"]
if !ok {
return nil, errors.New("invalid HTTP config, no base_url")
}

parsedURL, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("invalid base_url: %w", err)
}
if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
return nil, errors.New("base_url must use http or https scheme")
}

if !strings.HasSuffix(baseURL, "/") {
baseURL = baseURL + "/"
}

timeout := 30 * time.Second

Check failure on line 44 in support/datastore/http.go

View workflow job for this annotation

GitHub Actions / golangci

Magic number: 30, in <operation> detected (mnd)
if timeoutStr, ok := datastoreConfig.Params["timeout"]; ok {
parsedTimeout, err := time.ParseDuration(timeoutStr)
if err != nil {
return nil, fmt.Errorf("invalid timeout: %w", err)
}
timeout = parsedTimeout
}

headers := make(map[string]string)
for key, value := range datastoreConfig.Params {
if strings.HasPrefix(key, "header_") {
headerName := strings.TrimPrefix(key, "header_")
headers[headerName] = value
}
}

client := &http.Client{
Timeout: timeout,
Comment on lines +61 to +62
Copy link
Preview

Copilot AI Sep 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The HTTP client lacks important security configurations. Consider adding MaxIdleConns, MaxIdleConnsPerHost, and IdleConnTimeout to prevent connection pool exhaustion, and disable automatic redirect following for better security control.

Suggested change
client := &http.Client{
Timeout: timeout,
transport := &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
}
client := &http.Client{
Timeout: timeout,
Transport: transport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},

Copilot uses AI. Check for mistakes.

}

return &HTTPDataStore{
client: client,
baseURL: baseURL,
headers: headers,
}, nil
}

func (h *HTTPDataStore) buildURL(filePath string) string {
return h.baseURL + filePath
}

func (h *HTTPDataStore) addHeaders(req *http.Request) {
for key, value := range h.headers {
req.Header.Set(key, value)
}
}

func (h *HTTPDataStore) checkHTTPStatus(resp *http.Response, filePath string) error {
switch resp.StatusCode {
case http.StatusOK:
return nil
case http.StatusNotFound:
return os.ErrNotExist
default:
return fmt.Errorf("HTTP error %d for file %s", resp.StatusCode, filePath)
}
}

func (h *HTTPDataStore) doHeadRequest(ctx context.Context, filePath string) (*http.Response, error) {
requestURL := h.buildURL(filePath)
req, err := http.NewRequestWithContext(ctx, "HEAD", requestURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create HEAD request for %s: %w", filePath, err)
}
h.addHeaders(req)

resp, err := h.client.Do(req)
if err != nil {
return nil, fmt.Errorf("HEAD request failed for %s: %w", filePath, err)
}

if err := h.checkHTTPStatus(resp, filePath); err != nil {
resp.Body.Close()
return nil, err
}

return resp, nil
}

// GetFileMetadata retrieves basic metadata for a file via HTTP HEAD request.
func (h *HTTPDataStore) GetFileMetadata(ctx context.Context, filePath string) (map[string]string, error) {
resp, err := h.doHeadRequest(ctx, filePath)
if err != nil {
return nil, err
}
defer resp.Body.Close()

metadata := make(map[string]string)
for key, values := range resp.Header {
if len(values) > 0 {
metadata[strings.ToLower(key)] = values[0]
}
}

return metadata, nil
}

// GetFileLastModified retrieves the last modified time from HTTP headers.
func (h *HTTPDataStore) GetFileLastModified(ctx context.Context, filePath string) (time.Time, error) {
metadata, err := h.GetFileMetadata(ctx, filePath)
if err != nil {
return time.Time{}, err
}

if lastModified, ok := metadata["last-modified"]; ok {
return http.ParseTime(lastModified)
}

return time.Time{}, errors.New("last-modified header not found")
}

// GetFile downloads a file from the HTTP endpoint.
func (h *HTTPDataStore) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
requestURL := h.buildURL(filePath)
req, err := http.NewRequestWithContext(ctx, "GET", requestURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create GET request for %s: %w", filePath, err)
}
h.addHeaders(req)

resp, err := h.client.Do(req)
if err != nil {
log.Debugf("Error retrieving file '%s': %v", filePath, err)
Copy link
Preview

Copilot AI Sep 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logging the full error message may expose sensitive information like internal URLs or authentication details. Consider sanitizing the error message before logging or reducing the log level.

Suggested change
log.Debugf("Error retrieving file '%s': %v", filePath, err)
log.Debugf("Error retrieving file '%s'", filePath)

Copilot uses AI. Check for mistakes.

return nil, fmt.Errorf("GET request failed for %s: %w", filePath, err)
}

if err := h.checkHTTPStatus(resp, filePath); err != nil {
resp.Body.Close()
return nil, err
}

log.Debugf("File retrieved successfully: %s", filePath)
return resp.Body, nil
}

// PutFile is not supported for HTTP datastore.
func (h *HTTPDataStore) PutFile(ctx context.Context, path string, in io.WriterTo, metaData map[string]string) error {
return errors.New("HTTP datastore is read-only, PutFile not supported")
}

// PutFileIfNotExists is not supported for HTTP datastore.
func (h *HTTPDataStore) PutFileIfNotExists(ctx context.Context, path string, in io.WriterTo, metaData map[string]string) (bool, error) {
return false, errors.New("HTTP datastore is read-only, PutFileIfNotExists not supported")
}

// Exists checks if a file exists by making a HEAD request.
func (h *HTTPDataStore) Exists(ctx context.Context, filePath string) (bool, error) {
resp, err := h.doHeadRequest(ctx, filePath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
defer resp.Body.Close()

return true, nil
}

// Size retrieves the file size from Content-Length header.
func (h *HTTPDataStore) Size(ctx context.Context, filePath string) (int64, error) {
metadata, err := h.GetFileMetadata(ctx, filePath)
if err != nil {
return 0, err
}

if contentLength, ok := metadata["content-length"]; ok {
size, err := strconv.ParseInt(contentLength, 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid content-length header: %s", contentLength)
}
return size, nil
}

return 0, errors.New("content-length header not found")
}

// ListFilePaths is not supported for HTTP datastore.
func (h *HTTPDataStore) ListFilePaths(ctx context.Context, prefix string, limit int) ([]string, error) {
return nil, errors.New("HTTP datastore does not support listing files")
}

// Close does nothing for HTTPDataStore as it does not maintain a persistent connection.
func (h *HTTPDataStore) Close() error {
return nil
}
Loading
Loading