CodeSampleX

샘플

github.com/smallstep/scep v0.0.0-20231024192529-aee96d7ad34d: WithCACerts

검증된 샘플 — golang github.com/smallstep/scep v0.0.0-20231024192529-aee96d7ad34d: WithCACerts. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:21ce5c59814f52240eabe10b979fffd60fdd97d1d799d4ffd4e509a3722e1aaf

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
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-27

케이스

HOW
목표
verify github.com/smallstep/scep.WithCACerts in pkg:golang/github.com/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d
패키지
심벌
  • github.com/smallstep/scep.WithCACerts
생성일
2026-08-27T11:07:30Z

컨트랙트

  1. scep.WithCACerts returns an Option configuring CA certificates for SCEP PKIMessage parsing
  2. scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP PKCSReq message against the expected signer certificate
  3. scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP CertRep SUCCESS response against the CA certificate
  4. scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP CertRep FAILURE response against the CA certificate
  5. scep.ParsePKIMessage with scep.WithCACerts rejects messages when the provided CA certificates do not match the signer
  6. scep.WithCACerts supports multiple CA certificates and successfully validates messages signed by any certificate in the set
  7. scep.WithCACerts handles nil and empty certificate slices without crashing

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.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 github.com/smallstep/scep.WithCACerts in pkg:golang/github.com/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d
Demonstrate these symbols/APIs:
  - github.com/smallstep/scep.WithCACerts

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:29ad7a45b2a850b5b8363c671cc6b9af194a53709ca73020f514847a1340a82f","contract":["scep.WithCACerts returns an Option configuring CA certificates for SCEP PKIMessage parsing","scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP PKCSReq message against the expected signer certificate","scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP CertRep SUCCESS response against the CA certificate","scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP CertRep FAILURE response against the CA certificate","scep.ParsePKIMessage with scep.WithCACerts rejects messages when the provided CA certificates do not match the signer","scep.WithCACerts supports multiple CA certificates and successfully validates messages signed by any certificate in the set","scep.WithCACerts handles nil and empty certificate slices without crashing"],"goal":"verify github.com/smallstep/scep.WithCACerts in pkg:golang/github.com/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d","kind":"HOW","packages":["pkg:golang/github.com/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d"],"schemaVersion":1,"symbols":["github.com/smallstep/scep.WithCACerts"]},"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/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d"],"schemaVersion":1,"subject":"pkg:golang/github.com/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d","symbols":["github.com/smallstep/scep.WithCACerts"],"verifierAdapter":"golang@1"}
go.mod
module sample-scep-cacerts

go 1.22

require github.com/smallstep/scep v0.0.0-20231024192529-aee96d7ad34d

require (
	github.com/go-kit/kit v0.4.0 // indirect
	github.com/go-logfmt/logfmt v0.5.1 // indirect
	github.com/go-stack/stack v1.6.0 // indirect
	github.com/smallstep/pkcs7 v0.2.1 // indirect
	golang.org/x/crypto v0.33.0 // indirect
)
go.sum
github.com/go-kit/kit v0.4.0 h1:KeVK+Emj3c3S4eRztFuzbFYb2BAgf2jmwDwyXEri7Lo=
github.com/go-kit/kit v0.4.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA=
github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-stack/stack v1.6.0 h1:MmJCxYVKTJ0SplGKqFVX3SBnmaUhODHZrrFF6jMbpZk=
github.com/go-stack/stack v1.6.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/smallstep/pkcs7 v0.0.0-20231024181729-3b98ecc1ca81/go.mod h1:SoUAr/4M46rZ3WaLstHxGhLEgoYIDRqxQEXLOmOEB0Y=
github.com/smallstep/pkcs7 v0.2.1 h1:6Kfzr/QizdIuB6LSv8y1LJdZ3aPSfTNhTLqAx9CTLfA=
github.com/smallstep/pkcs7 v0.2.1/go.mod h1:RcXHsMfL+BzH8tRhmrF1NkkpebKpq3JEM66cOFxanf0=
github.com/smallstep/scep v0.0.0-20231024192529-aee96d7ad34d h1:06LUHn4Ia2X6syjIaCMNaXXDNdU+1N/oOHynJbWgpXw=
github.com/smallstep/scep v0.0.0-20231024192529-aee96d7ad34d/go.mod h1:4d0ub42ut1mMtvGyMensjuHYEUpRrASvkzLEJvoRQcU=
github.com/smallstep/scep v0.0.0-20260331191114-261f960a40d1 h1:lpXBkQKj1rT1oGX/2idvt8xbrOrnoQxH/+CjoeMxs9E=
github.com/smallstep/scep v0.0.0-20260331191114-261f960a40d1/go.mod h1:QQhwLqCS13nhv8L5ov7NgusowENUtXdEzdytjmJHdZQ=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
main.go
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"math/big"
	"time"

	"github.com/smallstep/scep"
	"github.com/smallstep/scep/x509util"
)

func createCertificate(subject string, isCA bool, parent *x509.Certificate, parentKey *rsa.PrivateKey) (*x509.Certificate, *rsa.PrivateKey, error) {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, err
	}

	serialNumber, err := rand.Int(rand.Reader, big.NewInt(100000000))
	if err != nil {
		return nil, nil, err
	}

	tmpl := &x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			CommonName: subject,
		},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		BasicConstraintsValid: true,
	}

	signerKey := key
	signerCert := tmpl
	if parent != nil && parentKey != nil {
		signerKey = parentKey
		signerCert = parent
	}

	if isCA {
		tmpl.IsCA = true
		tmpl.KeyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign
	}

	der, err := x509.CreateCertificate(rand.Reader, tmpl, signerCert, &key.PublicKey, signerKey)
	if err != nil {
		return nil, nil, err
	}

	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, nil, err
	}

	return cert, key, nil
}

func main() {
	caCert, caKey, err := createCertificate("Example CA", true, nil, nil)
	if err != nil {
		fmt.Printf("failed to generate CA: %v\n", err)
		return
	}

	clientCert, clientKey, err := createCertificate("client.example.com", false, caCert, caKey)
	if err != nil {
		fmt.Printf("failed to generate client cert: %v\n", err)
		return
	}

	csrTmpl := &x509util.CertificateRequest{
		CertificateRequest: x509.CertificateRequest{
			Subject: pkix.Name{
				CommonName: "client.example.com",
			},
			SignatureAlgorithm: x509.SHA256WithRSA,
		},
		ChallengePassword: "sample-challenge",
	}
	csrDer, err := x509util.CreateCertificateRequest(rand.Reader, csrTmpl, clientKey)
	if err != nil {
		fmt.Printf("failed to create CSR: %v\n", err)
		return
	}

	csr, err := x509.ParseCertificateRequest(csrDer)
	if err != nil {
		fmt.Printf("failed to parse CSR: %v\n", err)
		return
	}

	reqTmpl := &scep.PKIMessage{
		MessageType: scep.PKCSReq,
		Recipients:  []*x509.Certificate{caCert},
		SignerCert:  clientCert,
		SignerKey:   clientKey,
	}
	reqMsg, err := scep.NewCSRRequest(csr, reqTmpl)
	if err != nil {
		fmt.Printf("failed to create SCEP CSR request: %v\n", err)
		return
	}

	// Parse PKIMessage using scep.WithCACerts option to verify against CA certificates
	parsedReq, err := scep.ParsePKIMessage(reqMsg.Raw, scep.WithCACerts([]*x509.Certificate{caCert}))
	if err != nil {
		fmt.Printf("ParsePKIMessage with WithCACerts failed: %v\n", err)
		return
	}

	fmt.Printf("Successfully parsed SCEP message (TransactionID: %s, MessageType: %v) using WithCACerts\n",
		parsedReq.TransactionID, parsedReq.MessageType)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/smallstep/scep.WithCACerts in pkg:golang/github.com/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/smallstep/scep@v0.0.0-20231024192529-aee96d7ad34d"
  ],
  "symbols": [
    "github.com/smallstep/scep.WithCACerts"
  ]
}
test/contract.go
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"math/big"
	"os"
	"time"

	"github.com/smallstep/scep"
	"github.com/smallstep/scep/x509util"
)

func generateCertificate(cn string, isCA bool, parent *x509.Certificate, parentKey *rsa.PrivateKey) (*x509.Certificate, *rsa.PrivateKey, error) {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, err
	}

	serial, err := rand.Int(rand.Reader, big.NewInt(10000000))
	if err != nil {
		return nil, nil, err
	}

	tmpl := &x509.Certificate{
		SerialNumber: serial,
		Subject: pkix.Name{
			CommonName: cn,
		},
		NotBefore:             time.Now().Add(-1 * time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		BasicConstraintsValid: true,
	}

	signerKey := key
	signerCert := tmpl
	if parent != nil && parentKey != nil {
		signerKey = parentKey
		signerCert = parent
	}

	if isCA {
		tmpl.IsCA = true
		tmpl.KeyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign
	}

	der, err := x509.CreateCertificate(rand.Reader, tmpl, signerCert, &key.PublicKey, signerKey)
	if err != nil {
		return nil, nil, err
	}

	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, nil, err
	}

	return cert, key, nil
}

func generateCSR(cn string, key *rsa.PrivateKey) (*x509.CertificateRequest, error) {
	csrTmpl := &x509util.CertificateRequest{
		CertificateRequest: x509.CertificateRequest{
			Subject: pkix.Name{
				CommonName: cn,
			},
			SignatureAlgorithm: x509.SHA256WithRSA,
		},
		ChallengePassword: "test-challenge-password",
	}
	der, err := x509util.CreateCertificateRequest(rand.Reader, csrTmpl, key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificateRequest(der)
}

func main() {
	ca1Cert, ca1Key, err := generateCertificate("Primary Root CA", true, nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "setup failed: generate primary CA error: %v\n", err)
		os.Exit(1)
	}

	ca2Cert, _, err := generateCertificate("Secondary Root CA", true, nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "setup failed: generate secondary CA error: %v\n", err)
		os.Exit(1)
	}

	untrustedCACert, untrustedCAKey, err := generateCertificate("Untrusted CA", true, nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "setup failed: generate untrusted CA error: %v\n", err)
		os.Exit(1)
	}

	clientCert, clientKey, err := generateCertificate("client.example.com", false, ca1Cert, ca1Key)
	if err != nil {
		fmt.Fprintf(os.Stderr, "setup failed: generate client cert error: %v\n", err)
		os.Exit(1)
	}

	csr, err := generateCSR("client.example.com", clientKey)
	if err != nil {
		fmt.Fprintf(os.Stderr, "setup failed: generate CSR error: %v\n", err)
		os.Exit(1)
	}

	reqTmpl := &scep.PKIMessage{
		MessageType: scep.PKCSReq,
		Recipients:  []*x509.Certificate{ca1Cert},
		SignerCert:  clientCert,
		SignerKey:   clientKey,
	}
	reqMsg, err := scep.NewCSRRequest(csr, reqTmpl)
	if err != nil {
		fmt.Fprintf(os.Stderr, "setup failed: NewCSRRequest error: %v\n", err)
		os.Exit(1)
	}

	// Assertion 1: scep.WithCACerts returns an Option configuring CA certificates for SCEP PKIMessage parsing
	{
		opt := scep.WithCACerts([]*x509.Certificate{ca1Cert})
		if opt == nil {
			fmt.Fprintf(os.Stderr, "Assertion 1 failed: WithCACerts returned nil Option\n")
			os.Exit(1)
		}
	}

	// Assertion 2: scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP PKCSReq message against the expected signer certificate
	var parsedReq *scep.PKIMessage
	{
		parsedReq, err = scep.ParsePKIMessage(reqMsg.Raw, scep.WithCACerts([]*x509.Certificate{clientCert}))
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: ParsePKIMessage with WithCACerts failed: %v\n", err)
			os.Exit(1)
		}
		if parsedReq == nil || parsedReq.MessageType != scep.PKCSReq {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected PKCSReq message type, got %v\n", parsedReq)
			os.Exit(1)
		}
		if parsedReq.TransactionID != reqMsg.TransactionID {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: transactionID mismatch: %v != %v\n", parsedReq.TransactionID, reqMsg.TransactionID)
			os.Exit(1)
		}
	}

	// Decrypt PKI envelope before creating responses
	if err := parsedReq.DecryptPKIEnvelope(ca1Cert, ca1Key); err != nil {
		fmt.Fprintf(os.Stderr, "setup failed: DecryptPKIEnvelope error: %v\n", err)
		os.Exit(1)
	}

	// Assertion 3: scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP CertRep SUCCESS response against the CA certificate
	{
		issuedCert, _, err := generateCertificate("client.example.com", false, ca1Cert, ca1Key)
		if err != nil {
			fmt.Fprintf(os.Stderr, "setup failed: generate issued cert: %v\n", err)
			os.Exit(1)
		}

		successMsg, err := parsedReq.Success(ca1Cert, ca1Key, issuedCert)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 3 setup failed: Success() error: %v\n", err)
			os.Exit(1)
		}

		parsedSuccess, err := scep.ParsePKIMessage(successMsg.Raw, scep.WithCACerts([]*x509.Certificate{ca1Cert}))
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: ParsePKIMessage on Success CertRep failed: %v\n", err)
			os.Exit(1)
		}
		if parsedSuccess.CertRepMessage == nil || parsedSuccess.CertRepMessage.PKIStatus != scep.SUCCESS {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected SUCCESS status\n")
			os.Exit(1)
		}
	}

	// Assertion 4: scep.ParsePKIMessage with scep.WithCACerts successfully verifies and parses a SCEP CertRep FAILURE response against the CA certificate
	{
		failMsg, err := parsedReq.Fail(ca1Cert, ca1Key, scep.BadRequest)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 4 setup failed: Fail() error: %v\n", err)
			os.Exit(1)
		}

		parsedFail, err := scep.ParsePKIMessage(failMsg.Raw, scep.WithCACerts([]*x509.Certificate{ca1Cert}))
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: ParsePKIMessage on Fail CertRep failed: %v\n", err)
			os.Exit(1)
		}
		if parsedFail.CertRepMessage == nil || parsedFail.CertRepMessage.PKIStatus != scep.FAILURE {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected FAILURE status\n")
			os.Exit(1)
		}
		if parsedFail.CertRepMessage.FailInfo != scep.BadRequest {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected BadRequest fail info, got %v\n", parsedFail.CertRepMessage.FailInfo)
			os.Exit(1)
		}
	}

	// Assertion 5: scep.ParsePKIMessage with scep.WithCACerts rejects messages when the provided CA certificates do not match the signer
	{
		untrustedClientCert, untrustedClientKey, err := generateCertificate("untrusted.example.com", false, untrustedCACert, untrustedCAKey)
		if err != nil {
			fmt.Fprintf(os.Stderr, "setup failed: generate untrusted client cert: %v\n", err)
			os.Exit(1)
		}
		untrustedReqTmpl := &scep.PKIMessage{
			MessageType: scep.PKCSReq,
			Recipients:  []*x509.Certificate{ca1Cert},
			SignerCert:  untrustedClientCert,
			SignerKey:   untrustedClientKey,
		}
		untrustedReqMsg, err := scep.NewCSRRequest(csr, untrustedReqTmpl)
		if err != nil {
			fmt.Fprintf(os.Stderr, "setup failed: NewCSRRequest untrusted error: %v\n", err)
			os.Exit(1)
		}

		// Trying to parse untrusted request with only ca1Cert as expected signer must fail verification
		_, err = scep.ParsePKIMessage(untrustedReqMsg.Raw, scep.WithCACerts([]*x509.Certificate{ca1Cert}))
		if err == nil {
			fmt.Fprintf(os.Stderr, "Assertion 5 failed: expected error when parsing with mismatched CA certs, got nil\n")
			os.Exit(1)
		}
	}

	// Assertion 6: scep.WithCACerts supports multiple CA certificates and successfully validates messages signed by any certificate in the set
	{
		// With both ca2Cert and ca1Cert provided, verifying ca1-signed message should succeed
		multiOpts := scep.WithCACerts([]*x509.Certificate{ca2Cert, ca1Cert})
		issuedCert, _, _ := generateCertificate("client.example.com", false, ca1Cert, ca1Key)
		successMsg, err := parsedReq.Success(ca1Cert, ca1Key, issuedCert)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 6 setup failed: Success() error: %v\n", err)
			os.Exit(1)
		}

		parsedWithMultiCA, err := scep.ParsePKIMessage(successMsg.Raw, multiOpts)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 6 failed: ParsePKIMessage with multi CA failed: %v\n", err)
			os.Exit(1)
		}
		if parsedWithMultiCA.CertRepMessage == nil || parsedWithMultiCA.CertRepMessage.PKIStatus != scep.SUCCESS {
			fmt.Fprintf(os.Stderr, "Assertion 6 failed: expected SUCCESS status\n")
			os.Exit(1)
		}
	}

	// Assertion 7: scep.WithCACerts handles nil and empty certificate slices without crashing
	{
		optNil := scep.WithCACerts(nil)
		if optNil == nil {
			fmt.Fprintf(os.Stderr, "Assertion 7 failed: WithCACerts(nil) returned nil\n")
			os.Exit(1)
		}
		optEmpty := scep.WithCACerts([]*x509.Certificate{})
		if optEmpty == nil {
			fmt.Fprintf(os.Stderr, "Assertion 7 failed: WithCACerts([]) returned nil\n")
			os.Exit(1)
		}

		// Parsing with nil/empty WithCACerts falls back to embedded cert verification
		parsedNil, err := scep.ParsePKIMessage(reqMsg.Raw, optNil)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 7 failed: ParsePKIMessage with WithCACerts(nil) error: %v\n", err)
			os.Exit(1)
		}
		if parsedNil == nil || parsedNil.MessageType != scep.PKCSReq {
			fmt.Fprintf(os.Stderr, "Assertion 7 failed: expected PKCSReq\n")
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed successfully.")
}

오리진 시더

익명