CodeSampleX

示例

github.com/googleapis/enterprise-certificate-proxy v0.3.20: client.Cred, util.LoadSignerBinaryPath, util.GetDefaultConfigFilePath

已验证示例 — golang github.com/googleapis/enterprise-certificate-proxy v0.3.20: client.Cred, util.LoadSignerBinaryPath, util.GetDefaultConfigFilePath. contract 在…

sha256:9f1fcd20a777721fe9f8fb179b16db5f54b1503767ecaabbc19398e1c0052ada

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-14

案例

HOW
目标
verify pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.20
包
符号
  • github.com/googleapis/enterprise-certificate-proxy/client.Cred
  • github.com/googleapis/enterprise-certificate-proxy/client/util.LoadSignerBinaryPath
  • github.com/googleapis/enterprise-certificate-proxy/client/util.GetDefaultConfigFilePath
创建时间
2026-10-14T01:48:05Z

契约

  1. client.Cred returns ErrCredUnavailable when the configuration file does not exist
  2. util.LoadSignerBinaryPath extracts the signer binary path and expands ~ and $HOME placeholders
  3. client.Cred returns ErrCredUnavailable when the configuration file is missing the signer binary path in libs.ecp
  4. client.Cred returns a JSON syntax error when the configuration file contains invalid JSON
  5. client.Cred successfully starts the enterprise cert signer subprocess and initializes an RPC client connection when given a valid configuration file
  6. client.Key returned by Cred implements crypto.PublicKey via Public() and exposes the X.509 certificate chain via CertificateChain()
  7. 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.20
Kind: HOW

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

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:1ff9394a424212c04003d855c0996a78c99981f3c027f745fdfd63c4e75012b2","contract":["client.Cred returns ErrCredUnavailable when the configuration file does not exist","util.LoadSignerBinaryPath extracts the signer binary path and expands ~ and $HOME placeholders","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.20","kind":"HOW","packages":["pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.20"],"schemaVersion":1,"symbols":["github.com/googleapis/enterprise-certificate-proxy/client.Cred","github.com/googleapis/enterprise-certificate-proxy/client/util.LoadSignerBinaryPath","github.com/googleapis/enterprise-certificate-proxy/client/util.GetDefaultConfigFilePath"]},"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.20"],"schemaVersion":1,"subject":"pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.20","symbols":["github.com/googleapis/enterprise-certificate-proxy/client.Cred","github.com/googleapis/enterprise-certificate-proxy/client/util.LoadSignerBinaryPath","github.com/googleapis/enterprise-certificate-proxy/client/util.GetDefaultConfigFilePath"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.25.0

require github.com/googleapis/enterprise-certificate-proxy v0.3.20
go.sum
github.com/googleapis/enterprise-certificate-proxy v0.3.20 h1:t/xL64VUoN69MuMRQuJETqYGOw4Z9mSRJK9epIEtwFk=
github.com/googleapis/enterprise-certificate-proxy v0.3.20/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
main.go
package main

import (
	"errors"
	"fmt"
	"log"

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

func main() {
	defaultPath := util.GetDefaultConfigFilePath()
	fmt.Printf("Default enterprise certificate config path: %s\n", defaultPath)

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

	pubKey := key.Public()
	fmt.Printf("Public key loaded: %T\n", pubKey)

	certChain := key.CertificateChain()
	fmt.Printf("Certificate chain loaded with %d certificate(s)\n", len(certChain))

	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.20",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/googleapis/enterprise-certificate-proxy@v0.3.20"
  ]
}
test/contract.go
package main

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

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

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")

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

	// Assertion 2: util.LoadSignerBinaryPath extracts the signer binary path and expands ~ and $HOME placeholders
	homeDir := os.Getenv("HOME")
	if homeDir == "" {
		homeDir = tempDir
		os.Setenv("HOME", homeDir)
	}
	tildeConfigPath := filepath.Join(tempDir, "tilde_config.json")
	err = os.WriteFile(tildeConfigPath, []byte(`{"libs":{"ecp":"~/bin/signer"}}`), 0600)
	assert(err == nil, "writing tilde_config.json must succeed")
	tildePath, err := util.LoadSignerBinaryPath(tildeConfigPath)
	assert(err == nil, "LoadSignerBinaryPath must succeed for tilde path")
	assert(tildePath == filepath.Join(homeDir, "bin", "signer"), "LoadSignerBinaryPath must expand ~")

	// Assertion 3: 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 4: 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 5: 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 6: 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 7: 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.20 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{})
}

type SignArgs struct {
	Digest []byte
	Opts   crypto.SignerOpts
}

type EncryptArgs struct {
	Plaintext []byte
}

type DecryptArgs struct {
	Ciphertext []byte
}

type EnterpriseCertSigner struct {
	cert *tls.Certificate
}

type Connection struct {
	io.ReadCloser
	io.WriteCloser
}

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

func (s *EnterpriseCertSigner) CertificateChain(ignored struct{}, certificateChain *[][]byte) error {
	*certificateChain = s.cert.Certificate
	return nil
}

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
}

func (s *EnterpriseCertSigner) Sign(args SignArgs, resp *[]byte) error {
	*resp = args.Digest
	return nil
}

func (s *EnterpriseCertSigner) Encrypt(args EncryptArgs, plaintext *[]byte) error {
	*plaintext = args.Plaintext
	return nil
}

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)
	}

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

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

原始种子者

匿名