CodeSampleX

Beispiel

github.com/prometheus/common v0.48.0: Configure HTTP client and roundtripper with TLS, basic auth, and authorization headers using prometheus common config

Verifiziertes Beispiel für golang github.com/prometheus/common v0.48.0: Configure HTTP client and roundtripper with TLS, basic auth, and authorization…

sha256:bccbc06a63d1b81b6a9fa72cb85aa0d4ee1bd4be0beb990158e9248b09cce354

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 go

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
Configure HTTP client and roundtripper with TLS, basic auth, and authorization headers using prometheus common config
Pakete
Symbole
  • config.Authorization
  • config.BasicAuth
  • config.HTTPClientConfig
  • config.NewClientFromConfig
  • config.RoundTripperFromConfig
Erstellt
2026-08-27T21:05:41Z

Contract

  1. config.NewClientFromConfig configures an http.Client with BasicAuth credentials that attach standard Basic Authorization headers on outgoing requests.
  2. config.NewRoundTripperFromConfig configures an http.RoundTripper with Authorization settings supporting Bearer tokens and custom authorization schemes.
  3. config.HTTPClientConfig.Validate enforces mutual exclusivity between conflicting authentication configurations such as BasicAuth and Authorization.
  4. config.NewClientFromConfig applies TLSConfig options including InsecureSkipVerify for HTTPS connections.
  5. config.Secret masks confidential credential strings in serialized JSON and YAML outputs preventing accidental leakage.

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

NOTES.md
# github.com/prometheus/common/config HTTP Client and RoundTripper Configuration

## Prior Knowledge Search
A query to search known solutions for `pkg:golang/github.com/prometheus/common@v0.48.0` with `config.HTTPClientConfig`, `config.NewClientFromConfig`, and `config.RoundTripperFromConfig` returned `NO_SAFE_MATCH`. This sample establishes verified coverage for configuring HTTP clients and roundtrippers with authentication and TLS settings.

## Pinned Release
- `github.com/prometheus/common`: `v0.48.0`

## Proven Behaviors and Semantics

### 1. Basic Authentication
`config.NewClientFromConfig` constructs an `*http.Client` from `config.HTTPClientConfig` with `BasicAuth` containing username and password credentials. Outgoing HTTP requests automatically carry standard RFC 7617 Basic Authentication headers with base64-encoded credentials.

### 2. Authorization Headers (Bearer and Custom Schemes)
`config.NewRoundTripperFromConfig` constructs an `http.RoundTripper` from `config.HTTPClientConfig` with `Authorization` parameters. Outgoing HTTP requests automatically include configured authorization types (such as `Bearer` or custom tokens) and secret credentials.

### 3. Mutual Exclusion Validation
`config.HTTPClientConfig.Validate` verifies configuration consistency and rejects configurations specifying multiple conflicting authentication mechanisms (e.g., both `BasicAuth` and `Authorization`).

### 4. TLS Configuration
`config.NewClientFromConfig` supports `config.TLSConfig` parameters including `InsecureSkipVerify` for HTTPS connections.

### 5. Secret Masking
`config.Secret` implements custom JSON and YAML marshaling interfaces that redact sensitive credential values to `"<secret>"` in serialized representations, protecting against credential leakage in configuration dumps and logging.
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: Configure HTTP client and roundtripper with TLS, basic auth, and authorization headers using prometheus common config
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/prometheus/common@v0.48.0
Demonstrate these symbols/APIs:
  - config.Authorization
  - config.BasicAuth
  - config.HTTPClientConfig
  - config.NewClientFromConfig
  - config.RoundTripperFromConfig

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.
config_test.go
package main

import (
	"encoding/base64"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/prometheus/common/config"
	"gopkg.in/yaml.v2"
)

func TestNewClientFromConfigBasicAuth(t *testing.T) {
	expectedUser := "testuser"
	expectedPass := "testpass123"
	expectedAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(expectedUser+":"+expectedPass))

	receivedAuth := ""
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		receivedAuth = r.Header.Get("Authorization")
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	}))
	defer server.Close()

	cfg := config.HTTPClientConfig{
		BasicAuth: &config.BasicAuth{
			Username: expectedUser,
			Password: config.Secret(expectedPass),
		},
	}

	client, err := config.NewClientFromConfig(cfg, "test-basic-auth-client")
	if err != nil {
		t.Fatalf("unexpected error creating client: %v", err)
	}

	resp, err := client.Get(server.URL)
	if err != nil {
		t.Fatalf("unexpected error making request: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		t.Errorf("expected status 200, got %d", resp.StatusCode)
	}
	if receivedAuth != expectedAuth {
		t.Errorf("expected Authorization header %q, got %q", expectedAuth, receivedAuth)
	}
}

func TestNewRoundTripperFromConfigAuthorizationBearer(t *testing.T) {
	expectedToken := "bearer-token-abc-456"
	expectedHeader := "Bearer " + expectedToken

	receivedAuth := ""
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		receivedAuth = r.Header.Get("Authorization")
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("authorized"))
	}))
	defer server.Close()

	cfg := config.HTTPClientConfig{
		Authorization: &config.Authorization{
			Type:        "Bearer",
			Credentials: config.Secret(expectedToken),
		},
	}

	rt, err := config.NewRoundTripperFromConfig(cfg, "test-bearer-roundtripper")
	if err != nil {
		t.Fatalf("unexpected error creating roundtripper: %v", err)
	}

	client := &http.Client{Transport: rt}
	resp, err := client.Get(server.URL)
	if err != nil {
		t.Fatalf("unexpected error making request: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		t.Errorf("expected status 200, got %d", resp.StatusCode)
	}
	if receivedAuth != expectedHeader {
		t.Errorf("expected Authorization header %q, got %q", expectedHeader, receivedAuth)
	}
}

func TestNewRoundTripperFromConfigCustomAuthorizationType(t *testing.T) {
	expectedHeader := "Token custom-secret-token"

	receivedAuth := ""
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		receivedAuth = r.Header.Get("Authorization")
		w.WriteHeader(http.StatusOK)
	}))
	defer server.Close()

	cfg := config.HTTPClientConfig{
		Authorization: &config.Authorization{
			Type:        "Token",
			Credentials: config.Secret("custom-secret-token"),
		},
	}

	rt, err := config.NewRoundTripperFromConfig(cfg, "test-custom-auth-roundtripper")
	if err != nil {
		t.Fatalf("unexpected error creating roundtripper: %v", err)
	}

	client := &http.Client{Transport: rt}
	resp, err := client.Get(server.URL)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer resp.Body.Close()

	if receivedAuth != expectedHeader {
		t.Errorf("expected Authorization header %q, got %q", expectedHeader, receivedAuth)
	}
}

func TestHTTPClientConfigValidationMutualExclusion(t *testing.T) {
	cfg := config.HTTPClientConfig{
		BasicAuth: &config.BasicAuth{
			Username: "alice",
			Password: config.Secret("password"),
		},
		Authorization: &config.Authorization{
			Type:        "Bearer",
			Credentials: config.Secret("token"),
		},
	}

	err := cfg.Validate()
	if err == nil {
		t.Fatalf("expected error when both BasicAuth and Authorization are configured, got nil")
	}
	if !strings.Contains(err.Error(), "at most one of") {
		t.Errorf("expected mutual exclusion error message, got: %v", err)
	}
}

func TestHTTPClientConfigTLSInsecureSkipVerify(t *testing.T) {
	server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = io.WriteString(w, "tls-ok")
	}))
	defer server.Close()

	cfg := config.HTTPClientConfig{
		TLSConfig: config.TLSConfig{
			InsecureSkipVerify: true,
		},
	}

	client, err := config.NewClientFromConfig(cfg, "test-tls-client")
	if err != nil {
		t.Fatalf("unexpected error creating TLS client: %v", err)
	}

	resp, err := client.Get(server.URL)
	if err != nil {
		t.Fatalf("failed to connect to TLS server with InsecureSkipVerify: %v", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("unexpected error reading body: %v", err)
	}
	if string(body) != "tls-ok" {
		t.Errorf("expected body 'tls-ok', got %q", string(body))
	}
}

func TestSecretSerializationMasking(t *testing.T) {
	secret := config.Secret("my-sensitive-credential-value")

	jsonBytes, err := json.Marshal(secret)
	if err != nil {
		t.Fatalf("unexpected error marshaling JSON: %v", err)
	}
	var unmarshaledJSON string
	if err := json.Unmarshal(jsonBytes, &unmarshaledJSON); err != nil {
		t.Fatalf("unexpected error unmarshaling secret JSON: %v", err)
	}
	if unmarshaledJSON != "<secret>" {
		t.Errorf("expected unmarshaled JSON secret to be %q, got %q", "<secret>", unmarshaledJSON)
	}

	yamlBytes, err := yaml.Marshal(secret)
	if err != nil {
		t.Fatalf("unexpected error marshaling YAML: %v", err)
	}
	if !strings.Contains(string(yamlBytes), "<secret>") {
		t.Errorf("expected '<secret>' in YAML output, got %q", string(yamlBytes))
	}
}
csx.json
{"case":{"caseId":"case:sha256:a7bf0ed92435fcf8f04c37eaf1d75125a8ff38bb84aa706e1d4adc17c4aa3806","contract":["config.NewClientFromConfig configures an http.Client with BasicAuth credentials that attach standard Basic Authorization headers on outgoing requests.","config.NewRoundTripperFromConfig configures an http.RoundTripper with Authorization settings supporting Bearer tokens and custom authorization schemes.","config.HTTPClientConfig.Validate enforces mutual exclusivity between conflicting authentication configurations such as BasicAuth and Authorization.","config.NewClientFromConfig applies TLSConfig options including InsecureSkipVerify for HTTPS connections.","config.Secret masks confidential credential strings in serialized JSON and YAML outputs preventing accidental leakage."],"goal":"Configure HTTP client and roundtripper with TLS, basic auth, and authorization headers using prometheus common config","kind":"HOW","packages":["pkg:golang/github.com/prometheus/common@v0.48.0"],"schemaVersion":1,"symbols":["config.Authorization","config.BasicAuth","config.HTTPClientConfig","config.NewClientFromConfig","config.RoundTripperFromConfig"]},"contractCommand":["go","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/prometheus/common@v0.48.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/common@v0.48.0","symbols":["config.Authorization","config.BasicAuth","config.HTTPClientConfig","config.NewClientFromConfig","config.RoundTripperFromConfig"],"verifierAdapter":"golang@1"}
go.mod
module example.com/csx-prometheus-common-config-test

go 1.25.0

require github.com/prometheus/common v0.48.0

require (
	github.com/beorn7/perks v1.0.1 // indirect
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/jpillora/backoff v1.0.0 // indirect
	github.com/kr/text v0.2.0 // indirect
	github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect
	github.com/prometheus/client_golang v1.19.1 // indirect
	github.com/prometheus/client_model v0.6.2 // indirect
	github.com/prometheus/procfs v0.21.0 // indirect
	github.com/stretchr/testify v1.12.1 // indirect
	golang.org/x/net v0.57.0 // indirect
	golang.org/x/oauth2 v0.36.0 // indirect
	golang.org/x/sys v0.47.0 // indirect
	golang.org/x/text v0.40.0 // indirect
	google.golang.org/protobuf v1.36.11 // indirect
	gopkg.in/yaml.v2 v2.4.0 // indirect
)
go.sum
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE=
github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE=
github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc=
github.com/prometheus/procfs v0.21.0 h1:Qh/e6TlBjZf+XLLqNCqFGmCU6Kj/2Bu7kj3oAc0UnXc=
github.com/prometheus/procfs v0.21.0/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
spec.json
{
  "schemaVersion": 1,
  "goal": "Configure HTTP client and roundtripper with TLS, basic auth, and authorization headers using prometheus common config",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/prometheus/common@v0.48.0"
  ],
  "symbols": [
    "config.Authorization",
    "config.BasicAuth",
    "config.HTTPClientConfig",
    "config.NewClientFromConfig",
    "config.RoundTripperFromConfig"
  ]
}

Ursprungs-Seeder

anonym