CodeSampleX

サンプル

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

検証済みサンプル — golang cloud.google.com/go/auth v0.18.2: CachedTokenProviderOptions. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました.

sha256:61f1ff300419a76e31adbfe831ff50373f5ff5d82e3106638b12f7c194b18960

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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 cloud.google.com/go/auth.CachedTokenProviderOptions in pkg:golang/cloud.google.com/go/auth@v0.18.2
パッケージ
シンボル
  • cloud.google.com/go/auth.CachedTokenProviderOptions
作成日
2026-10-10T13:46:31Z

コントラクト

  1. CachedTokenProviderOptions enables caching of valid tokens across multiple calls to avoid duplicate provider invocations
  2. CachedTokenProviderOptions with DisableAutoRefresh returns the cached token even when the token has expired
  3. CachedTokenProviderOptions with DisableAsyncRefresh ensures blocking synchronous token refresh when tokens expire
  4. CachedTokenProviderOptions with ExpireEarly triggers proactive refresh for tokens within the expiration window

ファイル

  • 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.CachedTokenProviderOptions in 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
Demonstrate these symbols/APIs:
  - cloud.google.com/go/auth.CachedTokenProviderOptions

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:08d93e9fe59356b8b11d9f8dfbdb570eb97f1abb647e07f70e97c994c0054b1c","contract":["CachedTokenProviderOptions enables caching of valid tokens across multiple calls to avoid duplicate provider invocations","CachedTokenProviderOptions with DisableAutoRefresh returns the cached token even when the token has expired","CachedTokenProviderOptions with DisableAsyncRefresh ensures blocking synchronous token refresh when tokens expire","CachedTokenProviderOptions with ExpireEarly triggers proactive refresh for tokens within the expiration window"],"goal":"verify cloud.google.com/go/auth.CachedTokenProviderOptions in 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,"symbols":["cloud.google.com/go/auth.CachedTokenProviderOptions"]},"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","symbols":["cloud.google.com/go/auth.CachedTokenProviderOptions"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

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"
	"time"

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

// staticTokenProvider implements auth.TokenProvider returning a fixed token.
type staticTokenProvider struct {
	token *auth.Token
}

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

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

	baseProvider := &staticTokenProvider{
		token: &auth.Token{
			Value:  "sample-access-token-xyz",
			Type:   "Bearer",
			Expiry: time.Now().Add(1 * time.Hour),
		},
	}

	// Configure caching behavior using CachedTokenProviderOptions
	opts := &auth.CachedTokenProviderOptions{
		DisableAutoRefresh:  false,
		ExpireEarly:         5 * time.Minute,
		DisableAsyncRefresh: true,
	}

	cachedProvider := auth.NewCachedTokenProvider(baseProvider, opts)

	token, err := cachedProvider.Token(ctx)
	if err != nil {
		fmt.Printf("failed to retrieve cached token: %v\n", err)
		return
	}

	fmt.Printf("Retrieved token type: %s, valid: %t\n", token.Type, token.IsValid())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify cloud.google.com/go/auth.CachedTokenProviderOptions in pkg:golang/cloud.google.com/go/auth@v0.18.2",
  "kind": "HOW",
  "packages": [
    "pkg:golang/cloud.google.com/go/auth@v0.18.2"
  ],
  "symbols": [
    "cloud.google.com/go/auth.CachedTokenProviderOptions"
  ]
}
test/contract.go
package main

import (
	"context"
	"fmt"
	"os"
	"sync"
	"time"

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

type sequenceTokenProvider struct {
	mu     sync.Mutex
	calls  int
	tokens []*auth.Token
	notify chan struct{}
}

func (s *sequenceTokenProvider) Token(ctx context.Context) (*auth.Token, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	idx := s.calls
	s.calls++
	var tok *auth.Token
	if idx < len(s.tokens) {
		tok = s.tokens[idx]
	} else {
		tok = s.tokens[len(s.tokens)-1]
	}
	if s.notify != nil {
		select {
		case s.notify <- struct{}{}:
		default:
		}
	}
	return tok, nil
}

func (s *sequenceTokenProvider) callCount() int {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.calls
}

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

	// Assertion 1: CachedTokenProviderOptions enables caching of valid tokens across multiple calls to avoid duplicate provider invocations
	{
		validToken := &auth.Token{
			Value:  "valid-token-123",
			Type:   "Bearer",
			Expiry: time.Now().Add(1 * time.Hour),
		}
		mock := &sequenceTokenProvider{
			tokens: []*auth.Token{validToken},
		}

		opts := &auth.CachedTokenProviderOptions{}
		cached := auth.NewCachedTokenProvider(mock, opts)

		for i := 0; i < 3; i++ {
			tok, err := cached.Token(ctx)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Assertion 1 failed: unexpected error on call %d: %v\n", i+1, err)
				os.Exit(1)
			}
			if tok.Value != "valid-token-123" {
				fmt.Fprintf(os.Stderr, "Assertion 1 failed: expected token %q, got %q\n", "valid-token-123", tok.Value)
				os.Exit(1)
			}
		}

		if mock.callCount() != 1 {
			fmt.Fprintf(os.Stderr, "Assertion 1 failed: expected 1 underlying provider call, got %d\n", mock.callCount())
			os.Exit(1)
		}
	}

	// Assertion 2: CachedTokenProviderOptions with DisableAutoRefresh returns the cached token even when the token has expired
	{
		expiredToken := &auth.Token{
			Value:  "expired-token-val",
			Type:   "Bearer",
			Expiry: time.Now().Add(-10 * time.Minute),
		}
		mock := &sequenceTokenProvider{
			tokens: []*auth.Token{expiredToken},
		}

		opts := &auth.CachedTokenProviderOptions{
			DisableAutoRefresh: true,
		}
		cached := auth.NewCachedTokenProvider(mock, opts)

		tok1, err := cached.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: initial fetch error: %v\n", err)
			os.Exit(1)
		}
		if tok1.Value != "expired-token-val" {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected initial token %q, got %q\n", "expired-token-val", tok1.Value)
			os.Exit(1)
		}

		tok2, err := cached.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: second fetch error: %v\n", err)
			os.Exit(1)
		}
		if tok2.Value != "expired-token-val" {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected cached expired token %q, got %q\n", "expired-token-val", tok2.Value)
			os.Exit(1)
		}

		if mock.callCount() != 1 {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: DisableAutoRefresh should prevent refresh; expected 1 call, got %d\n", mock.callCount())
			os.Exit(1)
		}
	}

	// Assertion 3: CachedTokenProviderOptions with DisableAsyncRefresh ensures blocking synchronous token refresh when tokens expire
	{
		expiredToken := &auth.Token{
			Value:  "expired-initial-token",
			Type:   "Bearer",
			Expiry: time.Now().Add(-5 * time.Minute),
		}
		freshToken := &auth.Token{
			Value:  "fresh-refreshed-token",
			Type:   "Bearer",
			Expiry: time.Now().Add(1 * time.Hour),
		}
		mock := &sequenceTokenProvider{
			tokens: []*auth.Token{expiredToken, freshToken},
		}

		opts := &auth.CachedTokenProviderOptions{
			DisableAutoRefresh:  false,
			DisableAsyncRefresh: true,
		}
		cached := auth.NewCachedTokenProvider(mock, opts)

		tok1, err := cached.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: initial token retrieval error: %v\n", err)
			os.Exit(1)
		}
		if tok1.Value != "expired-initial-token" {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected initial token %q, got %q\n", "expired-initial-token", tok1.Value)
			os.Exit(1)
		}

		// Second call must block synchronously, detect expiration, and return fresh token
		tok2, err := cached.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: synchronous refresh error: %v\n", err)
			os.Exit(1)
		}
		if tok2.Value != "fresh-refreshed-token" {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected refreshed token %q, got %q\n", "fresh-refreshed-token", tok2.Value)
			os.Exit(1)
		}

		if mock.callCount() != 2 {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected 2 calls after blocking refresh, got %d\n", mock.callCount())
			os.Exit(1)
		}
	}

	// Assertion 4: CachedTokenProviderOptions with ExpireEarly triggers proactive refresh for tokens within the expiration window
	{
		nearExpiryToken := &auth.Token{
			Value:  "near-expiry-token",
			Type:   "Bearer",
			Expiry: time.Now().Add(10 * time.Second),
		}
		renewedToken := &auth.Token{
			Value:  "proactively-renewed-token",
			Type:   "Bearer",
			Expiry: time.Now().Add(2 * time.Hour),
		}
		notifyCh := make(chan struct{}, 5)
		mock := &sequenceTokenProvider{
			tokens: []*auth.Token{nearExpiryToken, renewedToken},
			notify: notifyCh,
		}

		opts := &auth.CachedTokenProviderOptions{
			ExpireEarly:         30 * time.Second,
			DisableAutoRefresh:  false,
			DisableAsyncRefresh: false,
		}
		cached := auth.NewCachedTokenProvider(mock, opts)

		tok1, err := cached.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: initial token retrieval error: %v\n", err)
			os.Exit(1)
		}
		if tok1.Value != "near-expiry-token" {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected initial token %q, got %q\n", "near-expiry-token", tok1.Value)
			os.Exit(1)
		}
		<-notifyCh // consume notification from initial fetch

		// Second call: token is within ExpireEarly window (10s left < 30s delta)
		// Should return stale token immediately and trigger async background refresh
		tok2, err := cached.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: stale token retrieval error: %v\n", err)
			os.Exit(1)
		}
		if tok2.Value != "near-expiry-token" {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected immediate stale token %q, got %q\n", "near-expiry-token", tok2.Value)
			os.Exit(1)
		}

		// Wait for background async refresh to complete
		select {
		case <-notifyCh:
		case <-time.After(2 * time.Second):
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: timed out waiting for proactive async refresh\n")
			os.Exit(1)
		}

		// Third call: should now yield the proactively renewed token
		tok3, err := cached.Token(ctx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: renewed token retrieval error: %v\n", err)
			os.Exit(1)
		}
		if tok3.Value != "proactively-renewed-token" {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected renewed token %q, got %q\n", "proactively-renewed-token", tok3.Value)
			os.Exit(1)
		}

		if mock.callCount() != 2 {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected 2 calls after proactive refresh, got %d\n", mock.callCount())
			os.Exit(1)
		}
	}

	fmt.Println("PASS: all CachedTokenProviderOptions contract assertions passed")
}

オリジンシーダー

匿名