CodeSampleX

Exemple

github.com/caddyserver/zerossl v0.1.3: Client.GetCertificate, Client.ListCertificates, Client.GenerateEABCredentials

Échantillon vérifié pour golang github.com/caddyserver/zerossl v0.1.3: Client.GetCertificate, Client.ListCertificates, Client.GenerateEABCredentials. Le…

sha256:f5b36e871abf2ea261e0e6a97b0189102563f01b125188ad5c813183bd25a877

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré go linux x64 go go go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-23

Cas

HOW
Objectif
verify pkg:golang/github.com/caddyserver/zerossl@v0.1.3
Paquets
Symboles
  • zerossl.Client.GetCertificate
  • zerossl.Client.ListCertificates
  • zerossl.Client.GenerateEABCredentials
Environnement
go
Créé
2026-08-23T17:38:03Z

Contrat

  1. assert Client.GetCertificate successfully queries and unmarshals certificate details using custom BaseURL and HTTPClient
  2. assert Client.ListCertificates populates query parameters for status and limit
  3. assert Client.GenerateEABCredentials sends POST request to /acme/eab-credentials and parses EAB credentials
  4. assert API error responses are detected and returned as errors with access_key redacted from query string

Fichiers

  • NOTES.md
  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# caddyserver/zerossl API Client Usage and Contract Verification

## Search Results
A search via `search_known_solution` for the package `github.com/caddyserver/zerossl@v0.1.3` returned no existing matching verified samples (`NO_SAFE_MATCH`).

## Implementation and Behavior Proved
1. **Custom BaseURL and HTTPClient Configuration**: `zerossl.Client` allows custom `BaseURL` and `HTTPClient` overrides to enable offline integration and hermetic contract testing without hitting external network endpoints.
2. **Endpoint Mapping & Authentication**: Client operations (such as `GetCertificate`, `ListCertificates`, and `GenerateEABCredentials`) append the required `access_key` query parameter and communicate with `/certificates`, `/certificates/{id}`, and `/acme/eab-credentials`.
3. **Error Handling & Secret Redaction**: The ZeroSSL REST client decodes API error structures and redacts `access_key` from error messages to prevent credential leakage.
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/caddyserver/zerossl@v0.1.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/caddyserver/zerossl@v0.1.3
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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.
contract_test.go
package sample_test

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/caddyserver/zerossl"
)

func TestClientGetCertificate(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/certificates/cert_test_123" {
			t.Errorf("unexpected path: %s", r.URL.Path)
			http.NotFound(w, r)
			return
		}
		if r.URL.Query().Get("access_key") != "sample_test_key" {
			t.Errorf("unexpected access key: %s", r.URL.Query().Get("access_key"))
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}

		cert := zerossl.CertificateObject{
			ID:         "cert_test_123",
			Type:       "custom",
			CommonName: "example.com",
			Status:     "issued",
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(cert)
	}))
	defer ts.Close()

	client := zerossl.Client{
		AccessKey:  "sample_test_key",
		BaseURL:    ts.URL,
		HTTPClient: ts.Client(),
	}

	cert, err := client.GetCertificate(context.Background(), "cert_test_123")
	if err != nil {
		t.Fatalf("GetCertificate failed: %v", err)
	}

	if cert.ID != "cert_test_123" {
		t.Errorf("expected ID cert_test_123, got %s", cert.ID)
	}
	if cert.CommonName != "example.com" {
		t.Errorf("expected CommonName example.com, got %s", cert.CommonName)
	}
	if cert.Status != "issued" {
		t.Errorf("expected Status issued, got %s", cert.Status)
	}
}

func TestClientListCertificates(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/certificates" {
			t.Errorf("unexpected path: %s", r.URL.Path)
			http.NotFound(w, r)
			return
		}
		if r.URL.Query().Get("access_key") != "sample_test_key" {
			t.Errorf("unexpected access key: %s", r.URL.Query().Get("access_key"))
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		if r.URL.Query().Get("certificate_status") != "issued" {
			t.Errorf("expected certificate_status=issued, got %s", r.URL.Query().Get("certificate_status"))
		}
		if r.URL.Query().Get("limit") != "10" {
			t.Errorf("expected limit=10, got %s", r.URL.Query().Get("limit"))
		}

		resp := zerossl.CertificateList{
			TotalCount:  1,
			ResultCount: 1,
			Page:        "1",
			Limit:       10,
			Results: []zerossl.CertificateObject{
				{
					ID:         "cert_test_123",
					CommonName: "example.com",
					Status:     "issued",
				},
			},
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(resp)
	}))
	defer ts.Close()

	client := zerossl.Client{
		AccessKey:  "sample_test_key",
		BaseURL:    ts.URL,
		HTTPClient: ts.Client(),
	}

	list, err := client.ListCertificates(context.Background(), zerossl.ListCertificatesParameters{
		Status: "issued",
		Limit:  10,
	})
	if err != nil {
		t.Fatalf("ListCertificates failed: %v", err)
	}

	if list.TotalCount != 1 || len(list.Results) != 1 {
		t.Fatalf("unexpected certificate list: %+v", list)
	}
	if list.Results[0].ID != "cert_test_123" {
		t.Errorf("expected cert ID cert_test_123, got %s", list.Results[0].ID)
	}
}

func TestClientGenerateEABCredentials(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/acme/eab-credentials" {
			t.Errorf("unexpected path: %s", r.URL.Path)
			http.NotFound(w, r)
			return
		}
		if r.Method != http.MethodPost {
			t.Errorf("unexpected method: %s", r.Method)
			return
		}
		if r.URL.Query().Get("access_key") != "sample_test_key" {
			t.Errorf("unexpected access key: %s", r.URL.Query().Get("access_key"))
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}

		resp := map[string]any{
			"success":      true,
			"eab_kid":      "sample-kid-12345",
			"eab_hmac_key": "sample-hmac-key-67890",
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(resp)
	}))
	defer ts.Close()

	client := zerossl.Client{
		AccessKey:  "sample_test_key",
		BaseURL:    ts.URL,
		HTTPClient: ts.Client(),
	}

	kid, hmac, err := client.GenerateEABCredentials(context.Background())
	if err != nil {
		t.Fatalf("GenerateEABCredentials failed: %v", err)
	}
	if kid != "sample-kid-12345" {
		t.Errorf("expected kid sample-kid-12345, got %s", kid)
	}
	if hmac != "sample-hmac-key-67890" {
		t.Errorf("expected hmac sample-hmac-key-67890, got %s", hmac)
	}
}

func TestClientErrorResponseRedactsKey(t *testing.T) {
	secretKey := "super_secret_access_key"
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		errResp := map[string]any{
			"success": false,
			"error": map[string]any{
				"code": 2812,
				"type": "certificate_not_found",
			},
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(errResp)
	}))
	defer ts.Close()

	client := zerossl.Client{
		AccessKey:  secretKey,
		BaseURL:    ts.URL,
		HTTPClient: ts.Client(),
	}

	_, err := client.GetCertificate(context.Background(), "non_existent_cert")
	if err == nil {
		t.Fatal("expected error for non-existent certificate, got nil")
	}

	errMsg := err.Error()
	if strings.Contains(errMsg, secretKey) {
		t.Errorf("error message leaked secret access key: %s", errMsg)
	}
	if !strings.Contains(errMsg, "access_key=redacted") {
		t.Errorf("expected access_key=redacted in error message, got: %s", errMsg)
	}
}
csx.json
{"case":{"caseId":"case:sha256:283c25e82ca0264f41fbdc017f6ee7b4047abcec54ccc41a9a4ecb44268ddebd","contract":["assert Client.GetCertificate successfully queries and unmarshals certificate details using custom BaseURL and HTTPClient","assert Client.ListCertificates populates query parameters for status and limit","assert Client.GenerateEABCredentials sends POST request to /acme/eab-credentials and parses EAB credentials","assert API error responses are detected and returned as errors with access_key redacted from query string"],"goal":"verify pkg:golang/github.com/caddyserver/zerossl@v0.1.3","kind":"HOW","packages":["pkg:golang/github.com/caddyserver/zerossl@v0.1.3"],"schemaVersion":1,"symbols":["zerossl.Client.GetCertificate","zerossl.Client.ListCertificates","zerossl.Client.GenerateEABCredentials"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/caddyserver/zerossl@v0.1.3"],"schemaVersion":1,"symbols":["zerossl.Client.GetCertificate","zerossl.Client.ListCertificates","zerossl.Client.GenerateEABCredentials"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/caddyserver/zerossl v0.1.3 // indirect
go.sum
github.com/caddyserver/zerossl v0.1.3 h1:onS+pxp3M8HnHpN5MMbOMyNjmTheJyWRaZYwn+YTAyA=
github.com/caddyserver/zerossl v0.1.3/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/caddyserver/zerossl@v0.1.3",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/caddyserver/zerossl@v0.1.3"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}

Seeder d'origine

anonyme