CodeSampleX

Пример

github.com/jackc/pgpassfile v1.0.0: Demonstrate that ParsePassfile silently drops lines with unescaped colons in fields and requires backslash escaping for literal colons and backslashes.

Проверенный пример — golang github.com/jackc/pgpassfile v1.0.0: Demonstrate that ParsePassfile silently drops lines with unescaped colons in fields and…

sha256:87ccb81eee71a0bc8355fa200b883b504c0916568d628a7a8cdca62b7ba04960

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

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

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

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

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

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

Кейс

HOW
Цель
Demonstrate that ParsePassfile silently drops lines with unescaped colons in fields and requires backslash escaping for literal colons and backslashes.
Пакеты
Символы
  • pgpassfile.ParsePassfile
  • pgpassfile.FindPassword
  • pgpassfile.ReadPassfile
Окружение
go
Создан
2026-08-19T13:58:00Z

Контракт

  1. ParsePassfile silently discards lines with unescaped colons in password fields rather than returning an error or preserving colons, causing FindPassword to return an empty string.
  2. Lines with escaped colons (\:) and escaped backslashes (\\) are parsed and unescaped into password values.
  3. Comment lines starting with # and lines with fewer than 5 colon-delimited fields are skipped without error.
  4. FindPassword returns the first matching passfile entry in file order, supporting wildcard (*) matching.

Файлы

  • NOTES.md
  • csx.json
  • go.mod
  • go.sum
  • passfile_test.go

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# PostgreSQL Passfile Configuration and Parsing Behavior

## Prior Knowledge Search
A search for known verified solutions returned `NO_SAFE_MATCH`, indicating no existing sample answered this configuration behavior.

## Pinned Release
- Package: `github.com/jackc/pgpassfile`
- Version: `v1.0.0`

## Observed Behavior

PostgreSQL `.pgpass` files follow the 5-field format `hostname:port:database:username:password`.

1. **Unescaped Colon Silent Drop**:
   When a field such as the password contains an unescaped colon (`:`), the line splits into more than 5 colon-separated tokens. The parser does not return an error and does not treat everything after the fourth colon as the password; instead, it silently discards the line and returns `nil` for that entry. As a result, `ParsePassfile` completes with `err == nil` and zero parsed entries. Subsequent calls to `FindPassword` return an empty string (`""`).

2. **Escape Sequence Requirements**:
   To represent literal colons and backslashes in password fields, they must be escaped using `\:` and `\\`. The parser substitutes escaped sequences prior to field splitting and restores them during unescaping, allowing characters like `:` and `\` to be preserved in credentials.

3. **Comments and Malformed Lines**:
   Lines starting with `#` as well as lines with fewer than 5 colon-separated fields are skipped silently without raising a parse error.

4. **Entry Precedence and Wildcards**:
   `FindPassword` returns the first matching entry in sequential order. A broad wildcard entry (e.g. `*:5432:mydb:user:pass`) listed before a specific host entry takes precedence over later entries.

## Failure Mode
The failure mode is silent: `ParsePassfile` and `ReadPassfile` return a `nil` error, leaving the application with an empty passfile structure (`len(Entries) == 0`). Password lookups return `""` with no indication of why authentication configuration failed to load.
csx.json
{"case":{"believed":"ParsePassfile returns a parsing error when encountering unescaped colons in password fields or parses them as part of the password field.","caseId":"case:sha256:8e73f2ace9818b9f4468b207b465e18c9b4a6f0a5c18c94f8b21050f186bb1e1","contract":["ParsePassfile silently discards lines with unescaped colons in password fields rather than returning an error or preserving colons, causing FindPassword to return an empty string.","Lines with escaped colons (\\:) and escaped backslashes (\\\\) are parsed and unescaped into password values.","Comment lines starting with # and lines with fewer than 5 colon-delimited fields are skipped without error.","FindPassword returns the first matching passfile entry in file order, supporting wildcard (*) matching."],"goal":"Demonstrate that ParsePassfile silently drops lines with unescaped colons in fields and requires backslash escaping for literal colons and backslashes.","kind":"HOW","packages":["pkg:golang/github.com/jackc/pgpassfile@v1.0.0"],"schemaVersion":1,"symbols":["pgpassfile.ParsePassfile","pgpassfile.FindPassword","pgpassfile.ReadPassfile"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/jackc/pgpassfile@v1.0.0"],"schemaVersion":1,"symbols":["pgpassfile.ParsePassfile","pgpassfile.FindPassword","pgpassfile.ReadPassfile"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.20

require github.com/jackc/pgpassfile v1.0.0
go.sum
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
passfile_test.go
package sample_test

import (
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/jackc/pgpassfile"
)

func TestUnescapedColonSilentDrop(t *testing.T) {
	// A line containing an unescaped colon inside a field (such as a password with colons)
	// produces 6 colon-separated tokens instead of 5.
	// ParsePassfile silently drops the entry without returning an error.
	rawConfig := "db.example.com:5432:mydb:myuser:secret:token\n"
	pf, err := pgpassfile.ParsePassfile(strings.NewReader(rawConfig))
	if err != nil {
		t.Fatalf("expected nil error, got %v", err)
	}
	if len(pf.Entries) != 0 {
		t.Fatalf("expected 0 entries due to unescaped colon splitting, got %d", len(pf.Entries))
	}

	// Lookup fails silently and returns empty string
	pw := pf.FindPassword("db.example.com", "5432", "mydb", "myuser")
	if pw != "" {
		t.Fatalf("expected empty password for dropped line, got %q", pw)
	}
}

func TestEscapedColonAndBackslashResolution(t *testing.T) {
	// When colons and backslashes are properly escaped with a backslash (\: and \\),
	// the line matches exactly 5 tokens, is parsed successfully, and unescaped.
	rawConfig := "db.example.com:5432:mydb:myuser:secret\\:token\\\\123\n"
	pf, err := pgpassfile.ParsePassfile(strings.NewReader(rawConfig))
	if err != nil {
		t.Fatalf("expected nil error, got %v", err)
	}
	if len(pf.Entries) != 1 {
		t.Fatalf("expected 1 entry, got %d", len(pf.Entries))
	}

	pw := pf.FindPassword("db.example.com", "5432", "mydb", "myuser")
	expected := "secret:token\\123"
	if pw != expected {
		t.Fatalf("expected password %q, got %q", expected, pw)
	}
}

func TestCommentsAndMalformedLinesAreIgnored(t *testing.T) {
	// Comments (#) and lines with fewer than 5 fields are silently ignored with err == nil
	content := "# This is a comment\n" +
		"invalid_line_without_colons\n" +
		"db.example.com:5432:mydb:user_only\n" +
		"db.example.com:5432:mydb:validuser:validpass\n"

	pf, err := pgpassfile.ParsePassfile(strings.NewReader(content))
	if err != nil {
		t.Fatalf("expected nil error, got %v", err)
	}
	if len(pf.Entries) != 1 {
		t.Fatalf("expected exactly 1 valid entry, got %d", len(pf.Entries))
	}

	pw := pf.FindPassword("db.example.com", "5432", "mydb", "validuser")
	if pw != "validpass" {
		t.Fatalf("expected 'validpass', got %q", pw)
	}
}

func TestWildcardAndFirstMatchPrecedence(t *testing.T) {
	// Earlier entries take precedence over later entries even if later entries are more specific
	content := "*:5432:mydb:appuser:first_match_pass\n" +
		"db.example.com:5432:mydb:appuser:specific_pass\n"

	pf, err := pgpassfile.ParsePassfile(strings.NewReader(content))
	if err != nil {
		t.Fatalf("expected nil error, got %v", err)
	}
	if len(pf.Entries) != 2 {
		t.Fatalf("expected 2 entries, got %d", len(pf.Entries))
	}

	pw := pf.FindPassword("db.example.com", "5432", "mydb", "appuser")
	if pw != "first_match_pass" {
		t.Fatalf("expected first matching line 'first_match_pass', got %q", pw)
	}
}

func TestReadPassfileFromDisk(t *testing.T) {
	tempDir := t.TempDir()
	filePath := filepath.Join(tempDir, "pgpass.conf")

	fileData := "postgres.example.com:5432:analytics:readonly:ro_secret\n"
	if err := os.WriteFile(filePath, []byte(fileData), 0600); err != nil {
		t.Fatalf("failed to write test passfile: %v", err)
	}

	pf, err := pgpassfile.ReadPassfile(filePath)
	if err != nil {
		t.Fatalf("expected nil error reading passfile, got %v", err)
	}
	if len(pf.Entries) != 1 {
		t.Fatalf("expected 1 entry, got %d", len(pf.Entries))
	}

	pw := pf.FindPassword("postgres.example.com", "5432", "analytics", "readonly")
	if pw != "ro_secret" {
		t.Fatalf("expected 'ro_secret', got %q", pw)
	}
}

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

csx-seed