CodeSampleX

示例

cloud.google.com/go/auth v0.18.2

已验证示例 — golang cloud.google.com/go/auth v0.18.2. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: Token with non-empty value and zero expiry is valid

sha256:f661cc0790a3bd9786d945db6a50c31fe286df928d9469f7632bd8722b183750

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

案例

HOW
目标
verify pkg:golang/cloud.google.com/go/auth@v0.18.2
包
创建时间
2026-10-10T13:04:06Z

契约

  1. Token with non-empty value and zero expiry is valid
  2. Token with empty value or expired timestamp is invalid
  3. Token MetadataString retrieves string values from metadata map
  4. NewCredentials creates credentials with project ID, default universe domain, and token access
  5. NewCachedTokenProvider caches token across repeated calls for fresh token
  6. Error Temporary reports true for transient HTTP error codes and false otherwise
  7. New2LOTokenProvider and New3LOTokenProvider validate mandatory configuration options

文件

  • 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 pkg:golang/cloud.google.com/go/auth@v0.18.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/cloud.google.com/go/auth@v0.18.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.
csx.json
{"case":{"caseId":"case:sha256:5c5d28e774f0c07149e119c4713bffda84156cc027cf7bef5d8f84cb6ee0fafd","contract":["Token with non-empty value and zero expiry is valid","Token with empty value or expired timestamp is invalid","Token MetadataString retrieves string values from metadata map","NewCredentials creates credentials with project ID, default universe domain, and token access","NewCachedTokenProvider caches token across repeated calls for fresh token","Error Temporary reports true for transient HTTP error codes and false otherwise","New2LOTokenProvider and New3LOTokenProvider validate mandatory configuration options"],"goal":"verify pkg:golang/cloud.google.com/go/auth@v0.18.2","kind":"HOW","packages":["pkg:golang/cloud.google.com/go/auth@v0.18.2"],"schemaVersion":1},"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/cloud.google.com/go/auth@v0.18.2"],"schemaVersion":1,"subject":"pkg:golang/cloud.google.com/go/auth@v0.18.2","verifierAdapter":"golang@1"}
go.mod
module sample

go 1.24.0

require cloud.google.com/go/auth v0.18.2

require (
	cloud.google.com/go/compute/metadata v0.9.0 // indirect
	github.com/googleapis/gax-go/v2 v2.17.0 // indirect
	golang.org/x/sys v0.40.0 // indirect
)
go.sum
cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM=
cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M=
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
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/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
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/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao=
github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8=
github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc=
github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 h1:H86B94AW+VfJWDqFeEbBPhEtHzJwJfTbgE2lZa54ZAQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
main.go
package main

import (
	"context"
	"fmt"
	"net/http"

	"cloud.google.com/go/auth"
)

type staticProvider struct {
	token *auth.Token
}

func (s *staticProvider) Token(ctx context.Context) (*auth.Token, error) {
	return s.token, nil
}

func main() {
	tok := &auth.Token{
		Value: "sample-token-value",
		Type:  "Bearer",
		Metadata: map[string]interface{}{
			"scope": "https://example.com/auth",
		},
	}
	fmt.Printf("Token valid: %t\n", tok.IsValid())
	fmt.Printf("Token scope: %s\n", tok.MetadataString("scope"))

	creds := auth.NewCredentials(&auth.CredentialsOptions{
		TokenProvider: &staticProvider{token: tok},
		ProjectIDProvider: auth.CredentialsPropertyFunc(func(ctx context.Context) (string, error) {
			return "sample-project-id", nil
		}),
	})
	ctx := context.Background()
	projID, _ := creds.ProjectID(ctx)
	universe, _ := creds.UniverseDomain(ctx)
	fmt.Printf("Project ID: %s, Universe Domain: %s\n", projID, universe)

	errTransient := &auth.Error{Response: &http.Response{StatusCode: http.StatusServiceUnavailable}}
	fmt.Printf("Service unavailable is temporary: %t\n", errTransient.Temporary())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/cloud.google.com/go/auth@v0.18.2",
  "kind": "HOW",
  "packages": [
    "pkg:golang/cloud.google.com/go/auth@v0.18.2"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

	"cloud.google.com/go/auth"
)

type mockTokenProvider struct {
	token *auth.Token
}

func (m *mockTokenProvider) Token(ctx context.Context) (*auth.Token, error) {
	return m.token, nil
}

type countingTokenProvider struct {
	fn func(ctx context.Context) (*auth.Token, error)
}

func (c *countingTokenProvider) Token(ctx context.Context) (*auth.Token, error) {
	return c.fn(ctx)
}

func main() {
	if err := runContractTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All contract tests passed successfully.")
}

func runContractTests() error {
	// Assertion 1: Token with non-empty value and zero expiry is valid
	{
		tok := &auth.Token{Value: "sample-token-value"}
		if !tok.IsValid() {
			return fmt.Errorf("Assertion 1: expected token with value to be valid")
		}
	}

	// Assertion 2: Token with empty value or expired timestamp is invalid
	{
		emptyTok := &auth.Token{}
		if emptyTok.IsValid() {
			return fmt.Errorf("Assertion 2: expected empty token to be invalid")
		}
		pastTok := &auth.Token{Value: "val", Expiry: time.Now().Add(-10 * time.Minute)}
		if pastTok.IsValid() {
			return fmt.Errorf("Assertion 2: expected expired token to be invalid")
		}
	}

	// Assertion 3: Token MetadataString retrieves string values from metadata map
	{
		tokWithMeta := &auth.Token{
			Value: "tok",
			Metadata: map[string]interface{}{
				"token_type": "Bearer",
				"int_key":    123,
			},
		}
		if tokWithMeta.MetadataString("token_type") != "Bearer" {
			return fmt.Errorf("Assertion 3: expected 'Bearer', got %q", tokWithMeta.MetadataString("token_type"))
		}
		if tokWithMeta.MetadataString("missing") != "" {
			return fmt.Errorf("Assertion 3: expected empty string for missing key")
		}
		if tokWithMeta.MetadataString("int_key") != "" {
			return fmt.Errorf("Assertion 3: expected empty string for non-string key")
		}
	}

	// Assertion 4: NewCredentials creates credentials with project ID, default universe domain, and token access
	{
		staticTP := &mockTokenProvider{token: &auth.Token{Value: "sample-access-token"}}
		rawJSON := []byte(`{"type":"service_account","project_id":"sample-project"}`)
		creds := auth.NewCredentials(&auth.CredentialsOptions{
			TokenProvider: staticTP,
			JSON:          rawJSON,
			ProjectIDProvider: auth.CredentialsPropertyFunc(func(ctx context.Context) (string, error) {
				return "sample-project", nil
			}),
		})
		if !bytes.Equal(creds.JSON(), rawJSON) {
			return fmt.Errorf("Assertion 4: JSON mismatch")
		}
		proj, err := creds.ProjectID(context.Background())
		if err != nil || proj != "sample-project" {
			return fmt.Errorf("Assertion 4: ProjectID got %q, err %v", proj, err)
		}
		ud, err := creds.UniverseDomain(context.Background())
		if err != nil || ud != "googleapis.com" {
			return fmt.Errorf("Assertion 4: UniverseDomain got %q, err %v", ud, err)
		}
		tok, err := creds.Token(context.Background())
		if err != nil || tok.Value != "sample-access-token" {
			return fmt.Errorf("Assertion 4: Token got %v, err %v", tok, err)
		}
	}

	// Assertion 5: NewCachedTokenProvider caches token across repeated calls for fresh token
	{
		calls := 0
		countingTP := &countingTokenProvider{
			fn: func(ctx context.Context) (*auth.Token, error) {
				calls++
				return &auth.Token{Value: "cached-token-1"}, nil
			},
		}
		cached := auth.NewCachedTokenProvider(countingTP, &auth.CachedTokenProviderOptions{})
		t1, err1 := cached.Token(context.Background())
		if err1 != nil || t1.Value != "cached-token-1" {
			return fmt.Errorf("Assertion 5: first call failed: %v", err1)
		}
		t2, err2 := cached.Token(context.Background())
		if err2 != nil || t2.Value != "cached-token-1" {
			return fmt.Errorf("Assertion 5: second call failed: %v", err2)
		}
		if calls != 1 {
			return fmt.Errorf("Assertion 5: expected 1 call, got %d", calls)
		}
	}

	// Assertion 6: Error Temporary reports true for transient HTTP error codes and false otherwise
	{
		transientCodes := []int{
			http.StatusInternalServerError,
			http.StatusServiceUnavailable,
			http.StatusRequestTimeout,
			http.StatusTooManyRequests,
		}
		for _, code := range transientCodes {
			e := &auth.Error{Response: &http.Response{StatusCode: code}}
			if !e.Temporary() {
				return fmt.Errorf("Assertion 6: expected status %d to be temporary", code)
			}
		}
		nonTransientCodes := []int{
			http.StatusBadRequest,
			http.StatusUnauthorized,
			http.StatusNotFound,
			http.StatusForbidden,
		}
		for _, code := range nonTransientCodes {
			e := &auth.Error{Response: &http.Response{StatusCode: code}}
			if e.Temporary() {
				return fmt.Errorf("Assertion 6: expected status %d not to be temporary", code)
			}
		}
	}

	// Assertion 7: New2LOTokenProvider and New3LOTokenProvider validate mandatory configuration options
	{
		if _, err := auth.New2LOTokenProvider(nil); err == nil {
			return fmt.Errorf("Assertion 7: expected New2LOTokenProvider(nil) to return error")
		}
		if _, err := auth.New2LOTokenProvider(&auth.Options2LO{}); err == nil {
			return fmt.Errorf("Assertion 7: expected New2LOTokenProvider(empty) to return error")
		}
		if _, err := auth.New3LOTokenProvider(nil); err == nil {
			return fmt.Errorf("Assertion 7: expected New3LOTokenProvider(nil) to return error")
		}
		if _, err := auth.New3LOTokenProvider(&auth.Options3LO{}); err == nil {
			return fmt.Errorf("Assertion 7: expected New3LOTokenProvider(empty) to return error")
		}
	}

	return nil
}

原始种子者

匿名