CodeSampleX

Пример

golang.org/x/net v0.28.0: xsrftoken.Generate, xsrftoken.Valid

Проверенный пример — golang golang.org/x/net v0.28.0: xsrftoken.Generate, xsrftoken.Valid. Контракт выполнен на go 1.26 · linux alpine/x64 · docker и пройден.

sha256:deb9bc64ba4c592490940ab604fc814a0894611fa937502e2c5d1148eb4a7508

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

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Кейс

HOW
Цель
verify golang.org/x/net/xsrftoken Generate and Valid in pkg:golang/golang.org/x/net@v0.28.0
Пакеты
Символы
  • golang.org/x/net/xsrftoken.Generate
  • golang.org/x/net/xsrftoken.Valid
Создан
2026-08-27T20:57:30Z

Контракт

  1. xsrftoken.Generate creates a non-empty token string for the given key, userID, and actionID
  2. xsrftoken.Valid returns true for matching token, key, userID, and actionID
  3. xsrftoken.Valid returns false when key, userID, or actionID differs from token generation parameters
  4. xsrftoken.Valid returns false for empty or malformed token strings
  5. xsrftoken.Generate produces different tokens for distinct actionIDs or userIDs

Файлы

  • 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 golang.org/x/net/xsrftoken Generate and Valid in pkg:golang/golang.org/x/net@v0.28.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/net@v0.28.0
Demonstrate these symbols/APIs:
  - golang.org/x/net/xsrftoken.Generate
  - golang.org/x/net/xsrftoken.Valid

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:fb12b226eb0ba48c05f077bc4c7489794091d112217126b35c12e9c0dbe0ec62","contract":["xsrftoken.Generate creates a non-empty token string for the given key, userID, and actionID","xsrftoken.Valid returns true for matching token, key, userID, and actionID","xsrftoken.Valid returns false when key, userID, or actionID differs from token generation parameters","xsrftoken.Valid returns false for empty or malformed token strings","xsrftoken.Generate produces different tokens for distinct actionIDs or userIDs"],"goal":"verify golang.org/x/net/xsrftoken Generate and Valid in pkg:golang/golang.org/x/net@v0.28.0","kind":"HOW","packages":["pkg:golang/golang.org/x/net@v0.28.0"],"schemaVersion":1,"symbols":["golang.org/x/net/xsrftoken.Generate","golang.org/x/net/xsrftoken.Valid"]},"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/golang.org/x/net@v0.28.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/net@v0.28.0","symbols":["golang.org/x/net/xsrftoken.Generate","golang.org/x/net/xsrftoken.Valid"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

require golang.org/x/net v0.28.0
go.sum
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
main.go
package main

import (
	"fmt"
	"golang.org/x/net/xsrftoken"
)

func main() {
	key := "sample-secret-key-abcdef123456"
	userID := "user-1001"
	actionID := "update-profile"

	// Generate a secure XSRF token for the user action
	token := xsrftoken.Generate(key, userID, actionID)
	fmt.Printf("Generated XSRF token: %s\n", token)

	// Validate the token against the correct credentials
	isValid := xsrftoken.Valid(token, key, userID, actionID)
	fmt.Printf("Token validation result: %t\n", isValid)

	// Attempt validation with mismatched action ID
	isInvalid := xsrftoken.Valid(token, key, userID, "delete-account")
	fmt.Printf("Mismatched action validation result: %t\n", isInvalid)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/net/xsrftoken Generate and Valid in pkg:golang/golang.org/x/net@v0.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/net@v0.28.0"
  ],
  "symbols": [
    "golang.org/x/net/xsrftoken.Generate",
    "golang.org/x/net/xsrftoken.Valid"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"

	"golang.org/x/net/xsrftoken"
)

func main() {
	key := "test-secret-key-32bytes-secure-val"
	userID := "alice"
	actionID := "edit-post-42"

	// 1. xsrftoken.Generate creates a non-empty token string for the given key, userID, and actionID
	token := xsrftoken.Generate(key, userID, actionID)
	if token == "" {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: Generate returned empty token\n")
		os.Exit(1)
	}

	// 2. xsrftoken.Valid returns true for matching token, key, userID, and actionID
	if !xsrftoken.Valid(token, key, userID, actionID) {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: Valid returned false for matching token and arguments\n")
		os.Exit(1)
	}

	// 3. xsrftoken.Valid returns false when key, userID, or actionID differs from token generation parameters
	if xsrftoken.Valid(token, "wrong-key", userID, actionID) {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: Valid returned true for wrong key\n")
		os.Exit(1)
	}
	if xsrftoken.Valid(token, key, "bob", actionID) {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: Valid returned true for wrong userID\n")
		os.Exit(1)
	}
	if xsrftoken.Valid(token, key, userID, "delete-post-42") {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: Valid returned true for wrong actionID\n")
		os.Exit(1)
	}

	// 4. xsrftoken.Valid returns false for empty or malformed token strings
	if xsrftoken.Valid("", key, userID, actionID) {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: Valid returned true for empty token\n")
		os.Exit(1)
	}
	if xsrftoken.Valid("invalid:token:format", key, userID, actionID) {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: Valid returned true for malformed colon-separated token\n")
		os.Exit(1)
	}
	if xsrftoken.Valid("invalidbase64token", key, userID, actionID) {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: Valid returned true for arbitrary invalid base64 token\n")
		os.Exit(1)
	}

	// 5. xsrftoken.Generate produces different tokens for distinct actionIDs or userIDs
	tokenDifferentAction := xsrftoken.Generate(key, userID, "other-action")
	if token == tokenDifferentAction {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: Generate produced identical token for different action\n")
		os.Exit(1)
	}
	tokenDifferentUser := xsrftoken.Generate(key, "bob", actionID)
	if token == tokenDifferentUser {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: Generate produced identical token for different user\n")
		os.Exit(1)
	}

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

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

аноним