Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(AutoTLS): opt-in WSS certs from p2p-forge at libp2p.direct #10521

Merged
merged 25 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
ce6d09d
feat: add ability to automatically acquire WSS certificates using p2p…
aschmahmann Sep 18, 2024
ecfc8d9
chore: update changelog
aschmahmann Sep 18, 2024
fe307da
refactor(config): Swarm.ForgeClient
lidel Sep 18, 2024
bfc73d0
fix: wire up config.ForgeClient settings
lidel Sep 20, 2024
7c9842e
refactor(forge): WithUserAgent + WithForgeAuth
lidel Sep 20, 2024
bef0a21
fix: p2p-forge require websocket transport
lidel Sep 20, 2024
06708d8
feat(forge): set certmagic default logger to use go-log
aschmahmann Sep 20, 2024
af543af
chore: logger name
lidel Oct 11, 2024
946298b
Merge master into feat/libp2p-direct
lidel Oct 11, 2024
d5994c1
chore: linter fix for deprecated config option
lidel Oct 11, 2024
7ae58bc
chore: bump p2p-forge client to 65145f8
lidel Oct 11, 2024
4889612
Merge branch 'master' into feat/libp2p-direct
lidel Oct 18, 2024
a038637
docs: Swarm.ForgeClient
lidel Oct 18, 2024
538c9bb
fix: p2p-forge log and debugging
lidel Oct 18, 2024
b306f56
chore(doc): add toc
lidel Oct 18, 2024
9bd8ebb
Merge branch 'master' into feat/libp2p-direct
lidel Oct 21, 2024
21b5c88
Merge remote-tracking branch 'origin/master' into feat/libp2p-direct
lidel Oct 23, 2024
7eeda1b
docs: apply suggestions from code review
lidel Oct 28, 2024
99b7757
refactor: ForgeClient → AutoTLS
lidel Oct 28, 2024
e6e0b7a
Merge branch 'master' into feat/libp2p-direct
lidel Oct 28, 2024
ed7e201
chore: rename logger to autotls
lidel Oct 28, 2024
e51d907
fix: p2p-forge/client with newCertmagicConfig
lidel Oct 28, 2024
73c3fd3
refactor: move AutoTLS to top level
lidel Oct 29, 2024
e68493a
docs: changelog + tracking next steps
lidel Oct 29, 2024
bcabbb4
docs: AutoTLS.Enabled
lidel Oct 29, 2024
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
30 changes: 30 additions & 0 deletions config/autotls.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package config

import p2pforge "github.com/ipshipyard/p2p-forge/client"

// AutoTLS includes optional configuration of p2p-forge client of service
// for obtaining a domain and TLS certificate to improve connectivity for web
// browser clients. More: https://github.com/ipshipyard/p2p-forge#readme
type AutoTLS struct {
// Enables the p2p-forge feature
Enabled Flag `json:",omitempty"`

// Optional override of the parent domain that will be used
DomainSuffix *OptionalString `json:",omitempty"`

// Optional override of HTTP API that acts as ACME DNS-01 Challenge broker
RegistrationEndpoint *OptionalString `json:",omitempty"`

// Optional Authorization token, used with private/test instances of p2p-forge
RegistrationToken *OptionalString `json:",omitempty"`

// Optional override of CA ACME API used by p2p-forge system
CAEndpoint *OptionalString `json:",omitempty"`
}

const (
DefaultAutoTLSEnabled = false // experimental, opt-in for now (https://github.com/ipfs/kubo/pull/10521)
DefaultDomainSuffix = p2pforge.DefaultForgeDomain
DefaultRegistrationEndpoint = p2pforge.DefaultForgeEndpoint
DefaultCAEndpoint = p2pforge.DefaultCAEndpoint
)
5 changes: 5 additions & 0 deletions config/swarm.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ type SwarmConfig struct {

// ResourceMgr configures the libp2p Network Resource Manager
ResourceMgr ResourceMgr

// AutoTLS controls the client of a service for obtaining and configuring a
// domain and TLS certificate to improve connectivity for web browser
// clients.
AutoTLS AutoTLS
}

type RelayClient struct {
Expand Down
21 changes: 21 additions & 0 deletions core/node/groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"strings"
"time"

"github.com/dustin/go-humanize"
Expand Down Expand Up @@ -113,6 +114,7 @@ func LibP2P(bcfg *BuildCfg, cfg *config.Config, userResourceOverrides rcmgr.Part
enableRelayTransport := cfg.Swarm.Transports.Network.Relay.WithDefault(true) // nolint
enableRelayService := cfg.Swarm.RelayService.Enabled.WithDefault(enableRelayTransport)
enableRelayClient := cfg.Swarm.RelayClient.Enabled.WithDefault(enableRelayTransport)
enableAutoTLS := cfg.Swarm.AutoTLS.Enabled.WithDefault(config.DefaultAutoTLSEnabled)

// Log error when relay subsystem could not be initialized due to missing dependency
if !enableRelayTransport {
Expand All @@ -123,6 +125,23 @@ func LibP2P(bcfg *BuildCfg, cfg *config.Config, userResourceOverrides rcmgr.Part
logger.Fatal("Failed to enable `Swarm.RelayClient`, it requires `Swarm.Transports.Network.Relay` to be true.")
}
}
if enableAutoTLS {
if !cfg.Swarm.Transports.Network.Websocket.WithDefault(true) {
logger.Fatal("Failed to enable `Swarm.AutoTLS`, it requires `Swarm.Transports.Network.Websocket` to be true.")
}

wssWildcard := fmt.Sprintf("/tls/sni/*.%s/ws", cfg.Swarm.AutoTLS.DomainSuffix.WithDefault(config.DefaultDomainSuffix))
wssWildcardPresent := false
for _, listener := range cfg.Addresses.Swarm {
if strings.Contains(listener, wssWildcard) {
wssWildcardPresent = true
break
}
}
if !wssWildcardPresent {
logger.Fatal(fmt.Sprintf("Failed to enable `Swarm.AutoTLS`, it requires `Addresses.Swarm` listener matching %q to be present, see https://github.com/ipfs/kubo/blob/master/docs/config.md#swarmautotls", wssWildcard))
}
}

// Gather all the options
opts := fx.Options(
Expand All @@ -133,6 +152,8 @@ func LibP2P(bcfg *BuildCfg, cfg *config.Config, userResourceOverrides rcmgr.Part

// Services (resource management)
fx.Provide(libp2p.ResourceManager(bcfg.Repo.Path(), cfg.Swarm, userResourceOverrides)),
maybeProvide(libp2p.P2PForgeCertMgr(cfg.Swarm.AutoTLS), enableAutoTLS),
maybeInvoke(libp2p.StartP2PAutoTLS, enableAutoTLS),
fx.Provide(libp2p.AddrFilters(cfg.Swarm.AddrFilters)),
fx.Provide(libp2p.AddrsFactory(cfg.Addresses.Announce, cfg.Addresses.AppendAnnounce, cfg.Addresses.NoAnnounce)),
fx.Provide(libp2p.SmuxTransport(cfg.Swarm.Transports)),
Expand Down
69 changes: 66 additions & 3 deletions core/node/libp2p/addrs.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
package libp2p

import (
"context"
"fmt"
"os"

logging "github.com/ipfs/go-log"
version "github.com/ipfs/kubo"
"github.com/ipfs/kubo/config"
p2pforge "github.com/ipshipyard/p2p-forge/client"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/host"
p2pbhost "github.com/libp2p/go-libp2p/p2p/host/basic"
ma "github.com/multiformats/go-multiaddr"
mamask "github.com/whyrusleeping/multiaddr-filter"

"github.com/caddyserver/certmagic"
"go.uber.org/fx"
)

func AddrFilters(filters []string) func() (*ma.Filters, Libp2pOpts, error) {
Expand Down Expand Up @@ -87,12 +97,26 @@ func makeAddrsFactory(announce []string, appendAnnouce []string, noAnnounce []st
}, nil
}

func AddrsFactory(announce []string, appendAnnouce []string, noAnnounce []string) func() (opts Libp2pOpts, err error) {
return func() (opts Libp2pOpts, err error) {
addrsFactory, err := makeAddrsFactory(announce, appendAnnouce, noAnnounce)
func AddrsFactory(announce []string, appendAnnouce []string, noAnnounce []string) interface{} {
return func(params struct {
fx.In
ForgeMgr *p2pforge.P2PForgeCertMgr `optional:"true"`
},
) (opts Libp2pOpts, err error) {
var addrsFactory p2pbhost.AddrsFactory
announceAddrsFactory, err := makeAddrsFactory(announce, appendAnnouce, noAnnounce)
if err != nil {
return opts, err
}
if params.ForgeMgr == nil {
addrsFactory = announceAddrsFactory
} else {
addrsFactory = func(multiaddrs []ma.Multiaddr) []ma.Multiaddr {
forgeProcessing := params.ForgeMgr.AddressFactory()(multiaddrs)
annouceProcessing := announceAddrsFactory(forgeProcessing)
return annouceProcessing
}
}
opts.Opts = append(opts.Opts, libp2p.AddrsFactory(addrsFactory))
return
}
Expand All @@ -107,3 +131,42 @@ func ListenOn(addresses []string) interface{} {
}
}
}

func P2PForgeCertMgr(cfg config.AutoTLS) interface{} {
return func() (*p2pforge.P2PForgeCertMgr, error) {
storagePath, err := config.Path("", "p2p-forge-certs")
if err != nil {
return nil, err
}

forgeLogger := logging.Logger("autotls").Desugar()
certStorage := &certmagic.FileStorage{Path: storagePath}
certMgr, err := p2pforge.NewP2PForgeCertMgr(
p2pforge.WithLogger(forgeLogger.Sugar()),
p2pforge.WithForgeDomain(cfg.DomainSuffix.WithDefault(config.DefaultDomainSuffix)),
p2pforge.WithForgeRegistrationEndpoint(cfg.RegistrationEndpoint.WithDefault(config.DefaultRegistrationEndpoint)),
p2pforge.WithCAEndpoint(cfg.CAEndpoint.WithDefault(config.DefaultCAEndpoint)),
p2pforge.WithForgeAuth(cfg.RegistrationToken.WithDefault(os.Getenv(p2pforge.ForgeAuthEnv))),
p2pforge.WithUserAgent(version.GetUserAgentVersion()),
p2pforge.WithCertificateStorage(certStorage),
)
if err != nil {
return nil, err
}

return certMgr, nil
}
}

func StartP2PAutoTLS(lc fx.Lifecycle, certMgr *p2pforge.P2PForgeCertMgr, h host.Host) {
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
certMgr.ProvideHost(h)
return certMgr.Start()
},
OnStop: func(ctx context.Context) error {
certMgr.Stop()
return nil
},
})
}
15 changes: 10 additions & 5 deletions core/node/libp2p/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package libp2p

import (
"fmt"

"github.com/ipfs/kubo/config"
"github.com/ipshipyard/p2p-forge/client"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/metrics"
quic "github.com/libp2p/go-libp2p/p2p/transport/quic"
Expand All @@ -16,20 +16,25 @@ import (
)

func Transports(tptConfig config.Transports) interface{} {
return func(pnet struct {
return func(params struct {
fx.In
Fprint PNetFingerprint `optional:"true"`
Fprint PNetFingerprint `optional:"true"`
ForgeMgr *client.P2PForgeCertMgr `optional:"true"`
},
) (opts Libp2pOpts, err error) {
privateNetworkEnabled := pnet.Fprint != nil
privateNetworkEnabled := params.Fprint != nil

if tptConfig.Network.TCP.WithDefault(true) {
// TODO(9290): Make WithMetrics configurable
opts.Opts = append(opts.Opts, libp2p.Transport(tcp.NewTCPTransport, tcp.WithMetrics()))
}

if tptConfig.Network.Websocket.WithDefault(true) {
opts.Opts = append(opts.Opts, libp2p.Transport(websocket.New))
if params.ForgeMgr == nil {
opts.Opts = append(opts.Opts, libp2p.Transport(websocket.New))
} else {
opts.Opts = append(opts.Opts, libp2p.Transport(websocket.New, websocket.WithTLSConfig(params.ForgeMgr.TLSConfig())))
}
}

if tptConfig.Network.QUIC.WithDefault(!privateNetworkEnabled) {
Expand Down
8 changes: 7 additions & 1 deletion docs/changelogs/v0.32.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Kubo changelog v0.32

- [v0.31.0](#v0320)
- [v0.32.0](#v0310)

## v0.32.0

Expand All @@ -15,6 +15,12 @@

### 🔦 Highlights

#### 🎯 Opt-in `/wss` Certificates via libp2p.direct
lidel marked this conversation as resolved.
Show resolved Hide resolved

This release introduces an experimental feature that significantly improves how browsers can connect to Kubo node.
Opt-in configuration allows Kubo node to obtain trusted certificates for Secure WebSocket (WSS) connections without manual intervention.
lidel marked this conversation as resolved.
Show resolved Hide resolved

See [`Swarm.AutoTLS`](https://github.com/ipfs/kubo/blob/master/docs/config.md#swarmforgeclient) for details how to enable it. We appreciate you testing and providing an early feedback.

#### go-libp2p updates

Expand Down
88 changes: 87 additions & 1 deletion docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ config file at runtime.
- [`Swarm.DisableBandwidthMetrics`](#swarmdisablebandwidthmetrics)
- [`Swarm.DisableNatPortMap`](#swarmdisablenatportmap)
- [`Swarm.EnableHolePunching`](#swarmenableholepunching)
- [`Swarm.AutoTLS`](#swarmautotls)
- [`Swarm.AutoTLS.Enabled`](#swarmautotlsenabled)
- [`Swarm.AutoTLS.DomainSuffix`](#swarmautotlsdomainsuffix)
- [`Swarm.AutoTLS.RegistrationEndpoint`](#swarmautotlsregistrationendpoint)
- [`Swarm.AutoTLS.RegistrationToken`](#swarmautotlsregistrationtoken)
- [`Swarm.AutoTLS.CAEndpoint`](#swarmautotlscaendpoint)
- [`Swarm.EnableAutoRelay`](#swarmenableautorelay)
- [`Swarm.RelayClient`](#swarmrelayclient)
- [`Swarm.RelayClient.Enabled`](#swarmrelayclientenabled)
Expand Down Expand Up @@ -1716,6 +1722,86 @@ Default: `true`

Type: `flag`

### `Swarm.AutoTLS`

AutoTLS enables publicly reachable Kubo nodes (those dialable from the public
internet) to automatically obtain a wildcard TLS certificate for a DNS name
unique to their PeerID at `*.[PeerID].libp2p.direct`. This enables direct
libp2p connections and retrieval of IPFS content from browsers using Secure
WebSockets, without requiring manual domain registration and configuration.

Under the hood, `libp2p.direct` acts as an [ACME DNS-01 Challenge](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge)
broker for obtaining these wildcard TLS certificates.

By default, the certificates are requested from Let's Encrypt.
Origin and rationale for this project can be found in [community.letsencrypt.org discussion].
lidel marked this conversation as resolved.
Show resolved Hide resolved

> [!NOTE]
> Public good infrastructure at `libp2p.direct` is run by the team at [Interplanetary Shipyard](https://ipshipyard.com).
>
> <a href="http://ipshipyard.com/"><img src="https://github.com/user-attachments/assets/39ed3504-bb71-47f6-9bf8-cb9a1698f272" /></a>

[p2p-forge]: https://github.com/ipshipyard/p2p-forge
[community.letsencrypt.org discussion]: https://community.letsencrypt.org/t/feedback-on-raising-certificates-per-registered-domain-to-enable-peer-to-peer-networking/223003

Default: `{}`

Type: `object`

#### `Swarm.AutoTLS.Enabled`

> [!CAUTION]
> This is an EXPERIMENTAL feature and should not be used in production yet.
2color marked this conversation as resolved.
Show resolved Hide resolved
> Feel free to enable it and [report issues](https://github.com/ipfs/kubo/issues/new/choose) if you want to help with testing.

Enables **EXPERIMENTAL** [p2p-forge] client. This feature works only if your Kubo node is publicly diallable.

If enabled, it will detect when `.../tls/sni/.../ws` is present in [`Addresses.Swarm`](#addressesswarm)
and SNI is matching `Swarm.AutoTLS.DomainSuffix`, and set up a trusted TLS certificate matching the domain name used in Secure WebSockets (WSS) listener.

If you want to test this, add `/ip4/0.0.0.0/tcp/4082/tls/sni/*.libp2p.direct/ws` to [`Addresses.Swarm`](#addressesswarm).
Copy link
Member

Choose a reason for hiding this comment

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

Why is port 4082 used here?

Can you use the same port as the /ws address: /ip4/0.0.0.0/tcp/4002/ws?

Copy link
Member

Choose a reason for hiding this comment

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

Not yet, we need libp2p/go-libp2p#2984 for that.

The idea is that TCP port sharing will land in go-libp2p before we enable AutoTLS by default.
For opt-in, using separate port is fine, just need to remember to remind people that they need to safelist additional port on their firewall.


Debugging can be enabled by setting environment variable `GOLOG_LOG_LEVEL="error,autotls=debug,p2p-forge/client=debug"`

Default: `false`

Type: `flag`

#### `Swarm.AutoTLS.DomainSuffix`

Optional override of the parent domain suffix that will be used in DNS+TLS+WebSockets multiaddrs generated by [p2p-forge] client.
Do not change this unless you self-host [p2p-forge].

Default: `libp2p.direct` (public good run by [Interplanetary Shipyard](https://ipshipyard.com))

Type: `optionalString`

#### `Swarm.AutoTLS.RegistrationEndpoint`

Optional override of [p2p-forge] HTTP registration API.
Do not change this unless you self-host [p2p-forge].

Default: `https://registration.libp2p.direct` (public good run by [Interplanetary Shipyard](https://ipshipyard.com))

Type: `optionalString`

#### `Swarm.AutoTLS.RegistrationToken`

Optional value for `Forge-Authorization` token sent with request to `RegistrationEndpoint`
(useful for private/self-hosted/test instances of [p2p-forge]).

Default: `""`

Type: `optionalString`

#### `Swarm.AutoTLS.CAEndpoint`

Optional override of CA ACME API used by [p2p-forge] system.

Default: [certmagic.LetsEncryptProductionCA](https://pkg.go.dev/github.com/caddyserver/certmagic#pkg-constants) (see [community.letsencrypt.org discussion])

Type: `optionalString`

### `Swarm.EnableAutoRelay`

**REMOVED**
Expand Down Expand Up @@ -1835,7 +1921,7 @@ Type: `optionalInteger`

#### `Swarm.RelayService.MaxReservationsPerPeer`

**REMOVED in kubo 0.32 due to removal from go-libp2p v0.37**
**REMOVED in kubo 0.32 due to [go-libp2p#2974](https://github.com/libp2p/go-libp2p/pull/2974)**

#### `Swarm.RelayService.MaxReservationsPerIP`

Expand Down
Loading
Loading