chore: hide autotls under compile flag (#1533)

This commit is contained in:
richΛrd
2025-07-14 13:52:33 -04:00
committed by GitHub
parent e83bd2d582
commit eee8341ad2
9 changed files with 645 additions and 612 deletions

View File

@@ -119,6 +119,11 @@ Enable quic transport support
nim c -d:libp2p_quic_support some_file.nim
```
Enable autotls support
```bash
nim c -d:libp2p_autotls_support some_file.nim
```
Enable expensive metrics (ie, metrics with per-peer cardinality):
```bash
nim c -d:libp2p_expensive_metrics some_file.nim

View File

@@ -30,7 +30,7 @@ proc runTest(filename: string, moreoptions: string = "") =
excstr.add(" " & moreoptions & " ")
if getEnv("CICOV").len > 0:
excstr &= " --nimcache:nimcache/" & filename & "-" & $excstr.hash
exec excstr & " -r -d:libp2p_quic_support tests/" & filename
exec excstr & " -r -d:libp2p_quic_support -d:libp2p_autotls_support tests/" & filename
rmFile "tests/" & filename.toExe
proc buildSample(filename: string, run = false, extraFlags = "") =

View File

@@ -1,6 +1,6 @@
import options, sequtils, strutils, json, uri
import json, uri
from times import DateTime, parse
import chronos/apps/http/httpclient, jwt, results, bearssl/pem, chronicles
import chronos/apps/http/httpclient, results, chronicles
import ./utils
import ../../crypto/crypto
@@ -158,6 +158,9 @@ type ACMECertificateResponse* = object
rawCertificate*: string
certificateExpiry*: DateTime
when defined(libp2p_autotls_support):
import options, sequtils, strutils, jwt, bearssl/pem
template handleError*(msg: string, body: untyped): untyped =
try:
body
@@ -301,7 +304,8 @@ proc requestRegister*(
let acmeResponseBody = acmeResponse.body.to(ACMERegisterResponseBody)
ACMERegisterResponse(
status: acmeResponseBody.status, kid: acmeResponse.headers.keyOrError("location")
status: acmeResponseBody.status,
kid: acmeResponse.headers.keyOrError("location"),
)
proc requestNewOrder*(
@@ -340,12 +344,15 @@ proc requestAuthorizations*(
proc requestChallenge*(
self: ACMEApi, domains: seq[Domain], key: KeyPair, kid: Kid
): Future[ACMEChallengeResponseWrapper] {.async: (raises: [ACMEError, CancelledError]).} =
): Future[ACMEChallengeResponseWrapper] {.
async: (raises: [ACMEError, CancelledError])
.} =
let orderResponse = await self.requestNewOrder(domains, key, kid)
if orderResponse.status != ACMEOrderStatus.PENDING and
orderResponse.status != ACMEOrderStatus.READY:
# ready is a valid status when renewing certs before expiry
raise newException(ACMEError, "Invalid new order status: " & $orderResponse.status)
raise
newException(ACMEError, "Invalid new order status: " & $orderResponse.status)
let authorizationsResponse =
await self.requestAuthorizations(orderResponse.authorizations, key, kid)
@@ -388,7 +395,8 @@ proc requestCheck*(
try:
ACMECheckResponse(
kind: checkKind,
chalStatus: parseEnum[ACMEChallengeStatus](acmeResponse.body["status"].getStr),
chalStatus:
parseEnum[ACMEChallengeStatus](acmeResponse.body["status"].getStr),
retryAfter: retryAfter,
)
except ValueError:
@@ -413,7 +421,8 @@ proc checkChallengeCompleted*(
retries: int = DefaultChalCompletedRetries,
): Future[bool] {.async: (raises: [ACMEError, CancelledError]).} =
for i in 0 .. retries:
let checkResponse = await self.requestCheck(checkURL, ACMEChallengeCheck, key, kid)
let checkResponse =
await self.requestCheck(checkURL, ACMEChallengeCheck, key, kid)
case checkResponse.chalStatus
of ACMEChallengeStatus.PENDING:
await sleepAsync(checkResponse.retryAfter) # try again after some delay
@@ -507,3 +516,6 @@ proc downloadCertificate*(
proc close*(self: ACMEApi) {.async: (raises: [CancelledError]).} =
await self.session.closeWait()
else:
{.hint: "autotls disabled. Use -d:libp2p_autotls_support".}

View File

@@ -28,6 +28,7 @@ type ACMEClient* = ref object
logScope:
topics = "libp2p acme client"
when defined(libp2p_autotls_support):
proc new*(
T: typedesc[ACMEClient],
rng: ref HmacDrbgContext = newRng(),
@@ -52,7 +53,9 @@ proc genKeyAuthorization*(self: ACMEClient, token: string): KeyAuthorization =
proc getChallenge*(
self: ACMEClient, domains: seq[api.Domain]
): Future[ACMEChallengeResponseWrapper] {.async: (raises: [ACMEError, CancelledError]).} =
): Future[ACMEChallengeResponseWrapper] {.
async: (raises: [ACMEError, CancelledError])
.} =
await self.api.requestChallenge(domains, self.key, await self.getOrInitKid())
proc getCertificate*(
@@ -62,22 +65,26 @@ proc getCertificate*(
let orderURL = parseUri(challenge.order)
let finalizeURL = parseUri(challenge.finalize)
trace "sending challenge completed notification"
discard
await self.api.sendChallengeCompleted(chalURL, self.key, await self.getOrInitKid())
discard await self.api.sendChallengeCompleted(
chalURL, self.key, await self.getOrInitKid()
)
trace "checking for completed challenge"
let completed =
await self.api.checkChallengeCompleted(chalURL, self.key, await self.getOrInitKid())
let completed = await self.api.checkChallengeCompleted(
chalURL, self.key, await self.getOrInitKid()
)
if not completed:
raise
newException(ACMEError, "Failed to signal ACME server about challenge completion")
raise newException(
ACMEError, "Failed to signal ACME server about challenge completion"
)
trace "waiting for certificate to be finalized"
let finalized = await self.api.certificateFinalized(
domain, finalizeURL, orderURL, self.key, await self.getOrInitKid()
)
if not finalized:
raise newException(ACMEError, "Failed to finalize certificate for domain " & domain)
raise
newException(ACMEError, "Failed to finalize certificate for domain " & domain)
trace "downloading certificate"
await self.api.downloadCertificate(orderURL)

View File

@@ -73,6 +73,7 @@ type AutotlsService* = ref object of Service
peerInfo: PeerInfo
rng: ref HmacDrbgContext
when defined(libp2p_autotls_support):
proc new*(T: typedesc[AutotlsCert], cert: TLSCertificate, expiry: Moment): T =
T(cert: cert, expiry: expiry)
@@ -104,7 +105,8 @@ proc new*(
config: AutotlsConfig = AutotlsConfig.new(),
): T =
T(
acmeClient: ACMEClient.new(api = ACMEApi.new(acmeServerURL = config.acmeServerURL)),
acmeClient:
ACMEClient.new(api = ACMEApi.new(acmeServerURL = config.acmeServerURL)),
brokerClient: PeerIDAuthClient.new(),
bearer: Opt.none(BearerToken),
cert: Opt.none(AutotlsCert),
@@ -133,7 +135,9 @@ method setup*(
method issueCertificate(
self: AutotlsService
) {.base, async: (raises: [AutoTLSError, ACMEError, PeerIDAuthError, CancelledError]).} =
) {.
base, async: (raises: [AutoTLSError, ACMEError, PeerIDAuthError, CancelledError])
.} =
trace "Issuing certificate"
assert not self.peerInfo.isNil(), "Cannot issue new certificate: peerInfo not set"

View File

@@ -6,23 +6,11 @@
# at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
{.push raises: [].}
{.push public.}
import net, strutils
from times import DateTime, toTime, toUnix
import chronos, stew/base36, chronicles
import
./acme/client,
../errors,
../peerid,
../multihash,
../cid,
../multicodec,
../nameresolving/dnsresolver
import chronos
import ../errors
const
DefaultDnsRetries = 10
@@ -30,6 +18,18 @@ const
type AutoTLSError* = object of LPError
when defined(libp2p_autotls_support):
import net, strutils
from times import DateTime, toTime, toUnix
import stew/base36, chronicles
import
../peerid,
../multihash,
../cid,
../multicodec,
../nameresolving/dnsresolver,
./acme/client
proc checkedGetPrimaryIPAddr*(): IpAddress {.raises: [AutoTLSError].} =
# This is so that we don't need to catch Exceptions directly
# since we support 1.6.16 and getPrimaryIPAddr before nim 2 didn't have explicit .raises. pragmas

View File

@@ -257,6 +257,7 @@ proc withAutonat*(b: SwitchBuilder): SwitchBuilder =
b.autonat = true
b
when defined(libp2p_autotls_support):
proc withAutotls*(
b: SwitchBuilder, config: AutotlsConfig = AutotlsConfig.new()
): SwitchBuilder {.public.} =

View File

@@ -10,4 +10,5 @@ when defined(linux) and defined(amd64):
# This file may not be copied, modified, or distributed except according to
# those terms.
when defined(libp2p_autotls_support):
import testpeeridauth_integration, testautotls_integration

View File

@@ -28,10 +28,13 @@ import
transports/tls/testcertificate
import
testautotls, testnameresolve, testmultistream, testbufferstream, testidentify,
testnameresolve, testmultistream, testbufferstream, testidentify,
testobservedaddrmanager, testconnmngr, testswitch, testnoise, testpeerinfo,
testpeerstore, testping, testmplex, testrelayv1, testrelayv2, testrendezvous,
testdiscovery, testyamux, testautonat, testautonatservice, testautorelay, testdcutr,
testhpservice, testutility, testhelpers, testwildcardresolverservice, testperf
import kademlia/[testencoding, testroutingtable]
when defined(libp2p_autotls_support):
import testautotls