CodeSampleX

Пример

github.com/caddyserver/certmagic v0.25.3: CacheOptions

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

sha256:70d4f13b6f734bef4f12ba36bc5ae67efb83b76ecf52af0897b4e38edddf9db5

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

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

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

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

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

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

Кейс

HOW
Цель
verify github.com/caddyserver/certmagic.CacheOptions in pkg:golang/github.com/caddyserver/certmagic@v0.25.3
Пакеты
Символы
  • github.com/caddyserver/certmagic.CacheOptions
Окружение
go 1.26.6
Создан
2026-09-04T12:16:39Z

Контракт

  1. certmagic.NewCache panics when CacheOptions.GetConfigForCert is not provided.
  2. certmagic.NewCache initializes an active Cache given valid CacheOptions including GetConfigForCert, Capacity, and check intervals.
  3. Cache.SetOptions dynamically updates CacheOptions on an existing cache instance.
  4. Cache.SetOptions panics if updated CacheOptions has nil GetConfigForCert.
  5. Cache created with CacheOptions integrates with certmagic.New to store and query certificates.

Файлы

  • 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.CacheOptions in pkg:golang/github.com/caddyserver/certmagic@v0.25.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/caddyserver/certmagic@v0.25.3
Demonstrate these symbols/APIs:
  - github.com/caddyserver/certmagic.CacheOptions
Required runtime conditions:
  - ecosystem: golang
  - language: go
  - packageManager: go@1.26.6
  - runtime: go@1.26.6

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:7a11685cb8e1c2106a65aa4eda8e657bd8d6a5cee57beb1f7134b8f20719b369","contract":["certmagic.NewCache panics when CacheOptions.GetConfigForCert is not provided.","certmagic.NewCache initializes an active Cache given valid CacheOptions including GetConfigForCert, Capacity, and check intervals.","Cache.SetOptions dynamically updates CacheOptions on an existing cache instance.","Cache.SetOptions panics if updated CacheOptions has nil GetConfigForCert.","Cache created with CacheOptions integrates with certmagic.New to store and query certificates."],"goal":"verify github.com/caddyserver/certmagic.CacheOptions in pkg:golang/github.com/caddyserver/certmagic@v0.25.3","kind":"HOW","packages":["pkg:golang/github.com/caddyserver/certmagic@v0.25.3"],"schemaVersion":1,"symbols":["github.com/caddyserver/certmagic.CacheOptions"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/caddyserver/certmagic@v0.25.3"],"schemaVersion":1,"subject":"pkg:golang/github.com/caddyserver/certmagic@v0.25.3","symbols":["github.com/caddyserver/certmagic.CacheOptions"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	github.com/caddyserver/certmagic v0.25.3 // indirect
	github.com/caddyserver/zerossl v0.1.5 // indirect
	github.com/klauspost/cpuid/v2 v2.3.0 // indirect
	github.com/libdns/libdns v1.1.1 // indirect
	github.com/mholt/acmez/v3 v3.1.6 // indirect
	github.com/miekg/dns v1.1.72 // indirect
	github.com/zeebo/blake3 v0.2.4 // indirect
	go.uber.org/multierr v1.11.0 // indirect
	go.uber.org/zap v1.27.1 // indirect
	go.uber.org/zap/exp v0.3.0 // indirect
	golang.org/x/crypto v0.50.0 // indirect
	golang.org/x/mod v0.35.0 // indirect
	golang.org/x/net v0.53.0 // indirect
	golang.org/x/sync v0.20.0 // indirect
	golang.org/x/sys v0.43.0 // indirect
	golang.org/x/text v0.36.0 // indirect
	golang.org/x/tools v0.44.0 // indirect
)
go.sum
github.com/caddyserver/certmagic v0.25.3 h1:mGf5ba8F7xA4c5jfDZZbK2buY1VEkbnwpMDixaju94A=
github.com/caddyserver/certmagic v0.25.3/go.mod h1:YVs43D5+H/Dckt4bTga1KSO/xYfFBfVZainGDywYPAA=
github.com/caddyserver/zerossl v0.1.5 h1:dkvOjBAEEtY6LIGAHei7sw2UgqSD6TrWweXpV7lvEvE=
github.com/caddyserver/zerossl v0.1.5/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U=
github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=
github.com/mholt/acmez/v3 v3.1.6 h1:eGVQNObP0pBN4sxqrXeg7MYqTOWyoiYpQqITVWlrevk=
github.com/mholt/acmez/v3 v3.1.6/go.mod h1:5nTPosTGosLxF3+LU4ygbgMRFDhbAVpqMI4+a4aHLBY=
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=
github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE=
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.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.1/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.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
main.go
package main

import (
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math/big"
	"os"
	"path/filepath"
	"time"

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

func generateSelfSignedCert(domain string) ([]byte, []byte, error) {
	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	template := x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			CommonName: domain,
		},
		DNSNames:  []string{domain},
		NotBefore: time.Now().Add(-1 * time.Hour),
		NotAfter:  time.Now().Add(24 * time.Hour),
		KeyUsage:  x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
	}

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

	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	privBytes, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		return nil, nil, err
	}
	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes})

	return certPEM, keyPEM, nil
}

func main() {
	var cfg *certmagic.Config

	tempDir, err := os.MkdirTemp("", "certmagic-cache-*")
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create temp dir: %v\n", err)
		os.Exit(1)
	}
	defer os.RemoveAll(tempDir)

	opts := certmagic.CacheOptions{
		GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
			return cfg, nil
		},
		OCSPCheckInterval:  30 * time.Minute,
		RenewCheckInterval: 1 * time.Hour,
		Capacity:           50,
		Logger:             zap.NewNop(),
	}

	cache := certmagic.NewCache(opts)
	defer cache.Stop()

	cfg = certmagic.New(cache, certmagic.Config{
		Storage: &certmagic.FileStorage{Path: filepath.Join(tempDir, "storage")},
		Logger:  zap.NewNop(),
	})

	certPEM, keyPEM, err := generateSelfSignedCert("example.com")
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to generate cert: %v\n", err)
		os.Exit(1)
	}

	ctx := context.Background()
	hash, err := cfg.CacheUnmanagedCertificatePEMBytes(ctx, certPEM, keyPEM, []string{"example.com"})
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to cache cert: %v\n", err)
		os.Exit(1)
	}

	certs := cache.AllMatchingCertificates("example.com")
	fmt.Printf("Cached certificate hash=%s count=%d\n", hash, len(certs))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/caddyserver/certmagic.CacheOptions in pkg:golang/github.com/caddyserver/certmagic@v0.25.3",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/caddyserver/certmagic@v0.25.3"
  ],
  "symbols": [
    "github.com/caddyserver/certmagic.CacheOptions"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.6",
    "runtime": "go@1.26.6"
  }
}
test/contract.go
package main

import (
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math/big"
	"os"
	"path/filepath"
	"time"

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

func generateTestCertPEM(domain string) ([]byte, []byte, error) {
	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	template := x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			CommonName: domain,
		},
		DNSNames:  []string{domain},
		NotBefore: time.Now().Add(-1 * time.Hour),
		NotAfter:  time.Now().Add(24 * time.Hour),
		KeyUsage:  x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
	}

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

	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	privBytes, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		return nil, nil, err
	}
	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes})

	return certPEM, keyPEM, nil
}

func main() {
	// Assertion 1: certmagic.NewCache panics when CacheOptions.GetConfigForCert is not provided.
	{
		panicked := false
		func() {
			defer func() {
				if r := recover(); r != nil {
					panicked = true
				}
			}()
			emptyOpts := certmagic.CacheOptions{
				GetConfigForCert: nil,
			}
			_ = certmagic.NewCache(emptyOpts)
		}()
		if !panicked {
			fmt.Fprintln(os.Stderr, "FAIL: expected NewCache to panic when GetConfigForCert is nil")
			os.Exit(1)
		}
	}

	// Assertion 2: certmagic.NewCache initializes an active Cache given valid CacheOptions including GetConfigForCert, Capacity, and check intervals.
	var cfg *certmagic.Config
	opts := certmagic.CacheOptions{
		GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
			return cfg, nil
		},
		OCSPCheckInterval:  15 * time.Minute,
		RenewCheckInterval: 30 * time.Minute,
		Capacity:           10,
		Logger:             zap.NewNop(),
	}

	cache := certmagic.NewCache(opts)
	if cache == nil {
		fmt.Fprintln(os.Stderr, "FAIL: expected NewCache to return a non-nil Cache")
		os.Exit(1)
	}
	defer cache.Stop()

	// Assertion 3: Cache.SetOptions dynamically updates CacheOptions on an existing cache instance.
	newOpts := certmagic.CacheOptions{
		GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
			return cfg, nil
		},
		OCSPCheckInterval:  45 * time.Minute,
		RenewCheckInterval: 90 * time.Minute,
		Capacity:           25,
		Logger:             zap.NewNop(),
	}
	cache.SetOptions(newOpts)

	// Assertion 4: Cache.SetOptions panics if updated CacheOptions has nil GetConfigForCert.
	{
		panicked := false
		func() {
			defer func() {
				if r := recover(); r != nil {
					panicked = true
				}
			}()
			badOpts := certmagic.CacheOptions{
				GetConfigForCert: nil,
			}
			cache.SetOptions(badOpts)
		}()
		if !panicked {
			fmt.Fprintln(os.Stderr, "FAIL: expected SetOptions to panic when GetConfigForCert is nil")
			os.Exit(1)
		}
	}

	// Assertion 5: Cache created with CacheOptions integrates with certmagic.New to store and query certificates.
	tempDir, err := os.MkdirTemp("", "contract-test-*")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: temp dir creation failed: %v\n", err)
		os.Exit(1)
	}
	defer os.RemoveAll(tempDir)

	cfg = certmagic.New(cache, certmagic.Config{
		Storage: &certmagic.FileStorage{Path: filepath.Join(tempDir, "storage")},
		Logger:  zap.NewNop(),
	})

	domain := "example.com"
	certPEM, keyPEM, err := generateTestCertPEM(domain)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to generate test cert: %v\n", err)
		os.Exit(1)
	}

	ctx := context.Background()
	hash, err := cfg.CacheUnmanagedCertificatePEMBytes(ctx, certPEM, keyPEM, []string{domain})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: CacheUnmanagedCertificatePEMBytes failed: %v\n", err)
		os.Exit(1)
	}
	if hash == "" {
		fmt.Fprintln(os.Stderr, "FAIL: expected non-empty certificate hash")
		os.Exit(1)
	}

	matched := cache.AllMatchingCertificates(domain)
	if len(matched) != 1 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 1 matching certificate for %s, got %d\n", domain, len(matched))
		os.Exit(1)
	}

	cache.Remove([]string{hash})
	matchedAfterRemove := cache.AllMatchingCertificates(domain)
	if len(matchedAfterRemove) != 0 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 0 matching certificates after Remove, got %d\n", len(matchedAfterRemove))
		os.Exit(1)
	}

	fmt.Println("PASS: all contract assertions passed")
}

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

аноним