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. go 1.26 …

sha256:9f1fcd20a777721fe9f8fb179b16db5f54b1503767ecaabbc19398e1c0052ada

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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})
}

오리진 시더

익명