CodeSampleX

Ejemplo

golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541: iterate NSS root certificates and construct x509 cert pool with constraints using bundle.Roots

Muestra verificada para golang golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541: iterate NSS root certificates and construct x509…

sha256:491942f7d1bcf34d6faf7db61d74eeed66af97fcd3de6e90d7b05fe52c3e1cc7

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
iterate NSS root certificates and construct x509 cert pool with constraints using bundle.Roots
Paquetes
Símbolos
  • golang.org/x/crypto/x509roots/fallback/bundle.Roots
Creado
2026-08-28T11:49:33Z

Contrato

  1. Iterating over bundle.Roots() yields embedded NSS root certificates with non-empty DER byte slices.
  2. Each DER-encoded root certificate parses into a valid x509.Certificate with non-empty subject metadata.
  3. Root certificates can be populated into an x509.CertPool, using AddCert for unconstrained roots and AddCertWithConstraint when custom constraints are present.
  4. An x509.CertPool constructed from bundle.Roots successfully rejects certificates not anchored by the NSS root trust bundle.

Archivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • main_test.go
  • spec.json

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# Iterating NSS Root Certificates and Constructing X.509 CertPool with bundle.Roots

## Known Solution Search
A search for existing community-verified samples targeting `golang.org/x/crypto/x509roots/fallback/bundle.Roots` returned no prior matches (`NO_SAFE_MATCH`).

## Pinned Release
- Package: `golang.org/x/crypto/x509roots/fallback`
- Version: `v0.0.0-20260213171211-a408498e5541` (declared in `go.mod` and pinned in `go.sum`)
- Symbol: `golang.org/x/crypto/x509roots/fallback/bundle.Roots`
- Runtime: Go (`golang@1` adapter)

## Observed Behaviour
The `golang.org/x/crypto/x509roots/fallback/bundle` sub-package exposes the underlying NSS root certificate bundle as an iterator sequence `Roots() iter.Seq[Root]`.

1. **Direct Iterator Access**:
   `bundle.Roots()` yields `bundle.Root` values containing raw DER-encoded certificate bytes (`root.Certificate []byte`) and optional custom validation constraints (`root.Constraint func([]*x509.Certificate) error`).

2. **Custom CertPool Construction**:
   Applications requiring granular certificate inspection, custom trust boundaries, or explicit trust stores can iterate over `bundle.Roots()`, parse each certificate with `x509.ParseCertificate`, and insert them into an `*x509.CertPool` using `pool.AddCert` or `pool.AddCertWithConstraint`.

3. **Offline Chain Validation**:
   The resulting `*x509.CertPool` acts as a complete CA root store for `x509.VerifyOptions`, validating compliant chains and rejecting untrusted or self-signed roots.
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: iterate NSS root certificates and construct x509 cert pool with constraints using bundle.Roots
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/crypto/x509roots/fallback@v0.0.0-20260213171211-a408498e5541
Demonstrate these symbols/APIs:
  - golang.org/x/crypto/x509roots/fallback/bundle.Roots

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:67420cdb2ad92db3afde9a30b253835c0c64c64d3f3703af16179f62feda5db3","contract":["Iterating over bundle.Roots() yields embedded NSS root certificates with non-empty DER byte slices.","Each DER-encoded root certificate parses into a valid x509.Certificate with non-empty subject metadata.","Root certificates can be populated into an x509.CertPool, using AddCert for unconstrained roots and AddCertWithConstraint when custom constraints are present.","An x509.CertPool constructed from bundle.Roots successfully rejects certificates not anchored by the NSS root trust bundle."],"goal":"iterate NSS root certificates and construct x509 cert pool with constraints using bundle.Roots","kind":"HOW","packages":["pkg:golang/golang.org/x/crypto/x509roots/fallback@v0.0.0-20260213171211-a408498e5541"],"schemaVersion":1,"symbols":["golang.org/x/crypto/x509roots/fallback/bundle.Roots"]},"contractCommand":["go","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/golang.org/x/crypto/x509roots/fallback@v0.0.0-20260213171211-a408498e5541"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/crypto/x509roots/fallback@v0.0.0-20260213171211-a408498e5541","symbols":["golang.org/x/crypto/x509roots/fallback/bundle.Roots"],"verifierAdapter":"golang@1"}
go.mod
module example.com/nssroots

go 1.25.0

require golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541
go.sum
golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541 h1:FmKxj9ocLKn45jiR2jQMwCVhDvaK7fKQFzfuT9GvyK8=
golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541/go.mod h1:+UoQFNBq2p2wO+Q6ddVtYc25GZ6VNdOMyyrd4nrqrKs=
main.go
package nssroots

import (
	"crypto/x509"
	"fmt"

	"golang.org/x/crypto/x509roots/fallback/bundle"
)

// BuildCertPool iterates over NSS root certificates from bundle.Roots()
// and constructs an *x509.CertPool, applying constraints when present.
func BuildCertPool() (*x509.CertPool, int, error) {
	pool := x509.NewCertPool()
	count := 0

	for root := range bundle.Roots() {
		cert, err := x509.ParseCertificate(root.Certificate)
		if err != nil {
			return nil, 0, fmt.Errorf("failed to parse root certificate: %w", err)
		}

		if root.Constraint == nil {
			pool.AddCert(cert)
		} else {
			pool.AddCertWithConstraint(cert, root.Constraint)
		}
		count++
	}

	if count == 0 {
		return nil, 0, fmt.Errorf("no roots found in bundle")
	}

	return pool, count, nil
}
main_test.go
package nssroots_test

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

	"example.com/nssroots"
	"golang.org/x/crypto/x509roots/fallback/bundle"
)

func TestRootsIterationAndCertPoolConstruction(t *testing.T) {
	pool, count, err := nssroots.BuildCertPool()
	if err != nil {
		t.Fatalf("BuildCertPool failed: %v", err)
	}

	if pool == nil {
		t.Fatal("expected non-nil CertPool")
	}

	if count < 100 {
		t.Fatalf("expected at least 100 root certificates, got %d", count)
	}

	iterCount := 0
	for root := range bundle.Roots() {
		if len(root.Certificate) == 0 {
			t.Fatalf("root %d has empty certificate DER", iterCount)
		}
		cert, err := x509.ParseCertificate(root.Certificate)
		if err != nil {
			t.Fatalf("failed to parse certificate %d: %v", iterCount, err)
		}
		if cert.Subject.CommonName == "" && len(cert.Subject.Organization) == 0 {
			t.Fatalf("cert %d has empty Subject CN and Organization", iterCount)
		}
		iterCount++
	}

	if iterCount != count {
		t.Fatalf("iterCount %d did not match pool count %d", iterCount, count)
	}
}

func TestCertPoolVerificationRejection(t *testing.T) {
	pool, _, err := nssroots.BuildCertPool()
	if err != nil {
		t.Fatalf("BuildCertPool failed: %v", err)
	}

	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("failed to generate private key: %v", err)
	}

	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(100),
		Subject: pkix.Name{
			CommonName: "untrusted.example.com",
		},
		NotBefore: time.Now().Add(-1 * time.Hour),
		NotAfter:  time.Now().Add(1 * time.Hour),
		DNSNames:  []string{"untrusted.example.com"},
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
	if err != nil {
		t.Fatalf("failed to create untrusted certificate: %v", err)
	}

	untrustedCert, err := x509.ParseCertificate(derBytes)
	if err != nil {
		t.Fatalf("failed to parse untrusted certificate: %v", err)
	}

	opts := x509.VerifyOptions{
		DNSName: "untrusted.example.com",
		Roots:   pool,
	}

	if _, err := untrustedCert.Verify(opts); err == nil {
		t.Fatal("expected verification against NSS root pool to fail for untrusted cert, but it succeeded")
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "iterate NSS root certificates and construct x509 cert pool with constraints using bundle.Roots",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/crypto/x509roots/fallback@v0.0.0-20260213171211-a408498e5541"
  ],
  "symbols": [
    "golang.org/x/crypto/x509roots/fallback/bundle.Roots"
  ]
}

Seeder de origen

anónimo