Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
105 commits
Select commit Hold shift + click to select a range
4bf7f27
feat: prototype autoclient library
lidel Jul 18, 2025
a72b8e1
feat(config): prototype autoconfig profile
lidel Jul 18, 2025
120bb82
feat: prototype embedded repo migrations
lidel Jul 18, 2025
51a49f9
feat: prototype of `ipfs config` support for `auto`
lidel Jul 24, 2025
a860748
docs: MustGetConfigWithMainnetFallbacks
lidel Jul 24, 2025
302dcdf
chore: lint + cleanup redundant tests
lidel Jul 24, 2025
d23374c
refactor: use const with profile names
lidel Jul 24, 2025
355bc3d
refactor: cfg.BootstrapPeers returns raw Bootstrap
lidel Jul 24, 2025
626a99f
fix: use resolved versions for making decisions
lidel Jul 24, 2025
1d91f11
refactor: Β Bootstrap[Peers]WithAutoConfig
lidel Jul 24, 2025
f629d8b
fix(cli): bootstrap cmd with auto
lidel Jul 24, 2025
0e75e4f
refactor: cleanup
lidel Jul 25, 2025
e711c3c
test: multiple consecutive --expand-auto calls
lidel Jul 25, 2025
d18a1fe
refactor: dry and useful logs
lidel Jul 25, 2025
7088d88
refactor: autoconfig .last-refresh
lidel Jul 25, 2025
e1e4e23
fix: `ipfs bootstrap add auto`
lidel Jul 26, 2025
53a642c
docs: AutoConfig in changelog
lidel Jul 26, 2025
273e18e
chore: update func name
lidel Jul 26, 2025
24d552d
refactor: schema v4
lidel Jul 30, 2025
e2476e9
test: DNSResolver validation
lidel Jul 30, 2025
e9f8ce9
docs: autoconfig changelog
lidel Jul 30, 2025
3d34f41
test: basic ipns publishing work in ci (offline)
lidel Jul 30, 2025
e4eb581
chore: cleanup to use testdata
lidel Jul 30, 2025
2a196dc
test(coreapi): ipns name
lidel Jul 30, 2025
a68d581
fix(docker): copy boxo/autoconfig
lidel Jul 30, 2025
8fa6527
fix(autoconfig): real ipni fallback
lidel Jul 30, 2025
a57df38
fix: restore legacy defaultRepo
lidel Jul 31, 2025
9480b93
test: restore coreiface from master
lidel Jul 31, 2025
85e80d4
chore: restore previous namesys wiring
lidel Jul 31, 2025
7585807
refactor: simplify constructDefaultHTTPRouters
lidel Jul 31, 2025
b3975a2
refactor: cleanup config/autoconfig.go
lidel Jul 31, 2025
00c9d9c
fix: thread-safe cache
lidel Jul 31, 2025
82f2b59
refactor: MustGetConfig fallback handling
lidel Aug 1, 2025
2e22eba
test: ParseAndValidateRoutingURL
lidel Aug 1, 2025
24e6aa4
fix: simpler cache dir
lidel Aug 1, 2025
cf8b596
refactor(config): remove need for passing repoPath
lidel Aug 1, 2025
374ba05
chore: collapse diffs of generated data
lidel Aug 1, 2025
1df21cd
chore: restore master code
lidel Aug 1, 2025
f7c2112
test: error cases for autoconfig.json fetch
lidel Aug 1, 2025
f5fe36f
chore: placeholder
lidel Aug 1, 2025
e52befe
refactor: clenup startAutoConfigUpdater
lidel Aug 1, 2025
03a2a3c
test(autoconfig): ipfs swarm connect
lidel Aug 1, 2025
146ef49
refactor: better names for Must* funcs
lidel Aug 1, 2025
3e4a854
fix(fx): ClearCachedNode
lidel Aug 1, 2025
ef98774
test: TestHTTPCachingBehavior and cleanup
lidel Aug 1, 2025
1a7230c
test: TestAutoConfigIPNS
lidel Aug 1, 2025
814723e
test(autoconfig) Routing.Type=auto|delegated
lidel Aug 2, 2025
36acffe
fix: go vet
lidel Aug 2, 2025
332ab2f
test: migration and autoconfig sharness
lidel Aug 3, 2025
a5f6777
fix: sync.RWMutex
lidel Aug 3, 2025
70dbdc8
test(cli): migration_legacy_15_to_17_test.go
lidel Aug 4, 2025
44dec15
test: testCLIUsesCacheOnlyDaemonUpdatesBackground
lidel Aug 4, 2025
e77f434
fix: t0066-migration.sh
lidel Aug 4, 2025
a6efc94
refactor: autoconfig β†’ autoconf
lidel Aug 4, 2025
35e521d
fix: validate AutoConfSchema 1
lidel Aug 4, 2025
1a73236
docs: highlights and deprecations
lidel Aug 4, 2025
7f3bcea
test: testAutoConfWithHTTPS
lidel Aug 4, 2025
5a6c5ab
docs: boxo/autoconf
lidel Aug 4, 2025
491b1c3
docs: examples in boxo/autoconf/README.md
lidel Aug 5, 2025
c71e9d8
Merge branch 'master' into feat-mainnet-autoconfig
gammazero Aug 11, 2025
6a32e60
remove unused import
gammazero Aug 11, 2025
ea6c3e4
Merge branch 'master' into feat-mainnet-autoconfig
gammazero Aug 11, 2025
285be62
Merge branch 'master' into feat-mainnet-autoconfig
gammazero Aug 11, 2025
13357e3
chore: config β†’ conf
lidel Aug 12, 2025
8fd1829
refactor: boxo/autoconf extraction prep
lidel Aug 13, 2025
ebb948f
refactor: boxo/autoconf cleanup, part 1
lidel Aug 13, 2025
95065fd
Merge branch 'master' into feat-mainnet-autoconfig
lidel Aug 13, 2025
564382f
tests: switch to testify
lidel Aug 13, 2025
d88c0d0
fix: log warn when no cache available
lidel Aug 13, 2025
c2129d7
refactor: improve lock scopes
lidel Aug 13, 2025
a4e0671
chore: move atomicfile
lidel Aug 13, 2025
cfa0bcc
refactor: simplify the path operations
lidel Aug 13, 2025
70860e0
refactor: code simplifications
lidel Aug 13, 2025
0a9a5b7
refactor: reuse buildEndpointURL
lidel Aug 13, 2025
a0bac20
fix: Errorf
lidel Aug 13, 2025
c890bfd
chore: remove FromCache
lidel Aug 13, 2025
c0269f4
fix: panic on nil client
lidel Aug 13, 2025
3a6ec69
chore: preallocate slice
lidel Aug 13, 2025
62f67d6
refactor: slices.Contains
lidel Aug 13, 2025
af51a49
refactor: review feedback cleanup
lidel Aug 13, 2025
54df810
refactor: core/node/libp2p/host.go
lidel Aug 13, 2025
b0cdf44
refactor: move autoclient to boxo#997
lidel Aug 13, 2025
1946d45
fix: restore dockerfile
lidel Aug 13, 2025
5d4275e
chore: gofmt
lidel Aug 13, 2025
66fe0a8
Merge branch 'master' into feat-mainnet-autoconfig
gammazero Aug 14, 2025
2176ae4
merge: origin/master into feat-mainnet-autoconfig
lidel Aug 15, 2025
7f027e4
docs: concise changelog
lidel Aug 15, 2025
9321e46
chore: update to latest boxo#997
lidel Aug 15, 2025
018b73b
chore: update to boxo@main
lidel Aug 15, 2025
e4e08a3
merge: origin/master into feat-mainnet-autoconfig
lidel Aug 18, 2025
f2ca7d9
fix: telemetry bootstrap check for autoconf
lidel Aug 18, 2025
f3b8ed3
feat: autoconf telemetry
lidel Aug 18, 2025
2bb5276
test: telemetry schema regression guard
lidel Aug 18, 2025
f0314d0
test: use atomic.Int32 for cleaner counter handling
lidel Aug 18, 2025
0eb4a02
test: remove emojis from test logs
lidel Aug 18, 2025
dc41fbb
test: clarify bootstrap peer round-trip test
lidel Aug 18, 2025
9ffbf88
test: simplify IPNS error tests
lidel Aug 18, 2025
a7b0b21
refactor: rename --delegated-only to --allow-delegated
lidel Aug 19, 2025
470d4db
refactor: make AutoConf.URL implicit like AutoTLS
lidel Aug 19, 2025
0da54e0
fix: sort profile names in config help output
lidel Aug 19, 2025
8ec830b
test: AutoConf in bootstrap add default test
lidel Aug 19, 2025
ccd2388
fix: allow ipfs repo migrate to run without daemon
lidel Aug 19, 2025
6e75456
refactor: make Migration config optional
lidel Aug 19, 2025
d028a23
Merge branch 'master' into feat-mainnet-autoconfig
lidel Aug 19, 2025
2b32db3
fix(migration): use implicit defaults for AutoConf fields
lidel Aug 20, 2025
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
162 changes: 162 additions & 0 deletions boxo/autoconfig/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# AutoConfig Library

This package provides a client library for fetching and caching IPFS autoconfig.json files. It's designed to be generic and self-contained for easy extraction to the boxo library later.

## Features

- **HTTP Client**: Configurable HTTP client with timeout, user-agent, and TLS options
- **Caching**: Intelligent caching with ETag/Last-Modified support and version rotation
- **Version Management**: Automatic cleanup of old cached versions
- **Path Safety**: Sanitized cache directory structure based on URL hostname
- **Error Handling**: Graceful fallback to cached versions when remote fetch fails

## Usage

### Basic Usage

```go
import "github.com/ipfs/kubo/boxo/autoconfig"

// Create a client with default options
client, err := autoconfig.NewClient()
if err != nil {
return err
}

// Fetch the latest config
config, err := client.GetLatest(ctx, "https://config.ipfs-mainnet.org/autoconfig.json")
if err != nil {
return err
}

// Use the config
fmt.Printf("Bootstrap peers: %v\n", config.Bootstrap)
```

### With Custom Options

```go
client, err := autoconfig.NewClient(
autoconfig.WithCacheDir("/path/to/cache"),
autoconfig.WithUserAgent("my-app/1.0"),
autoconfig.WithCacheSize(5),
autoconfig.WithTimeout(10*time.Second),
)
```

### Integration with Applications

This library is designed to be integrated into applications that need autoconfig functionality. The client is generic and does not depend on any specific application framework.

```go
func main() {
client, err := autoconfig.NewClient(
autoconfig.WithCacheDir("/app/data/autoconfig"),
autoconfig.WithUserAgent("myapp/1.2.3"),
autoconfig.WithTimeout(10*time.Second),
)
if err != nil {
panic(err)
}

config, err := client.GetLatest(context.Background(), "https://config.ipfs-mainnet.org/autoconfig.json")
if err != nil {
panic(err)
}

fmt.Printf("Bootstrap peers: %v\n", config.Bootstrap)
fmt.Printf("DNS resolvers: %v\n", config.DNSResolvers)
}
```

### Background Updates

For applications that need periodic config updates, use the background updater:

```go
func main() {
client, err := autoconfig.NewClient(
autoconfig.WithCacheDir("/app/data/autoconfig"),
autoconfig.WithUserAgent("myapp/1.2.3"),
)
if err != nil {
panic(err)
}

// Create background updater with custom callbacks
updater, err := autoconfig.NewBackgroundUpdater(client, "https://config.ipfs-mainnet.org/autoconfig.json",
autoconfig.WithUpdateInterval(6*time.Hour), // Check every 6 hours
autoconfig.WithOnVersionChange(func(oldVersion, newVersion int64, configURL string) {
fmt.Printf("New config version %d available (was %d) - consider restarting\n", newVersion, oldVersion)
}),
autoconfig.WithOnUpdateSuccess(func(resp *autoconfig.AutoConfigResponse) {
fmt.Printf("Updated config cache at %s\n", resp.FetchTime.Format(time.RFC3339))
}),
autoconfig.WithOnUpdateError(func(err error) {
fmt.Printf("Update failed: %v\n", err)
}),
)
if err != nil {
panic(err)
}

ctx := context.Background()
if err := updater.Start(ctx); err != nil {
panic(err)
}
defer updater.Stop()

// Your application logic here...
select {}
}
```

## Cache Structure

The cache is organized by hostname and version:

```
$CACHE_DIR/
autoconfig/
config.ipfs-mainnet.org/
2025071801.json
2025071802.json
.etag
.last-modified
```

## Configuration Options

### Client Options
- `WithCacheDir(dir)`: Set custom cache directory
- `WithHTTPClient(client)`: Use custom HTTP client
- `WithCacheSize(n)`: Set maximum cached versions (default: 3)
- `WithUserAgent(ua)`: Set HTTP user-agent
- `WithTimeout(duration)`: Set HTTP timeout (default: 5s)
- `WithTLSInsecureSkipVerify(bool)`: Skip TLS verification (for testing)

### Background Updater Options
- `WithUpdateInterval(duration)`: Set update check interval (default: 24h)
- `WithOnVersionChange(callback)`: Called when new config version is detected
- `WithOnUpdateSuccess(callback)`: Called on successful update for metadata persistence
- `WithOnUpdateError(callback)`: Called when update fails

## Error Handling

The client implements graceful fallback:
1. Try to fetch from remote URL
2. If remote fails, fall back to latest cached version
3. If no cache exists, fall back to hardcoded defaults (when using `MustGetConfigWithMainnetFallbacks`)

Note: `GetLatest()` returns errors, while `MustGetConfigWithMainnetFallbacks()` never fails and always returns usable configuration.

## Testing

Run tests with:
```bash
go test .
```

## Future Extraction

This package is designed to be extracted to `github.com/ipfs/boxo` with no changes needed. It has no application-specific dependencies.
4 changes: 4 additions & 0 deletions boxo/autoconfig/autoconfig.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package autoconfig

// This file exists to maintain backwards compatibility during the transition.
// All Kubo-specific client functions have been moved to github.com/ipfs/kubo/config
187 changes: 187 additions & 0 deletions boxo/autoconfig/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
package autoconfig

import (
"crypto/tls"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"time"

logging "github.com/ipfs/go-log/v2"
)

var log = logging.Logger("autoconfig")

const (
defaultTimeout = 5 * time.Second
defaultCacheSize = 3
defaultMaxResponseSize = 2 * 1024 * 1024 // 2MiB
etagFile = ".etag"
lastModifiedFile = ".last-modified"
)

// Client is the autoconfig client
type Client struct {
httpClient *http.Client
cacheDir string
cacheSize int
userAgent string
maxResponseSize int64
}

// Option is a function that configures the client
type Option func(*Client) error

// NewClient creates a new autoconfig client with the given options
func NewClient(options ...Option) (*Client, error) {
c := &Client{
httpClient: &http.Client{Timeout: defaultTimeout},
cacheSize: defaultCacheSize,
maxResponseSize: defaultMaxResponseSize,
}

for _, opt := range options {
if err := opt(c); err != nil {
return nil, fmt.Errorf("failed to apply option: %w", err)
}
}

// Use temp dir if no cache dir provided
if c.cacheDir == "" {
tmpDir, err := os.MkdirTemp("", "ipfs-autoconfig-")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
c.cacheDir = tmpDir
log.Debugf("using temporary cache directory: %s", tmpDir)
}

return c, nil
}

// WithHTTPClient sets a custom HTTP client
func WithHTTPClient(client *http.Client) Option {
return func(c *Client) error {
if client == nil {
return fmt.Errorf("http client cannot be nil")
}
c.httpClient = client
return nil
}
}

// WithCacheDir sets the cache directory
func WithCacheDir(dir string) Option {
return func(c *Client) error {
c.cacheDir = dir
return nil
}
}

// WithCacheSize sets the maximum number of versions to keep in cache
func WithCacheSize(size int) Option {
return func(c *Client) error {
if size < 1 {
return fmt.Errorf("cache size must be at least 1")
}
c.cacheSize = size
return nil
}
}

// WithUserAgent sets the user agent for HTTP requests
func WithUserAgent(ua string) Option {
return func(c *Client) error {
c.userAgent = ua
return nil
}
}

// WithTimeout sets the HTTP client timeout
func WithTimeout(timeout time.Duration) Option {
return func(c *Client) error {
c.httpClient.Timeout = timeout
return nil
}
}

// WithTLSInsecureSkipVerify sets whether to skip TLS verification (for testing)
func WithTLSInsecureSkipVerify(skip bool) Option {
return func(c *Client) error {
if skip {
log.Warnf("TLS certificate verification is disabled - this should only be used for testing")
}
if c.httpClient.Transport == nil {
c.httpClient.Transport = http.DefaultTransport.(*http.Transport).Clone()
}
if t, ok := c.httpClient.Transport.(*http.Transport); ok {
if t.TLSClientConfig == nil {
t.TLSClientConfig = &tls.Config{}
}
t.TLSClientConfig.InsecureSkipVerify = skip
}
return nil
}
}

// sanitizeForPath sanitizes a string to be safe for use in file paths
func sanitizeForPath(s string) string {
// Replace any character that's not alphanumeric, dash, underscore, or dot
re := regexp.MustCompile(`[^a-zA-Z0-9\-_\.]`)
sanitized := re.ReplaceAllString(s, "_")
// Replace consecutive dots with a single underscore
re2 := regexp.MustCompile(`\.{2,}`)
return re2.ReplaceAllString(sanitized, "_")
}

// getCacheDir returns the cache directory for a given URL
func (c *Client) getCacheDir(configURL string) (string, error) {
u, err := url.Parse(configURL)
if err != nil {
return "", fmt.Errorf("failed to parse URL: %w", err)
}

host := sanitizeForPath(u.Host)
return filepath.Join(c.cacheDir, "autoconfig", host), nil
}

// readCachedMetadata reads cached ETag and Last-Modified values
func (c *Client) readCachedMetadata(cacheDir string) (etag, lastModified string) {
// Sanitize cache directory path
cleanCacheDir := filepath.Clean(cacheDir)

etagData, err := os.ReadFile(filepath.Join(cleanCacheDir, etagFile))
if err != nil {
log.Debugf("failed to read cached etag: %v", err)
}

lastModData, err := os.ReadFile(filepath.Join(cleanCacheDir, lastModifiedFile))
if err != nil {
log.Debugf("failed to read cached last-modified: %v", err)
}

return strings.TrimSpace(string(etagData)), strings.TrimSpace(string(lastModData))
}

// writeCachedMetadata writes ETag and Last-Modified values to cache
func (c *Client) writeCachedMetadata(cacheDir, etag, lastModified string) error {
// Sanitize cache directory path
cleanCacheDir := filepath.Clean(cacheDir)
if etag != "" {
// Use owner-only permissions (0600) for security
if err := os.WriteFile(filepath.Join(cleanCacheDir, etagFile), []byte(etag), 0600); err != nil {
return fmt.Errorf("failed to write etag: %w", err)
}
}
if lastModified != "" {
// Use owner-only permissions (0600) for security
if err := os.WriteFile(filepath.Join(cleanCacheDir, lastModifiedFile), []byte(lastModified), 0600); err != nil {
return fmt.Errorf("failed to write last-modified: %w", err)
}
}
return nil
}
Loading
Loading