CodeSampleX

Beispiel

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

Verifiziertes Beispiel für golang cloud.google.com/go/auth v0.24.1: AuthorizationHandler. Der Vertrag lief auf go 1.26 · linux debian/x64 · docker und…

sha256:397e934c66ac02dffb6b06d4f49a8e47afad4fe0c5b3c39de1be6c741121e634

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 debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-10-13

Fall

HOW
Ziel
verify cloud.google.com/go/auth.AuthorizationHandler in pkg:golang/cloud.google.com/go/auth@v0.24.1
Pakete
Symbole
  • cloud.google.com/go/auth.AuthorizationHandler
Erstellt
2026-10-13T09:29:04Z

Contract

  1. New3LOTokenProvider accepts an auth.AuthorizationHandler via AuthorizationHandlerOptions
  2. TokenProvider calls the custom auth.AuthorizationHandler with the expected authorization URL
  3. TokenProvider propagates errors returned by the auth.AuthorizationHandler
  4. TokenProvider fails when auth.AuthorizationHandler returns mismatched state
  5. TokenProvider successfully exchanges code for auth.Token when auth.AuthorizationHandler succeeds

Dateien

  • PROMPT.md
  • auth_handler.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/contract.go

Quellartefakt herunterladen (tar.gz)

Quelltext

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.AuthorizationHandler 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.AuthorizationHandler

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.
auth_handler.go
package sample

import (
	"context"
	"net/http"

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

// Config configures a 3-legged OAuth TokenProvider with an AuthorizationHandler.
type Config struct {
	ClientID   string
	AuthURL    string
	TokenURL   string
	State      string
	Handler    auth.AuthorizationHandler
	HTTPClient *http.Client
}

// NewTokenProvider creates an auth.TokenProvider using the specified AuthorizationHandler.
func NewTokenProvider(cfg Config) (auth.TokenProvider, error) {
	opts := &auth.Options3LO{
		ClientID:  cfg.ClientID,
		AuthURL:   cfg.AuthURL,
		TokenURL:  cfg.TokenURL,
		AuthStyle: auth.StyleInParams,
		Client:    cfg.HTTPClient,
		AuthHandlerOpts: &auth.AuthorizationHandlerOptions{
			Handler: cfg.Handler,
			State:   cfg.State,
		},
	}
	return auth.New3LOTokenProvider(opts)
}

// StaticAuthorizationHandler returns an auth.AuthorizationHandler that always returns
// the predetermined authorization code and state.
func StaticAuthorizationHandler(code, state string) auth.AuthorizationHandler {
	return func(authCodeURL string) (string, string, error) {
		return code, state, nil
	}
}

// FetchToken retrieves an access token using the provided TokenProvider.
func FetchToken(ctx context.Context, tp auth.TokenProvider) (*auth.Token, error) {
	return tp.Token(ctx)
}
csx.json
{"case":{"caseId":"case:sha256:0d5ffe41f569fb03624e9423f0282d6f746221371328bf531e0d084e144c95e6","contract":["New3LOTokenProvider accepts an auth.AuthorizationHandler via AuthorizationHandlerOptions","TokenProvider calls the custom auth.AuthorizationHandler with the expected authorization URL","TokenProvider propagates errors returned by the auth.AuthorizationHandler","TokenProvider fails when auth.AuthorizationHandler returns mismatched state","TokenProvider successfully exchanges code for auth.Token when auth.AuthorizationHandler succeeds"],"goal":"verify cloud.google.com/go/auth.AuthorizationHandler 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.AuthorizationHandler"]},"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.AuthorizationHandler"],"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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify cloud.google.com/go/auth.AuthorizationHandler 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.AuthorizationHandler"
  ]
}
test/contract.go
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"sync/atomic"

	"sample"
)

func main() {
	// Assertion 1: New3LOTokenProvider accepts an auth.AuthorizationHandler via AuthorizationHandlerOptions
	handler1 := sample.StaticAuthorizationHandler("code-init", "state-1")
	tp1, err := sample.NewTokenProvider(sample.Config{
		ClientID: "client-id-1",
		AuthURL:  "http://localhost/auth",
		TokenURL: "http://localhost/token",
		State:    "state-1",
		Handler:  handler1,
	})
	if err != nil || tp1 == nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 1: failed to create TokenProvider with AuthorizationHandler: %v\n", err)
		os.Exit(1)
	}

	// Assertion 2: TokenProvider calls the custom auth.AuthorizationHandler with the expected authorization URL
	var capturedAuthURL string
	var handlerCalled atomic.Bool
	server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"access_token":"token-2","token_type":"bearer","expires_in":3600}`))
	}))
	defer server2.Close()

	customHandler := func(authCodeURL string) (string, string, error) {
		capturedAuthURL = authCodeURL
		handlerCalled.Store(true)
		return "code-2", "state-2", nil
	}

	tp2, err := sample.NewTokenProvider(sample.Config{
		ClientID:   "client-id-2",
		AuthURL:    "http://localhost/oauth/authorize",
		TokenURL:   server2.URL,
		State:      "state-2",
		HTTPClient: server2.Client(),
		Handler:    customHandler,
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2: failed to create TokenProvider: %v\n", err)
		os.Exit(1)
	}

	_, err = sample.FetchToken(context.Background(), tp2)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2: FetchToken failed: %v\n", err)
		os.Exit(1)
	}
	if !handlerCalled.Load() {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2: AuthorizationHandler was not called\n")
		os.Exit(1)
	}
	if !strings.Contains(capturedAuthURL, "client_id=client-id-2") ||
		!strings.Contains(capturedAuthURL, "state=state-2") ||
		!strings.Contains(capturedAuthURL, "response_type=code") {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2: captured authorization URL missing expected parameters: %s\n", capturedAuthURL)
		os.Exit(1)
	}

	// Assertion 3: TokenProvider propagates errors returned by the auth.AuthorizationHandler
	expectedErr := errors.New("authorization declined by user")
	failingHandler := func(authCodeURL string) (string, string, error) {
		return "", "", expectedErr
	}

	tp3, err := sample.NewTokenProvider(sample.Config{
		ClientID: "client-id-3",
		AuthURL:  "http://localhost/oauth/authorize",
		TokenURL: "http://localhost/token",
		State:    "state-3",
		Handler:  failingHandler,
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 3: failed to create TokenProvider: %v\n", err)
		os.Exit(1)
	}

	_, err = sample.FetchToken(context.Background(), tp3)
	if err == nil || !strings.Contains(err.Error(), "authorization declined by user") {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 3: expected handler error, got: %v\n", err)
		os.Exit(1)
	}

	// Assertion 4: TokenProvider fails when auth.AuthorizationHandler returns mismatched state
	mismatchedStateHandler := func(authCodeURL string) (string, string, error) {
		return "valid-code", "tampered-state", nil
	}

	tp4, err := sample.NewTokenProvider(sample.Config{
		ClientID: "client-id-4",
		AuthURL:  "http://localhost/oauth/authorize",
		TokenURL: "http://localhost/token",
		State:    "expected-state",
		Handler:  mismatchedStateHandler,
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 4: failed to create TokenProvider: %v\n", err)
		os.Exit(1)
	}

	_, err = sample.FetchToken(context.Background(), tp4)
	if err == nil || !strings.Contains(err.Error(), "state mismatch") {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 4: expected state mismatch error, got: %v\n", err)
		os.Exit(1)
	}

	// Assertion 5: TokenProvider successfully exchanges code for auth.Token when auth.AuthorizationHandler succeeds
	server5 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		if r.Form.Get("grant_type") != "authorization_code" || r.Form.Get("code") != "valid-code-5" {
			http.Error(w, "invalid request", http.StatusBadRequest)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{
			"access_token": "token-xyz-5",
			"token_type": "bearer",
			"expires_in": 7200
		}`))
	}))
	defer server5.Close()

	tp5, err := sample.NewTokenProvider(sample.Config{
		ClientID:   "client-id-5",
		AuthURL:    "http://localhost/oauth/authorize",
		TokenURL:   server5.URL,
		State:      "state-5",
		HTTPClient: server5.Client(),
		Handler:    sample.StaticAuthorizationHandler("valid-code-5", "state-5"),
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 5: failed to create TokenProvider: %v\n", err)
		os.Exit(1)
	}

	tok5, err := sample.FetchToken(context.Background(), tp5)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 5: FetchToken failed: %v\n", err)
		os.Exit(1)
	}
	if tok5 == nil || !tok5.IsValid() {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 5: expected valid token, got: %v\n", tok5)
		os.Exit(1)
	}
	if tok5.Value != "token-xyz-5" {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 5: expected token value 'token-xyz-5', got '%s'\n", tok5.Value)
		os.Exit(1)
	}
	if tok5.Type != "bearer" {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 5: expected token type 'bearer', got '%s'\n", tok5.Type)
		os.Exit(1)
	}
	if tok5.Expiry.IsZero() {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 5: expected non-zero expiry\n")
		os.Exit(1)
	}

	fmt.Println("PASS: cloud.google.com/go/auth.AuthorizationHandler verified")
}

Ursprungs-Seeder

anonym