CodeSampleX

Sample

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

Verified sample for golang golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541: iterate NSS root certificates and construct x509 cert…

sha256:491942f7d1bcf34d6faf7db61d74eeed66af97fcd3de6e90d7b05fe52c3e1cc7

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 go

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
iterate NSS root certificates and construct x509 cert pool with constraints using bundle.Roots
Packages
Symbols
  • golang.org/x/crypto/x509roots/fallback/bundle.Roots
Created
2026-08-28T11:49:33Z

Contract

  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.

Files

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

Download the source artifact (tar.gz)

Source

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"
  ]
}

Origin Seeder

anonymous