CodeSampleX

Пример

github.com/caddyserver/certmagic v0.23.0: Certificate

Проверенный пример — golang github.com/caddyserver/certmagic v0.23.0: Certificate. Контракт выполнен на go 1.26 · linux alpine/x64 · docker и пройден.

sha256:06dc27eb305e82ad63b693592fff6f26b259b68119092e13f6e038d2e44a8c16

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-28

Кейс

HOW
Цель
verify github.com/caddyserver/certmagic.Certificate in pkg:golang/github.com/caddyserver/certmagic@v0.23.0
Пакеты
Символы
  • github.com/caddyserver/certmagic.Certificate
Создан
2026-08-28T02:10:03Z

Контракт

  1. Certificate.Empty returns true for zero-value struct and false when Certificate bytes are populated
  2. Certificate.HasTag checks for presence of arbitrary tags in the Tags slice
  3. Certificate.Lifetime calculates the total validity duration from Leaf NotBefore and NotAfter
  4. Certificate.Expired returns true when current time is after leaf expiration and false otherwise
  5. Certificate.NeedsRenewal evaluates whether a certificate is due for renewal under Config renewal window
  6. DefaultCertificateSelector selects the first non-expired supported certificate and returns error on empty choices

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify github.com/caddyserver/certmagic.Certificate in pkg:golang/github.com/caddyserver/certmagic@v0.23.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/caddyserver/certmagic@v0.23.0
Demonstrate these symbols/APIs:
  - github.com/caddyserver/certmagic.Certificate

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:7795436d94aec050bad0c2af6aa97bcf483e0753f538aeb9c00d59e4b78c5b62","contract":["Certificate.Empty returns true for zero-value struct and false when Certificate bytes are populated","Certificate.HasTag checks for presence of arbitrary tags in the Tags slice","Certificate.Lifetime calculates the total validity duration from Leaf NotBefore and NotAfter","Certificate.Expired returns true when current time is after leaf expiration and false otherwise","Certificate.NeedsRenewal evaluates whether a certificate is due for renewal under Config renewal window","DefaultCertificateSelector selects the first non-expired supported certificate and returns error on empty choices"],"goal":"verify github.com/caddyserver/certmagic.Certificate in pkg:golang/github.com/caddyserver/certmagic@v0.23.0","kind":"HOW","packages":["pkg:golang/github.com/caddyserver/certmagic@v0.23.0"],"schemaVersion":1,"symbols":["github.com/caddyserver/certmagic.Certificate"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/caddyserver/certmagic@v0.23.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/caddyserver/certmagic@v0.23.0","symbols":["github.com/caddyserver/certmagic.Certificate"],"verifierAdapter":"golang@1"}
go.mod
module sample-certmagic

go 1.26.6

require github.com/caddyserver/certmagic v0.23.0

require (
	github.com/caddyserver/zerossl v0.1.3 // indirect
	github.com/klauspost/cpuid/v2 v2.2.10 // indirect
	github.com/libdns/libdns v1.0.0-beta.1 // indirect
	github.com/mholt/acmez/v3 v3.1.2 // indirect
	github.com/miekg/dns v1.1.63 // indirect
	github.com/zeebo/blake3 v0.2.4 // indirect
	go.uber.org/multierr v1.11.0 // indirect
	go.uber.org/zap v1.27.0 // indirect
	go.uber.org/zap/exp v0.3.0 // indirect
	golang.org/x/crypto v0.36.0 // indirect
	golang.org/x/mod v0.24.0 // indirect
	golang.org/x/net v0.37.0 // indirect
	golang.org/x/sync v0.12.0 // indirect
	golang.org/x/sys v0.31.0 // indirect
	golang.org/x/text v0.23.0 // indirect
	golang.org/x/tools v0.31.0 // indirect
)
go.sum
github.com/caddyserver/certmagic v0.23.0 h1:CfpZ/50jMfG4+1J/u2LV6piJq4HOfO6ppOnOf7DkFEU=
github.com/caddyserver/certmagic v0.23.0/go.mod h1:9mEZIWqqWoI+Gf+4Trh04MOVPD0tGSxtqsxg87hAIH4=
github.com/caddyserver/zerossl v0.1.3 h1:onS+pxp3M8HnHpN5MMbOMyNjmTheJyWRaZYwn+YTAyA=
github.com/caddyserver/zerossl v0.1.3/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/libdns/libdns v1.0.0-beta.1 h1:KIf4wLfsrEpXpZ3vmc/poM8zCATXT2klbdPe6hyOBjQ=
github.com/libdns/libdns v1.0.0-beta.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=
github.com/mholt/acmez/v3 v3.1.2 h1:auob8J/0FhmdClQicvJvuDavgd5ezwLBfKuYmynhYzc=
github.com/mholt/acmez/v3 v3.1.2/go.mod h1:L1wOU06KKvq7tswuMDwKdcHeKpFFgkppZy/y0DFxagQ=
github.com/miekg/dns v1.1.63 h1:8M5aAw6OMZfFXTT7K5V0Eu5YiiL8l7nUAkyN6C9YwaY=
github.com/miekg/dns v1.1.63/go.mod h1:6NGHfjhpmr5lt3XPLuyfDJi5AXbNIPM9PY6H6sF1Nfs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=
github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE=
github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo=
github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=
go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ=
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
main.go
package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"math/big"
	"time"

	"github.com/caddyserver/certmagic"
)

func main() {
	privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		fmt.Printf("failed to generate key: %v\n", err)
		return
	}

	notBefore := time.Now().Add(-1 * time.Hour)
	notAfter := time.Now().Add(24 * time.Hour)

	template := &x509.Certificate{
		SerialNumber: big.NewInt(1001),
		Subject: pkix.Name{
			CommonName: "example.com",
		},
		DNSNames:  []string{"example.com", "api.example.com"},
		NotBefore: notBefore,
		NotAfter:  notAfter,
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &privKey.PublicKey, privKey)
	if err != nil {
		fmt.Printf("failed to create certificate: %v\n", err)
		return
	}

	parsed, err := x509.ParseCertificate(derBytes)
	if err != nil {
		fmt.Printf("failed to parse certificate: %v\n", err)
		return
	}

	cert := certmagic.Certificate{
		Names: []string{"example.com", "api.example.com"},
		Tags:  []string{"production", "web"},
	}
	cert.Certificate.Certificate = [][]byte{derBytes}
	cert.Certificate.Leaf = parsed

	fmt.Printf("Certificate empty: %v\n", cert.Empty())
	fmt.Printf("Has 'production' tag: %v\n", cert.HasTag("production"))
	fmt.Printf("Certificate expired: %v\n", cert.Expired())
	fmt.Printf("Certificate lifetime: %v\n", cert.Lifetime())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/caddyserver/certmagic.Certificate in pkg:golang/github.com/caddyserver/certmagic@v0.23.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/caddyserver/certmagic@v0.23.0"
  ],
  "symbols": [
    "github.com/caddyserver/certmagic.Certificate"
  ]
}
test/contract.go
package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"math/big"
	"os"
	"time"

	"github.com/caddyserver/certmagic"
)

func makeCert(dnsNames []string, notBefore, notAfter time.Time) (certmagic.Certificate, error) {
	privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return certmagic.Certificate{}, err
	}

	serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	if err != nil {
		return certmagic.Certificate{}, err
	}

	template := &x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			CommonName: dnsNames[0],
		},
		DNSNames:              dnsNames,
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &privKey.PublicKey, privKey)
	if err != nil {
		return certmagic.Certificate{}, err
	}

	parsed, err := x509.ParseCertificate(derBytes)
	if err != nil {
		return certmagic.Certificate{}, err
	}

	cert := certmagic.Certificate{
		Certificate: tls.Certificate{
			Certificate: [][]byte{derBytes},
			PrivateKey:  privKey,
			Leaf:        parsed,
		},
		Names: dnsNames,
	}
	return cert, nil
}

func main() {
	// Assertion 1: Certificate.Empty returns true for zero-value struct and false when Certificate bytes are present
	var zeroCert certmagic.Certificate
	if !zeroCert.Empty() {
		fmt.Fprintf(os.Stderr, "FAIL: zero-value Certificate should be empty\n")
		os.Exit(1)
	}

	now := time.Now()
	validCert, err := makeCert([]string{"example.com"}, now.Add(-1*time.Hour), now.Add(24*time.Hour))
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: makeCert error: %v\n", err)
		os.Exit(1)
	}
	if validCert.Empty() {
		fmt.Fprintf(os.Stderr, "FAIL: populated Certificate should not be empty\n")
		os.Exit(1)
	}

	// Assertion 2: Certificate.HasTag returns true if the tag exists in Tags and false otherwise
	validCert.Tags = []string{"edge", "production"}
	if !validCert.HasTag("edge") || !validCert.HasTag("production") {
		fmt.Fprintf(os.Stderr, "FAIL: HasTag should return true for present tags\n")
		os.Exit(1)
	}
	if validCert.HasTag("staging") {
		fmt.Fprintf(os.Stderr, "FAIL: HasTag should return false for absent tags\n")
		os.Exit(1)
	}

	// Assertion 3: Certificate.Lifetime calculates the total validity duration from Leaf NotBefore and NotAfter
	lifetime := validCert.Lifetime()
	expectedMinLifetime := 25 * time.Hour
	if lifetime < expectedMinLifetime || lifetime > expectedMinLifetime+2*time.Second {
		fmt.Fprintf(os.Stderr, "FAIL: unexpected lifetime: %v (expected ~25h)\n", lifetime)
		os.Exit(1)
	}
	if zeroCert.Lifetime() != 0 {
		fmt.Fprintf(os.Stderr, "FAIL: zeroCert lifetime should be 0, got %v\n", zeroCert.Lifetime())
		os.Exit(1)
	}

	// Assertion 4: Certificate.Expired returns true when current time is after leaf expiration and false otherwise
	if validCert.Expired() {
		fmt.Fprintf(os.Stderr, "FAIL: validCert should not be expired\n")
		os.Exit(1)
	}
	expiredCert, err := makeCert([]string{"expired.example.com"}, now.Add(-48*time.Hour), now.Add(-24*time.Hour))
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: make expired cert error: %v\n", err)
		os.Exit(1)
	}
	if !expiredCert.Expired() {
		fmt.Fprintf(os.Stderr, "FAIL: expiredCert should be expired\n")
		os.Exit(1)
	}

	// Assertion 5: Certificate.NeedsRenewal evaluates whether a certificate is due for renewal under Config renewal window
	cfg := certmagic.NewDefault()
	// An expired cert or nearly expired cert needs renewal
	if !expiredCert.NeedsRenewal(cfg) {
		fmt.Fprintf(os.Stderr, "FAIL: expiredCert should need renewal\n")
		os.Exit(1)
	}
	// A fresh certificate with 90 days validity of which 1 hour has passed should not need renewal
	freshCert, err := makeCert([]string{"fresh.example.com"}, now.Add(-1*time.Hour), now.Add(90*24*time.Hour))
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: make fresh cert error: %v\n", err)
		os.Exit(1)
	}
	if freshCert.NeedsRenewal(cfg) {
		fmt.Fprintf(os.Stderr, "FAIL: freshCert should not need renewal\n")
		os.Exit(1)
	}

	// Assertion 6: DefaultCertificateSelector selects the first non-expired supported certificate and returns error on empty choices
	_, err = certmagic.DefaultCertificateSelector(&tls.ClientHelloInfo{}, []certmagic.Certificate{})
	if err == nil {
		fmt.Fprintf(os.Stderr, "FAIL: DefaultCertificateSelector should return error on empty choices\n")
		os.Exit(1)
	}

	singleChoice, err := certmagic.DefaultCertificateSelector(&tls.ClientHelloInfo{}, []certmagic.Certificate{validCert})
	if err != nil || singleChoice.Empty() || singleChoice.Names[0] != "example.com" {
		fmt.Fprintf(os.Stderr, "FAIL: DefaultCertificateSelector failed on single choice: %v\n", err)
		os.Exit(1)
	}

	// When given [expiredCert, validCert], selector prefers the unexpired one supported by client
	hello := &tls.ClientHelloInfo{
		ServerName: "example.com",
		SupportedVersions: []uint16{tls.VersionTLS13},
		SignatureSchemes: []tls.SignatureScheme{tls.ECDSAWithP256AndSHA256},
	}
	multiChoice, err := certmagic.DefaultCertificateSelector(hello, []certmagic.Certificate{expiredCert, validCert})
	if err != nil || multiChoice.Names[0] != "example.com" {
		fmt.Fprintf(os.Stderr, "FAIL: DefaultCertificateSelector did not pick validCert: %v, chosen: %+v\n", err, multiChoice.Names)
		os.Exit(1)
	}

	fmt.Println("Contract test passed successfully.")
}

Исходный сидер

аноним