CodeSampleX

Пример

cloud.google.com/go/auth v0.24.1: New3LOTokenProvider

Проверенный пример — golang cloud.google.com/go/auth v0.24.1: New3LOTokenProvider. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:28f2c420f3b75c77f763329bb94f015726b77eb2aaa012ae4f16b61b939dea36

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-12

Кейс

HOW
Цель
verify cloud.google.com/go/auth.New3LOTokenProvider in pkg:golang/cloud.google.com/go/auth@v0.24.1
Пакеты
Символы
  • cloud.google.com/go/auth.New3LOTokenProvider
Создан
2026-10-12T19:10:02Z

Контракт

  1. New3LOTokenProvider validates required options and returns an error when mandatory fields are missing
  2. New3LOTokenProvider creates a TokenProvider that fetches and parses access tokens from the token endpoint
  3. New3LOTokenProvider automatically caches retrieved tokens to prevent redundant network requests
  4. New3LOTokenProvider supports AuthorizationHandler to exchange authorization codes for access tokens
  5. New3LOTokenProvider detects and rejects authorization state mismatches during auth handler flow

Файлы

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

Use EXACTLY these public packages and versions:
  - pkg:golang/cloud.google.com/go/auth@v0.24.1
Demonstrate these symbols/APIs:
  - cloud.google.com/go/auth.New3LOTokenProvider

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:e59447cb1e45f1f84cfc7d5daf54d5fbcbe15b7bdcb608439a1bacbbc723330e","contract":["New3LOTokenProvider validates required options and returns an error when mandatory fields are missing","New3LOTokenProvider creates a TokenProvider that fetches and parses access tokens from the token endpoint","New3LOTokenProvider automatically caches retrieved tokens to prevent redundant network requests","New3LOTokenProvider supports AuthorizationHandler to exchange authorization codes for access tokens","New3LOTokenProvider detects and rejects authorization state mismatches during auth handler flow"],"goal":"verify cloud.google.com/go/auth.New3LOTokenProvider in pkg:golang/cloud.google.com/go/auth@v0.24.1","kind":"HOW","packages":["pkg:golang/cloud.google.com/go/auth@v0.24.1"],"schemaVersion":1,"symbols":["cloud.google.com/go/auth.New3LOTokenProvider"]},"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.24.1"],"schemaVersion":1,"subject":"pkg:golang/cloud.google.com/go/auth@v0.24.1","symbols":["cloud.google.com/go/auth.New3LOTokenProvider"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

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

require (
	cloud.google.com/go/compute/metadata v0.9.0 // indirect
	github.com/googleapis/gax-go/v2 v2.26.2 // indirect
	golang.org/x/sys v0.47.0 // indirect
)
go.sum
cloud.google.com/go/auth v0.24.1 h1:NTmd2iJb4DsGIav0KiqFMYI88nMshA2wnFMBatRmoCs=
cloud.google.com/go/auth v0.24.1/go.mod h1:1dmBXa9xfBvBr39ZnDUDkaaA91ccq9CcqENDgJA4d7c=
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.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/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.17 h1:73NfMHdiqo9JFU9+7a5ExpVa10/R29pXfZIaW559nrg=
github.com/googleapis/enterprise-certificate-proxy v0.3.17/go.mod h1:rSEsBUemEBZEexP2y6jPp16LUmUbjmSbcPMQizR0o4k=
github.com/googleapis/gax-go/v2 v2.26.2 h1:ydkmNXxj7bEmmeK5AihkKnWxyOyBR9TDebvp5L5izk8=
github.com/googleapis/gax-go/v2 v2.26.2/go.mod h1:sMKqnMesnKH+3wiRJROcttA+cJoZoGbZl1vDQ8XYtGk=
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.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
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.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
google.golang.org/api v0.288.0 h1:glhO/J88obKP5I269W3hB73dvBKrjU56ZfmNlNXpgTU=
google.golang.org/api v0.288.0/go.mod h1:lM2kYRzYUCBY91P9h6VF1PYmvhxii3O5hji37qRvIcY=
google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d h1:C9v1o0/4quuhOAfmRXA2j+we0PqZIp8traLdeogF3Ms=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260715232425-e75dac1f907d h1:Jkpk39hlTZOIp3RbfvNX9R8Hv+Sw0X89nlU/xFOErsc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260715232425-e75dac1f907d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
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"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

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

func main() {
	// Start an offline mock OAuth2 token endpoint
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{
			"access_token": "sample-access-token",
			"token_type":   "Bearer",
			"expires_in":   3600,
		})
	}))
	defer server.Close()

	opts := &auth.Options3LO{
		ClientID:     "example-client-id",
		ClientSecret: "example-client-secret",
		AuthURL:      server.URL + "/auth",
		TokenURL:     server.URL + "/token",
		AuthStyle:    auth.StyleInHeader,
		RefreshToken: "example-refresh-token",
		Client:       server.Client(),
	}

	tp, err := auth.New3LOTokenProvider(opts)
	if err != nil {
		panic(err)
	}

	tok, err := tp.Token(context.Background())
	if err != nil {
		panic(err)
	}

	fmt.Printf("Token: %s, Type: %s, Expiry: %s\n", tok.Value, tok.Type, tok.Expiry.Format(time.RFC3339))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify cloud.google.com/go/auth.New3LOTokenProvider in pkg:golang/cloud.google.com/go/auth@v0.24.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/cloud.google.com/go/auth@v0.24.1"
  ],
  "symbols": [
    "cloud.google.com/go/auth.New3LOTokenProvider"
  ]
}
test/contract.go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"strings"
	"sync/atomic"

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

func main() {
	ctx := context.Background()

	// Assertion 1: New3LOTokenProvider validates required options and returns an error when mandatory fields are missing
	{
		if _, err := auth.New3LOTokenProvider(nil); err == nil {
			fmt.Fprintln(os.Stderr, "FAIL assertion 1: expected error for nil options")
			os.Exit(1)
		}

		baseOpts := func() *auth.Options3LO {
			return &auth.Options3LO{
				ClientID:     "client-id",
				ClientSecret: "client-secret",
				AuthURL:      "http://localhost/auth",
				TokenURL:     "http://localhost/token",
				AuthStyle:    auth.StyleInHeader,
				RefreshToken: "refresh-token",
			}
		}

		// Missing ClientID
		opt := baseOpts()
		opt.ClientID = ""
		if _, err := auth.New3LOTokenProvider(opt); err == nil {
			fmt.Fprintln(os.Stderr, "FAIL assertion 1: expected error for missing ClientID")
			os.Exit(1)
		}

		// Missing ClientSecret without AuthHandlerOpts
		opt = baseOpts()
		opt.ClientSecret = ""
		if _, err := auth.New3LOTokenProvider(opt); err == nil {
			fmt.Fprintln(os.Stderr, "FAIL assertion 1: expected error for missing ClientSecret")
			os.Exit(1)
		}

		// Missing AuthURL
		opt = baseOpts()
		opt.AuthURL = ""
		if _, err := auth.New3LOTokenProvider(opt); err == nil {
			fmt.Fprintln(os.Stderr, "FAIL assertion 1: expected error for missing AuthURL")
			os.Exit(1)
		}

		// Missing TokenURL
		opt = baseOpts()
		opt.TokenURL = ""
		if _, err := auth.New3LOTokenProvider(opt); err == nil {
			fmt.Fprintln(os.Stderr, "FAIL assertion 1: expected error for missing TokenURL")
			os.Exit(1)
		}

		// Unknown AuthStyle
		opt = baseOpts()
		opt.AuthStyle = auth.StyleUnknown
		if _, err := auth.New3LOTokenProvider(opt); err == nil {
			fmt.Fprintln(os.Stderr, "FAIL assertion 1: expected error for unknown AuthStyle")
			os.Exit(1)
		}

		// Missing RefreshToken without AuthHandlerOpts
		opt = baseOpts()
		opt.RefreshToken = ""
		if _, err := auth.New3LOTokenProvider(opt); err == nil {
			fmt.Fprintln(os.Stderr, "FAIL assertion 1: expected error for missing RefreshToken")
			os.Exit(1)
		}
	}

	// Assertion 2: New3LOTokenProvider creates a TokenProvider that fetches and parses access tokens from the token endpoint
	// Assertion 3: New3LOTokenProvider automatically caches retrieved tokens to prevent redundant network requests
	{
		var tokenServerHits int64
		server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			atomic.AddInt64(&tokenServerHits, 1)
			w.Header().Set("Content-Type", "application/json")
			_ = json.NewEncoder(w).Encode(map[string]any{
				"access_token":  "access-token-abc",
				"token_type":    "Bearer",
				"refresh_token": "new-refresh-token",
				"expires_in":    3600,
			})
		}))
		defer server.Close()

		opts := &auth.Options3LO{
			ClientID:     "my-client-id",
			ClientSecret: "my-client-secret",
			AuthURL:      server.URL + "/auth",
			TokenURL:     server.URL + "/token",
			AuthStyle:    auth.StyleInHeader,
			RefreshToken: "init-refresh-token",
			Client:       server.Client(),
		}

		tp, err := auth.New3LOTokenProvider(opts)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL assertion 2: unexpected constructor error: %v\n", err)
			os.Exit(1)
		}

		// First call fetches from endpoint
		tok1, err := tp.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL assertion 2: failed to fetch token: %v\n", err)
			os.Exit(1)
		}
		if tok1.Value != "access-token-abc" {
			fmt.Fprintf(os.Stderr, "FAIL assertion 2: expected access-token-abc, got %q\n", tok1.Value)
			os.Exit(1)
		}
		if tok1.Type != "Bearer" {
			fmt.Fprintf(os.Stderr, "FAIL assertion 2: expected Bearer, got %q\n", tok1.Type)
			os.Exit(1)
		}
		if atomic.LoadInt64(&tokenServerHits) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL assertion 2: expected 1 server hit, got %d\n", tokenServerHits)
			os.Exit(1)
		}

		// Second call returns cached token without calling server again (Assertion 3)
		tok2, err := tp.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL assertion 3: failed to get cached token: %v\n", err)
			os.Exit(1)
		}
		if tok2.Value != "access-token-abc" {
			fmt.Fprintf(os.Stderr, "FAIL assertion 3: expected access-token-abc, got %q\n", tok2.Value)
			os.Exit(1)
		}
		if atomic.LoadInt64(&tokenServerHits) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL assertion 3: expected cached call not to increase server hits, got %d\n", tokenServerHits)
			os.Exit(1)
		}
	}

	// Assertion 4: New3LOTokenProvider supports AuthorizationHandler to exchange authorization codes for access tokens
	{
		server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if err := r.ParseForm(); err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
			grantType := r.Form.Get("grant_type")
			code := r.Form.Get("code")
			if grantType != "authorization_code" || code != "mock-auth-code" {
				http.Error(w, "invalid code or grant_type", http.StatusBadRequest)
				return
			}

			w.Header().Set("Content-Type", "application/json")
			_ = json.NewEncoder(w).Encode(map[string]any{
				"access_token": "handler-token-xyz",
				"token_type":   "Bearer",
				"expires_in":   3600,
			})
		}))
		defer server.Close()

		opts := &auth.Options3LO{
			ClientID:  "handler-client-id",
			AuthURL:   server.URL + "/auth",
			TokenURL:  server.URL + "/token",
			AuthStyle: auth.StyleInParams,
			Client:    server.Client(),
			AuthHandlerOpts: &auth.AuthorizationHandlerOptions{
				State: "valid-state-123",
				Handler: func(authCodeURL string) (string, string, error) {
					parsed, err := url.Parse(authCodeURL)
					if err != nil {
						return "", "", err
					}
					state := parsed.Query().Get("state")
					return "mock-auth-code", state, nil
				},
			},
		}

		tp, err := auth.New3LOTokenProvider(opts)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL assertion 4: unexpected error creating provider: %v\n", err)
			os.Exit(1)
		}

		tok, err := tp.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL assertion 4: error exchanging auth code: %v\n", err)
			os.Exit(1)
		}
		if tok.Value != "handler-token-xyz" {
			fmt.Fprintf(os.Stderr, "FAIL assertion 4: expected handler-token-xyz, got %q\n", tok.Value)
			os.Exit(1)
		}
	}

	// Assertion 5: New3LOTokenProvider detects and rejects authorization state mismatches during auth handler flow
	{
		opts := &auth.Options3LO{
			ClientID:  "mismatch-client-id",
			AuthURL:   "http://localhost/auth",
			TokenURL:  "http://localhost/token",
			AuthStyle: auth.StyleInParams,
			AuthHandlerOpts: &auth.AuthorizationHandlerOptions{
				State: "expected-state",
				Handler: func(authCodeURL string) (string, string, error) {
					return "code", "mismatched-state", nil
				},
			},
		}

		tp, err := auth.New3LOTokenProvider(opts)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL assertion 5: unexpected error creating provider: %v\n", err)
			os.Exit(1)
		}

		_, err = tp.Token(ctx)
		if err == nil {
			fmt.Fprintln(os.Stderr, "FAIL assertion 5: expected state mismatch error, got nil")
			os.Exit(1)
		}
		if !strings.Contains(err.Error(), "state mismatch") {
			fmt.Fprintf(os.Stderr, "FAIL assertion 5: expected error mentioning 'state mismatch', got %q\n", err.Error())
			os.Exit(1)
		}
	}

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

Исходный сидер

аноним