CodeSampleX

サンプル

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

検証済みサンプル — golang cloud.google.com/go/auth v0.2.1. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました: Token.IsValid requires a non-empty Value and…

sha256:a4e14e932e1d31666f7fbbfeb6ddcb8500f4c9378e321e6e9be2af3801a0c0de

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。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-11-12

ケース

HOW
ゴール
verify pkg:golang/cloud.google.com/go/auth@v0.2.1
パッケージ
作成日
2026-11-12T02:24:53Z

コントラクト

  1. Token.IsValid requires a non-empty Value and an Expiry beyond the 215-second early-expiry window in v0.2.1
  2. NewCachedTokenProvider reuses valid cached tokens without calling the underlying TokenProvider and refreshes expired tokens
  3. NewCredentials preserves raw JSON bytes and resolves ProjectID, QuotaProjectID, and UniverseDomain via CredentialsPropertyFunc
  4. New3LOTokenProvider rejects StyleUnknown and performs offline PKCE authorization_code exchange with StyleInHeader Basic auth
  5. New3LOTokenProvider with StyleInParams sends client credentials in POST form body and returns *auth.Error reporting Temporary()=true on HTTP 503 and Temporary()=false on HTTP 400

ファイル

  • 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.2.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/cloud.google.com/go/auth@v0.2.1

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:3ca6b0891ce2d821975fde171f36905f1873473e2b870a5a0fac743927b5b2fb","contract":["Token.IsValid requires a non-empty Value and an Expiry beyond the 215-second early-expiry window in v0.2.1","NewCachedTokenProvider reuses valid cached tokens without calling the underlying TokenProvider and refreshes expired tokens","NewCredentials preserves raw JSON bytes and resolves ProjectID, QuotaProjectID, and UniverseDomain via CredentialsPropertyFunc","New3LOTokenProvider rejects StyleUnknown and performs offline PKCE authorization_code exchange with StyleInHeader Basic auth","New3LOTokenProvider with StyleInParams sends client credentials in POST form body and returns *auth.Error reporting Temporary()=true on HTTP 503 and Temporary()=false on HTTP 400"],"goal":"verify pkg:golang/cloud.google.com/go/auth@v0.2.1","kind":"HOW","packages":["pkg:golang/cloud.google.com/go/auth@v0.2.1"],"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.2.1"],"schemaVersion":1,"subject":"pkg:golang/cloud.google.com/go/auth@v0.2.1","verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

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

require cloud.google.com/go/compute/metadata v0.3.0 // indirect
go.sum
cloud.google.com/go/auth v0.2.1 h1:RMl6PI2MH1Qc3CM7XNJJHGwbC4WHQppSAjL0Cvu/M/g=
cloud.google.com/go/auth v0.2.1/go.mod h1:khQRBNrvNoHiHhV1iu2x8fSnlNbCaVHilznW5MAI5GY=
cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs=
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be h1:LG9vZxsWGOmUKieR8wPAUR3u3MpnYFQZROPIMaXh7/A=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY=
google.golang.org/grpc v1.63.0 h1:WjKe+dnvABXyPJMD7KDNLxtoGk5tgk+YFWN6cBWjZE8=
google.golang.org/grpc v1.63.0/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
main.go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

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

type staticProvider struct {
	token *auth.Token
}

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

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

	cached := auth.NewCachedTokenProvider(&staticProvider{
		token: &auth.Token{
			Value:  "demo-access-value",
			Type:   "Bearer",
			Expiry: time.Now().Add(time.Hour),
		},
	}, nil)

	creds := auth.NewCredentials(&auth.CredentialsOptions{
		TokenProvider: cached,
		ProjectIDProvider: auth.CredentialsPropertyFunc(func(context.Context) (string, error) {
			return "demo-project", nil
		}),
		UniverseDomainProvider: auth.CredentialsPropertyFunc(func(context.Context) (string, error) {
			return "example.com", nil
		}),
	})

	tok, err := creds.Token(ctx)
	if err != nil {
		panic(err)
	}
	proj, err := creds.ProjectID(ctx)
	if err != nil {
		panic(err)
	}
	domain, err := creds.UniverseDomain(ctx)
	if err != nil {
		panic(err)
	}

	srv := 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": "demo-3lo-value",
			"token_type":   "Bearer",
			"expires_in":   3600,
		})
	}))
	defer srv.Close()

	tp3lo, err := auth.New3LOTokenProvider(&auth.Options3LO{
		ClientID:     "demo-id",
		ClientSecret: "demo-pass",
		AuthURL:      srv.URL + "/authorize",
		TokenURL:     srv.URL + "/exchange",
		AuthStyle:    auth.StyleInParams,
		RefreshToken: "demo-refresh",
		Client:       srv.Client(),
	})
	if err != nil {
		panic(err)
	}
	exchanged, err := tp3lo.Token(ctx)
	if err != nil {
		panic(err)
	}

	fmt.Printf("credentials valid=%t project=%s domain=%s 3lo=%s\n", tok.IsValid(), proj, domain, exchanged.Value)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/cloud.google.com/go/auth@v0.2.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/cloud.google.com/go/auth@v0.2.1"
  ]
}
test/contract.go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"time"

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

type countingProvider struct {
	calls  int
	tokens []*auth.Token
}

func (c *countingProvider) Token(context.Context) (*auth.Token, error) {
	idx := c.calls
	c.calls++
	if idx >= len(c.tokens) {
		idx = len(c.tokens) - 1
	}
	return c.tokens[idx], nil
}

func verify() error {
	ctx := context.Background()

	// 1. Token.IsValid enforces non-empty Value and a 215-second early-expiry buffer in v0.2.1.
	var nilTok *auth.Token
	if nilTok.IsValid() {
		return fmt.Errorf("nil Token reported IsValid=true")
	}
	emptyTok := &auth.Token{Expiry: time.Now().Add(time.Hour)}
	if emptyTok.IsValid() {
		return fmt.Errorf("empty Value Token reported IsValid=true")
	}
	nearExpiryTok := &auth.Token{
		Value:  "near-expiry",
		Expiry: time.Now().Add(60 * time.Second),
	}
	if nearExpiryTok.IsValid() {
		return fmt.Errorf("Token expiring within 215s window reported IsValid=true")
	}
	validTok := &auth.Token{
		Value:  "far-expiry",
		Type:   "Bearer",
		Expiry: time.Now().Add(10 * time.Minute),
	}
	if !validTok.IsValid() {
		return fmt.Errorf("Token expiring in 10m reported IsValid=false")
	}

	// 2. NewCachedTokenProvider caches valid tokens and refreshes expired tokens.
	cp := &countingProvider{
		tokens: []*auth.Token{
			{Value: "short-lived", Expiry: time.Now().Add(-time.Minute)},
			{Value: "long-lived", Expiry: time.Now().Add(time.Hour)},
		},
	}
	cached := auth.NewCachedTokenProvider(cp, nil)
	first, err := cached.Token(ctx)
	if err != nil || first.Value != "short-lived" {
		return fmt.Errorf("unexpected first cached token: %v, err=%v", first, err)
	}
	second, err := cached.Token(ctx)
	if err != nil || second.Value != "long-lived" {
		return fmt.Errorf("expected refresh to long-lived token, got %v, err=%v", second, err)
	}
	third, err := cached.Token(ctx)
	if err != nil || third.Value != "long-lived" || cp.calls != 2 {
		return fmt.Errorf("expected cached reuse with 2 provider calls, got value=%q calls=%d err=%v", third.Value, cp.calls, err)
	}

	// 3. NewCredentials exposes JSON bytes and resolves properties via CredentialsPropertyFunc.
	rawJSON := []byte(`{"type":"authorized_user"}`)
	creds := auth.NewCredentials(&auth.CredentialsOptions{
		TokenProvider: cached,
		JSON:          rawJSON,
		ProjectIDProvider: auth.CredentialsPropertyFunc(func(context.Context) (string, error) {
			return "proj-alpha", nil
		}),
		QuotaProjectIDProvider: auth.CredentialsPropertyFunc(func(context.Context) (string, error) {
			return "quota-beta", nil
		}),
		UniverseDomainProvider: auth.CredentialsPropertyFunc(func(context.Context) (string, error) {
			return "example.com", nil
		}),
	})
	if string(creds.JSON()) != string(rawJSON) {
		return fmt.Errorf("Credentials.JSON mismatch: got %q", string(creds.JSON()))
	}
	if got, err := creds.ProjectID(ctx); err != nil || got != "proj-alpha" {
		return fmt.Errorf("Credentials.ProjectID mismatch: got %q, err=%v", got, err)
	}
	if got, err := creds.QuotaProjectID(ctx); err != nil || got != "quota-beta" {
		return fmt.Errorf("Credentials.QuotaProjectID mismatch: got %q, err=%v", got, err)
	}
	if got, err := creds.UniverseDomain(ctx); err != nil || got != "example.com" {
		return fmt.Errorf("Credentials.UniverseDomain mismatch: got %q, err=%v", got, err)
	}

	// 4. New3LOTokenProvider validates options, performs PKCE authorization code exchange with StyleInHeader,
	//    performs refresh_token exchange with StyleInParams, and surfaces retryable vs non-retryable *auth.Error.
	if _, err := auth.New3LOTokenProvider(&auth.Options3LO{
		ClientID:     "cid",
		ClientSecret: "csec",
		AuthURL:      "http://localhost/authorize",
		TokenURL:     "http://localhost/exchange",
		AuthStyle:    auth.StyleUnknown,
		RefreshToken: "rtok",
	}); err == nil {
		return fmt.Errorf("expected error when AuthStyle is StyleUnknown")
	}

	var capturedForm url.Values
	var capturedBasicUser, capturedBasicPass string
	var capturedBasicOK bool
	statusToReturn := http.StatusOK

	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		capturedBasicUser, capturedBasicPass, capturedBasicOK = r.BasicAuth()
		_ = r.ParseForm()
		capturedForm = r.PostForm

		if statusToReturn != http.StatusOK {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(statusToReturn)
			_ = json.NewEncoder(w).Encode(map[string]any{
				"error":             "temporarily_unavailable",
				"error_description": "simulated failure",
			})
			return
		}

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

	var capturedAuthURL string
	pkceTP, err := auth.New3LOTokenProvider(&auth.Options3LO{
		ClientID:    "pkce-client",
		AuthURL:     srv.URL + "/authorize",
		TokenURL:    srv.URL + "/exchange",
		RedirectURL: "http://localhost/callback",
		AuthStyle:   auth.StyleInHeader,
		Scopes:      []string{"scope.read"},
		Client:      srv.Client(),
		AuthHandlerOpts: &auth.AuthorizationHandlerOptions{
			State: "nonce-state-1",
			PKCEOpts: &auth.PKCEOptions{
				Challenge:       "challenge-value",
				ChallengeMethod: "S256",
				Verifier:        "verifier-value",
			},
			Handler: func(authCodeURL string) (string, string, error) {
				capturedAuthURL = authCodeURL
				return "auth-code-1", "nonce-state-1", nil
			},
		},
	})
	if err != nil {
		return fmt.Errorf("New3LOTokenProvider PKCE failed: %w", err)
	}
	pkceTok, err := pkceTP.Token(ctx)
	if err != nil {
		return fmt.Errorf("PKCE Token exchange failed: %w", err)
	}
	parsedAuthURL, err := url.Parse(capturedAuthURL)
	if err != nil {
		return fmt.Errorf("invalid authCodeURL: %w", err)
	}
	if q := parsedAuthURL.Query(); q.Get("code_challenge") != "challenge-value" || q.Get("code_challenge_method") != "S256" || q.Get("state") != "nonce-state-1" {
		return fmt.Errorf("missing PKCE/state query parameters in authCodeURL: %s", capturedAuthURL)
	}
	if !capturedBasicOK || capturedBasicUser != "pkce-client" || capturedForm.Get("code_verifier") != "verifier-value" || capturedForm.Get("grant_type") != "authorization_code" {
		return fmt.Errorf("unexpected PKCE exchange request: basicOK=%t user=%q form=%v", capturedBasicOK, capturedBasicUser, capturedForm)
	}
	if !pkceTok.IsValid() || pkceTok.Value != "issued-access" {
		return fmt.Errorf("unexpected PKCE token: %+v", pkceTok)
	}

	// Test StyleInParams and *auth.Error.Temporary() on HTTP 503 vs HTTP 400.
	paramsTP, err := auth.New3LOTokenProvider(&auth.Options3LO{
		ClientID:     "param-client",
		ClientSecret: "param-pass",
		AuthURL:      srv.URL + "/authorize",
		TokenURL:     srv.URL + "/exchange",
		AuthStyle:    auth.StyleInParams,
		RefreshToken: "refresh-1",
		Client:       srv.Client(),
	})
	if err != nil {
		return fmt.Errorf("New3LOTokenProvider StyleInParams failed: %w", err)
	}

	statusToReturn = http.StatusServiceUnavailable
	_, err = paramsTP.Token(ctx)
	var authErr *auth.Error
	if !errors.As(err, &authErr) || !authErr.Temporary() {
		return fmt.Errorf("expected temporary *auth.Error on 503, got %v", err)
	}
	if capturedBasicOK || capturedBasicPass != "" || capturedForm.Get("client_id") != "param-client" || capturedForm.Get("client_secret") != "param-pass" {
		return fmt.Errorf("expected client params in POST body without BasicAuth, got basicOK=%t form=%v", capturedBasicOK, capturedForm)
	}

	statusToReturn = http.StatusBadRequest
	_, err = paramsTP.Token(ctx)
	if !errors.As(err, &authErr) || authErr.Temporary() {
		return fmt.Errorf("expected non-temporary *auth.Error on 400, got %v", err)
	}

	return nil
}

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

オリジンシーダー

匿名