CodeSampleX

示例

github.com/googleapis/enterprise-certificate-proxy v0.3.14: client.Cred

已验证示例 — golang github.com/googleapis/enterprise-certificate-proxy v0.3.14: client.Cred. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过.

sha256:54449d63732777a060b1417485f89fa00f285a2256144d6306f67acecde4953a

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 go

验证运行环境

环境 契约 阶段 运行日期
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-10-12

案例

HOW
目标
verify pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14
包
符号
  • github.com/googleapis/enterprise-certificate-proxy/client.Cred
创建时间
2026-10-12T23:46:06Z

契约

  1. client.Cred returns ErrCredUnavailable when the configuration file does not exist
  2. client.Cred returns ErrCredUnavailable when the configuration file is missing the signer binary path in libs.ecp
  3. client.Cred returns a JSON syntax error when the configuration file contains invalid JSON
  4. client.Cred successfully starts the enterprise cert signer subprocess and initializes an RPC client connection when given a valid configuration file
  5. client.Key returned by Cred implements crypto.PublicKey via Public() and exposes the X.509 certificate chain via CertificateChain()
  6. client.Key returned by Cred implements message signing via Sign() and terminates the signer subprocess cleanly on Close()

文件

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go
  • test/signer.sh
  • test/signer/main.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 pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14

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:6854cbb69ec81fa05a511e32ca1dbb3d71c7e807c57307924d68c3a3b3a0004d","contract":["client.Cred returns ErrCredUnavailable when the configuration file does not exist","client.Cred returns ErrCredUnavailable when the configuration file is missing the signer binary path in libs.ecp","client.Cred returns a JSON syntax error when the configuration file contains invalid JSON","client.Cred successfully starts the enterprise cert signer subprocess and initializes an RPC client connection when given a valid configuration file","client.Key returned by Cred implements crypto.PublicKey via Public() and exposes the X.509 certificate chain via CertificateChain()","client.Key returned by Cred implements message signing via Sign() and terminates the signer subprocess cleanly on Close()"],"goal":"verify pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14","kind":"HOW","packages":["pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14"],"schemaVersion":1,"symbols":["github.com/googleapis/enterprise-certificate-proxy/client.Cred"]},"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/googleapis/enterprise-certificate-proxy@v0.3.14"],"schemaVersion":1,"subject":"pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14","symbols":["github.com/googleapis/enterprise-certificate-proxy/client.Cred"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require github.com/googleapis/enterprise-certificate-proxy v0.3.14
go.sum
github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8=
github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=
main.go
package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/googleapis/enterprise-certificate-proxy/client"
)

func main() {
	// client.Cred initializes the Enterprise Certificate Proxy (ECP) client
	// by loading configuration and connecting to the platform-specific signer subprocess.
	configPath := "certificate_config.json"

	key, err := client.Cred(configPath)
	if err != nil {
		if errors.Is(err, client.ErrCredUnavailable) {
			fmt.Printf("ECP credential is unavailable (config file or signer binary not found): %v\n", err)
			return
		}
		log.Fatalf("failed to initialize ECP client: %v", err)
	}
	defer key.Close()

	// Public returns the crypto.PublicKey associated with the enterprise certificate.
	pubKey := key.Public()
	fmt.Printf("Public key loaded: %T\n", pubKey)

	// CertificateChain returns the certificate chain in raw DER format.
	certChain := key.CertificateChain()
	fmt.Printf("Certificate chain loaded with %d certificate(s)\n", len(certChain))

	// Sign messages using the enterprise certificate credential.
	digest := []byte("example-digest-to-sign")
	signature, err := key.Sign(nil, digest, nil)
	if err != nil {
		log.Fatalf("failed to sign digest: %v", err)
	}
	fmt.Printf("Successfully signed digest (%d bytes signature)\n", len(signature))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"crypto"
	"crypto/rsa"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"github.com/googleapis/enterprise-certificate-proxy/client"
)

func assert(condition bool, message string) {
	if !condition {
		fmt.Fprintf(os.Stderr, "Assertion failed: %s\n", message)
		os.Exit(1)
	}
}

func main() {
	// Assertion 1: client.Cred returns ErrCredUnavailable when the configuration file does not exist
	_, err := client.Cred("non_existent_config_file_12345.json")
	assert(err != nil, "Cred must return error for non-existent file")
	assert(errors.Is(err, client.ErrCredUnavailable), "Cred error must wrap client.ErrCredUnavailable for missing file")

	// Create a temporary directory for test configuration files
	tempDir, err := os.MkdirTemp("", "ecp-test-*")
	assert(err == nil, "creating temporary directory must succeed")
	defer os.RemoveAll(tempDir)

	// Assertion 2: client.Cred returns ErrCredUnavailable when libs.ecp is missing
	missingSignerConfigPath := filepath.Join(tempDir, "missing_signer.json")
	err = os.WriteFile(missingSignerConfigPath, []byte(`{"libs": {}}`), 0600)
	assert(err == nil, "writing missing_signer.json must succeed")

	_, err = client.Cred(missingSignerConfigPath)
	assert(err != nil, "Cred must return error when libs.ecp is missing")
	assert(errors.Is(err, client.ErrCredUnavailable), "Cred error must wrap client.ErrCredUnavailable when libs.ecp is missing")

	// Assertion 3: client.Cred returns a JSON syntax error when configuration is invalid JSON
	malformedConfigPath := filepath.Join(tempDir, "malformed.json")
	err = os.WriteFile(malformedConfigPath, []byte(`{"libs": `), 0600)
	assert(err == nil, "writing malformed.json must succeed")

	_, err = client.Cred(malformedConfigPath)
	assert(err != nil, "Cred must return error for malformed JSON config")
	var syntaxErr *json.SyntaxError
	assert(errors.As(err, &syntaxErr), "Cred error must be a json.SyntaxError for malformed JSON")

	// Assertion 4: client.Cred successfully initializes RPC client connection when given a valid configuration file
	signerScript := "./test/signer.sh"
	err = os.Chmod(signerScript, 0755)
	assert(err == nil, fmt.Sprintf("setting execute permission on %s must succeed: %v", signerScript, err))

	validConfigPath := filepath.Join(tempDir, "valid_config.json")
	validConfigContent := fmt.Sprintf(`{"libs": {"ecp": "%s"}}`, signerScript)
	err = os.WriteFile(validConfigPath, []byte(validConfigContent), 0600)
	assert(err == nil, "writing valid_config.json must succeed")

	key, err := client.Cred(validConfigPath)
	assert(err == nil, fmt.Sprintf("Cred must succeed with valid config and mock signer: %v", err))
	assert(key != nil, "returned Key must not be nil")

	// Assertion 5: client.Key provides valid crypto.PublicKey and X.509 certificate chain
	pubKey := key.Public()
	assert(pubKey != nil, "key.Public() must return non-nil public key")
	rsaPub, ok := pubKey.(*rsa.PublicKey)
	assert(ok, "public key must be an *rsa.PublicKey")
	assert(rsaPub.Size() >= 256, "RSA key size must be at least 2048 bits (>= 256 bytes)")

	chain := key.CertificateChain()
	assert(len(chain) > 0, "key.CertificateChain() must return at least one certificate")
	assert(len(chain[0]) > 0, "first certificate in chain must have non-zero length")

	// Assertion 6: client.Key signs digests and terminates subprocess cleanly on Close()
	testDigest := []byte("contract-verification-digest")
	signed, err := key.Sign(nil, testDigest, nil)
	assert(err == nil, fmt.Sprintf("key.Sign with nil opts must succeed: %v", err))
	assert(bytes.Equal(signed, testDigest), "mock signer must return matching signed digest")

	sha256Digest := make([]byte, 32)
	copy(sha256Digest, []byte("sha256-test-digest-32bytes-len!"))
	signedSha, err := key.Sign(nil, sha256Digest, crypto.SHA256)
	assert(err == nil, fmt.Sprintf("key.Sign with crypto.SHA256 must succeed: %v", err))
	assert(bytes.Equal(signedSha, sha256Digest), "mock signer must return matching SHA256 digest")

	err = key.Close()
	assert(err == nil, fmt.Sprintf("key.Close must succeed: %v", err))

	fmt.Println("All contract assertions for pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.14 passed successfully.")
}
test/signer.sh
#!/bin/sh
exec go run ./test/signer "$@"
test/signer/main.go
package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/gob"
	"io"
	"log"
	"math/big"
	"net/rpc"
	"os"
	"time"
)

func init() {
	gob.Register(crypto.SHA256)
	gob.Register(crypto.SHA384)
	gob.Register(crypto.SHA512)
	gob.Register(&rsa.PSSOptions{})
	gob.Register(&rsa.OAEPOptions{})
}

// SignArgs encapsulates the parameters for the Sign RPC method.
type SignArgs struct {
	Digest []byte
	Opts   crypto.SignerOpts
}

// EncryptArgs encapsulates the parameters for the Encrypt RPC method.
type EncryptArgs struct {
	Plaintext []byte
}

// DecryptArgs encapsulates the parameters for the Decrypt RPC method.
type DecryptArgs struct {
	Ciphertext []byte
}

// EnterpriseCertSigner exports RPC methods matching the enterprise-certificate-proxy client expectation.
type EnterpriseCertSigner struct {
	cert *tls.Certificate
}

// Connection wraps a pair of unidirectional streams as an io.ReadWriteCloser.
type Connection struct {
	io.ReadCloser
	io.WriteCloser
}

// Close closes the underlying streams.
func (c *Connection) Close() error {
	rerr := c.ReadCloser.Close()
	werr := c.WriteCloser.Close()
	if rerr != nil {
		return rerr
	}
	return werr
}

// CertificateChain returns the certificate chain in raw DER format.
func (s *EnterpriseCertSigner) CertificateChain(ignored struct{}, certificateChain *[][]byte) error {
	*certificateChain = s.cert.Certificate
	return nil
}

// Public returns the public key in PKIX DER format.
func (s *EnterpriseCertSigner) Public(ignored struct{}, publicKey *[]byte) error {
	if len(s.cert.Certificate) == 0 {
		return nil
	}
	cert, err := x509.ParseCertificate(s.cert.Certificate[0])
	if err != nil {
		return err
	}
	*publicKey, err = x509.MarshalPKIXPublicKey(cert.PublicKey)
	return err
}

// Sign returns a mock signature for the provided digest.
func (s *EnterpriseCertSigner) Sign(args SignArgs, resp *[]byte) error {
	*resp = args.Digest
	return nil
}

// Encrypt returns ciphertext for the provided plaintext.
func (s *EnterpriseCertSigner) Encrypt(args EncryptArgs, plaintext *[]byte) error {
	*plaintext = args.Plaintext
	return nil
}

// Decrypt returns plaintext for the provided ciphertext.
func (s *EnterpriseCertSigner) Decrypt(args DecryptArgs, ciphertext *[]byte) error {
	*ciphertext = args.Ciphertext
	return nil
}

func generateSelfSignedCert() (tls.Certificate, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return tls.Certificate{}, err
	}
	template := x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			CommonName: "localhost",
		},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
	}
	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return tls.Certificate{}, err
	}
	return tls.Certificate{
		Certificate: [][]byte{derBytes},
		PrivateKey:  priv,
	}, nil
}

func main() {
	cert, err := generateSelfSignedCert()
	if err != nil {
		log.Fatalf("failed to generate self-signed certificate: %v", err)
	}

	signer := &EnterpriseCertSigner{
		cert: &cert,
	}

	if err := rpc.Register(signer); err != nil {
		log.Fatalf("failed to register EnterpriseCertSigner RPC: %v", err)
	}

	// Exit when parent process terminates
	go func() {
		for {
			if os.Getppid() == 1 {
				os.Exit(0)
			}
			time.Sleep(500 * time.Millisecond)
		}
	}()

	rpc.ServeConn(&Connection{os.Stdin, os.Stdout})
}

原始种子者

匿名