embargo

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 6 Imported by: 0

README

embargo

sensitive detects sensitive data in text and returns its type, byte positions, and confidence, with optional masking.

Go Reference Coverage MultiPlatformUnitTest OpenSSF Scorecard

logo

Quick start

Save this as main.go in a new directory:

package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithPAN(), embargo.WithEmail())
	text := "user tanaka@example.com paid with 4532015112830366"
	for _, f := range scanner.ScanString(text) {
		fmt.Printf("%s: %s (%.2f)\n", f.DetectorName, f.RawValue, f.Confidence)
	}
	// Output:
	// pan: 4532015112830366 (1.00)
	// email: tanaka@example.com (1.00)
}
go mod init example.com/scan
go get github.com/nao1215/embargo
go run .

This uses a test card number and an example.com address. Choose detectors explicitly as above; NewScanner shows empty, selected, and all-detector configurations.

Why embargo?

Logs, support messages, and imported text can contain payment details, personal data, or credentials. embargo finds their locations so your Go program can flag, classify, or mask them before forwarding the text.

Dedicated parsers and checksum checks help distinguish candidates from ordinary text, including Japanese phone numbers and My Number. Detection results remain available when you need your own handling policy.

Supported detectors

Option Detects Validation
WithPAN() Credit card numbers (Visa, Mastercard, Amex, JCB, Discover, Diners, UnionPay) BIN prefix + Luhn algorithm
WithEmail() Email addresses Structure + known TLD check
WithJPPhone() Japanese phone numbers (mobile, landline, IP phone, toll-free, M2M/IoT, service) Prefix classification + digit count
WithMyNumber() Japanese My Number (12-digit individual number) MOD 11 check digit
WithJWT() JSON Web Tokens Header decode + alg key check
WithAWSKey() AWS Access Key IDs (AKIA... / ASIA...) Prefix + 20-char alphanumeric
WithIBAN() International Bank Account Numbers Country code + MOD 97 check digit
WithIPAddr() IPv4 and IPv6 addresses net.ParseIP + octet range
WithSWIFTBIC() SWIFT/BIC codes Format + country code validation
WithABARouting() US ABA routing numbers Prefix range + checksum
WithUKSortCode() UK sort codes (XX-XX-XX) Pattern + boundary checks
WithCVV() Card verification values (CVV/CVC/CID) Context keyword + digit length (context-based, weaker)
WithCardExpiry() Card expiration dates Context keyword + MM/YY validation (context-based, weaker)
WithPaymentToken() Payment processor tokens (Stripe/PayPal/Square) Prefix + minimum body length
WithBankAccount() Bank account numbers (context-based) Context keyword + digit range (context-based, weaker)
WithACHTrace() ACH trace numbers Context keyword + prefix range (context-based, weaker)
WithMerchantID() Merchant/terminal IDs Context keyword + format (context-based, weaker)
WithBTC() Bitcoin addresses (P2PKH, P2SH, Bech32, Bech32m/Taproot) Base58Check (double SHA-256) / Bech32 polynomial checksum
WithETH() Ethereum addresses (0x + 40 hex) EIP-55 mixed-case checksum (Keccak-256)
WithGitHubToken() GitHub tokens (classic ghp_/gho_/ghu_/ghs_/ghr_, fine-grained github_pat_) Prefix + body character set + length
WithSlackToken() Slack API tokens (xoxb-/xoxp-/xoxa-/xoxo-/xoxr-/xoxs-) Prefix + type character + minimum body length
WithGoogleAPIKey() Google API keys (AIza...) Prefix + 35-char body
WithPrivateKeyPEM() PEM private key headers (RSA/EC/DSA/OpenSSH/PKCS#8) -----BEGIN [ALGO ]PRIVATE KEY----- header parse
WithAll() All of the above

The table summarizes validation; each detector type documents its exact acceptance rules and score. Detection does not establish that an account exists or that a credential authenticates. WithAll includes context-based matches; use individual options when false positives are costly.

Installation and requirements

In an existing Go module, run go get github.com/nao1215/embargo. The library requires Go 1.22 or later and is tested on Linux, macOS, and Windows.

Scan bytes, strings, or streams

Use Scan for []byte, ScanString for strings, or ScanReader for a reader whose content fits in memory. For line-oriented logs, import strings and use ScanLines:

scanner := embargo.NewScanner(embargo.WithEmail())
input := "safe line\nadmin@example.com\n"
err := scanner.ScanLines(strings.NewReader(input), func(n int, line []byte, findings []embargo.Finding) {
	for _, f := range findings {
		fmt.Printf("line %d [%d:%d]: %s\n", n, f.Start, f.End, line[f.Start:f.End])
	}
})
if err != nil {
	fmt.Println("error:", err)
}
// Output:
// line 2 [0:17]: admin@example.com

The method docs specify line limits, offsets, callback lifetime, and read errors. The package documentation explains the scanning pipeline; benchmarks record its measurements.

Work with findings

Finding exposes the matched value and detector-specific detail. Use Is or an Is* method to select a detector, Kind to classify financial data, PII, or credentials, and typed accessors such as PANDetail to read metadata without a direct type assertion.

The detail example shows brand and last-four access. Scanner options show how to retain overlapping matches and order findings by position. Full-width digit support lists the detectors that normalize Japanese numeric text.

Filter by confidence

WithMinConfidence selects the results to keep:

text := "user tanaka@example.com bank account 12345678"
for _, threshold := range []float64{0.4, 0.8} {
	scanner := embargo.NewScanner(
		embargo.WithEmail(), embargo.WithBankAccount(),
		embargo.WithMinConfidence(threshold),
	)
	fmt.Printf("threshold %.1f: %d findings\n", threshold, len(scanner.ScanString(text)))
}
// Output:
// threshold 0.4: 2 findings
// threshold 0.8: 1 findings

Read the confidence model before using the score as a policy; Finding.Level offers named categories when an exact number is unnecessary.

Mask findings

Import detector and mask alongside embargo to assign a strategy to each detector:

scanner := embargo.NewScanner(embargo.WithPAN(), embargo.WithEmail())
text := "user tanaka@example.com paid with 4532015112830366"
findings := scanner.ScanString(text)

// Apply different masking strategies per detector.
masked := mask.Mask(text, findings, map[embargo.DetectorName]mask.Strategy{
	detector.NamePAN:   mask.Last4,
	detector.NameEmail: mask.Partial,
})

fmt.Println(masked)
// Output:
// user t*****@example.com paid with ************0366

MaskAll applies one strategy to every finding. The strategy example compares Redact, Last4, First1Last4, Partial, and Hash; their docs specify what remains visible and how overlaps are handled.

Add a detector

Use WithDetector with detector.NewRegex for a custom pattern such as a ticket ID. For domain validation, implement Detector. The custom detector guide explains hint selection and links the runnable example.

Testing

The library has zero dependencies; test-only tools live in the separate tests/ module (Go 1.26.0+). Run go test ./... in both directories; this executes the Go examples and checks README snippets against them. See testing for lint, vet, fuzzing, golden updates, coverage, and mutation checks.

Contributing

Bug reports, feature requests, and pull requests are welcome through GitHub Issues and CONTRIBUTING.md. Use synthetic data in tests and see CLAUDE.md for development rules. You can also sponsor maintenance.

License

MIT License.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

CHIKAMATSU Naohiro
CHIKAMATSU Naohiro

💻 📖

This project follows the all-contributors specification. Contributions of any kind welcome!

Documentation

Overview

Package embargo detects sensitive data in text; the optional mask subpackage applies masking to its findings.

Choosing an API

Use NewScanner to select detectors, Scanner.Scan for bytes, and Scanner.ScanString for strings. For readers, Scanner.ScanReader handles content that fits in memory and Scanner.ScanLines handles line-oriented logs. Each method has a runnable example; its documentation defines offsets, limits, and error behavior.

Confidence

Confidence is a detector-specific heuristic, not a probability or proof that an identifier is assigned or a credential authenticates. A WithMinConfidence threshold of 0.8 selects the high category; 0.4 includes medium confidence. detector.Finding.Level supplies the category, and each detector type documents its scoring rules.

Context-based detectors use nearby keywords rather than checksums. In particular, CVV and card expiry can still pass a high-confidence filter; choose detector options to control what is considered sensitive. WithAll is useful for exploration, while explicit options suit stricter auditing.

How It Works

  1. Return immediately for empty input.
  2. Check cached hints with bytes.Contains, folding ASCII letters for case-insensitive matching; detectors without hints always run.
  3. Run matching detectors' parsers and domain validation, such as BIN, Luhn, and MOD 97 checks.
  4. Merge findings using the overlap, ordering, and filtering rules in Scanner.Scan.

Hint filtering avoids parser work when a required substring is absent; its benefit depends on the input and enabled detectors. See the benchmarks for recorded measurements and reproduction commands.

Custom Detectors

Wrap a compiled pattern with detector.NewRegex and pass it to WithDetector, as its example shows. A specific hint such as TICKET- lets the scanner skip the regex when that substring is absent. For parsing or validation beyond a regex, implement Detector; its methods define names, exhaustive hints, and finding offsets. Use dedicated parsers when scan cost matters.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithPAN(), embargo.WithEmail())
	text := "user tanaka@example.com paid with 4532015112830366"
	for _, f := range scanner.ScanString(text) {
		fmt.Printf("%s: %s (%.2f)\n", f.DetectorName, f.RawValue, f.Confidence)
	}
}
Output:
pan: 4532015112830366 (1.00)
email: tanaka@example.com (1.00)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Detector

type Detector = detector.Detector

Detector aliases detector.Detector, the contract for custom detectors.

type DetectorName

type DetectorName = detector.DetectorName

DetectorName aliases detector.DetectorName, a detector identifier.

type Finding

type Finding = detector.Finding

Finding aliases detector.Finding, a match with byte offsets and detector-specific detail.

type Option

type Option func(*Scanner)

Option configures a Scanner through NewScanner.

func WithABARouting

func WithABARouting() Option

WithABARouting enables detector.ABARouting detection.

func WithACHTrace

func WithACHTrace() Option

WithACHTrace enables detector.ACHTrace detection.

func WithAWSKey

func WithAWSKey() Option

WithAWSKey enables detector.AWSKey detection.

func WithAll

func WithAll() Option

WithAll enables every built-in detector, including context-based detectors that can produce false positives. Select individual With options when those matches are unwanted.

func WithBTC

func WithBTC() Option

WithBTC enables detector.BTC detection.

func WithBankAccount

func WithBankAccount() Option

WithBankAccount enables detector.BankAccount detection.

func WithCVV

func WithCVV() Option

WithCVV enables detector.CVV detection.

func WithCardExpiry

func WithCardExpiry() Option

WithCardExpiry enables detector.CardExpiry detection.

func WithDetector

func WithDetector(d Detector) Option

WithDetector registers d; a nil interface is ignored. See Detector for the hint and finding contracts.

Example
package main

import (
	"fmt"
	"regexp"

	"github.com/nao1215/embargo"
	"github.com/nao1215/embargo/detector"
)

func main() {
	ticket := detector.NewRegex(
		"ticket_id", regexp.MustCompile(`TICKET-\d{4}`),
		[][]byte{[]byte("TICKET-")}, 0.9,
	)
	scanner := embargo.NewScanner(embargo.WithDetector(ticket))
	for _, f := range scanner.ScanString("see TICKET-4321 for details") {
		fmt.Printf("%s: %s (%.1f)\n", f.DetectorName, f.RawValue, f.Confidence)
	}
}
Output:
ticket_id: TICKET-4321 (0.9)

func WithETH

func WithETH() Option

WithETH enables detector.ETH detection.

func WithEmail

func WithEmail() Option

WithEmail enables detector.Email detection.

func WithGitHubToken

func WithGitHubToken() Option

WithGitHubToken enables detector.GitHubToken detection.

func WithGoogleAPIKey

func WithGoogleAPIKey() Option

WithGoogleAPIKey enables detector.GoogleAPIKey detection.

func WithIBAN

func WithIBAN() Option

WithIBAN enables detector.IBAN detection.

func WithIPAddr

func WithIPAddr() Option

WithIPAddr enables detector.IPAddr detection.

func WithJPPhone

func WithJPPhone() Option

WithJPPhone enables detector.JPPhone detection.

func WithJWT

func WithJWT() Option

WithJWT enables detector.JWT detection.

func WithMerchantID

func WithMerchantID() Option

WithMerchantID enables detector.MerchantID detection.

func WithMinConfidence

func WithMinConfidence(threshold float64) Option

WithMinConfidence keeps findings with confidence >= threshold after deduplication and sorting. Values below 0 become 0, values above 1 become 1, and 0 (the default) disables filtering.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "user tanaka@example.com bank account 12345678"
	for _, threshold := range []float64{0.4, 0.8} {
		scanner := embargo.NewScanner(
			embargo.WithEmail(), embargo.WithBankAccount(),
			embargo.WithMinConfidence(threshold),
		)
		fmt.Printf("threshold %.1f: %d findings\n", threshold, len(scanner.ScanString(text)))
	}
}
Output:
threshold 0.4: 2 findings
threshold 0.8: 1 findings

func WithMyNumber

func WithMyNumber() Option

WithMyNumber enables detector.MyNumber detection.

func WithPAN

func WithPAN() Option

WithPAN enables detector.PAN detection.

func WithPaymentToken

func WithPaymentToken() Option

WithPaymentToken enables detector.PaymentToken detection.

func WithPrivateKeyPEM

func WithPrivateKeyPEM() Option

WithPrivateKeyPEM enables detector.PrivateKeyPEM detection.

func WithSWIFTBIC

func WithSWIFTBIC() Option

WithSWIFTBIC enables detector.SWIFTBIC detection.

func WithSlackToken

func WithSlackToken() Option

WithSlackToken enables detector.SlackToken detection.

func WithSortByPosition

func WithSortByPosition() Option

WithSortByPosition orders findings by start offset ascending, then confidence descending and detector name.

func WithUKSortCode

func WithUKSortCode() Option

WithUKSortCode enables detector.UKSortCode detection.

func WithoutDedup

func WithoutDedup() Option

WithoutDedup retains overlapping findings from all enabled detectors.

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner detects sensitive data with configured Detector implementations. Create one with NewScanner; concurrent scans require each registered detector to support concurrent use.

func NewScanner

func NewScanner(opts ...Option) *Scanner

NewScanner applies opts in order; no options enables no detectors. Nil options are ignored, and the last registration for each detector name wins.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "tanaka@example.com 4532015112830366 from 192.0.2.1"
	for _, config := range []struct {
		name string
		opts []embargo.Option
	}{
		{"no options", nil},
		{"selected", []embargo.Option{embargo.WithPAN(), embargo.WithEmail()}},
		{"all built-ins", []embargo.Option{embargo.WithAll()}},
	} {
		scanner := embargo.NewScanner(config.opts...)
		fmt.Printf("%s: %d findings\n", config.name, len(scanner.ScanString(text)))
	}
}
Output:
no options: 0 findings
selected: 2 findings
all built-ins: 3 findings
Example (Options)
package main

import (
	"fmt"
	"regexp"

	"github.com/nao1215/embargo"
	"github.com/nao1215/embargo/detector"
)

func main() {
	// Keep overlapping candidates and process them in input order.
	custom := detector.NewRegex("reference", regexp.MustCompile(`REF-\d{4}`), nil, 0.5)
	scanner := embargo.NewScanner(
		embargo.WithEmail(),
		embargo.WithDetector(custom),
		embargo.WithoutDedup(),
		embargo.WithSortByPosition(),
	)
	for _, f := range scanner.ScanString("REF-1234@example.com then admin@example.com") {
		fmt.Printf("%s [%d:%d] %.1f\n", f.DetectorName, f.Start, f.End, f.Confidence)
	}
}
Output:
email [0:20] 1.0
reference [0:8] 0.5
email [26:43] 1.0

func (*Scanner) Scan

func (s *Scanner) Scan(data []byte) []Finding

Scan returns findings in data, or nil for empty input. It keeps the highest-confidence non-overlapping findings, then orders them by confidence descending, start offset ascending, and detector name.

Overlap ties prefer an earlier start, then a later end, then detector name. WithoutDedup retains overlaps; WithSortByPosition changes ordering; WithMinConfidence filters the final results.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithPAN())
	data := []byte("カード: 4532-0151-1283-0366")
	for _, f := range scanner.Scan(data) {
		fmt.Printf("%s [%d:%d]: %s\n", f.DetectorName, f.Start, f.End, data[f.Start:f.End])
	}
}
Output:
pan [11:30]: 4532-0151-1283-0366

func (*Scanner) ScanLines

func (s *Scanner) ScanLines(r io.Reader, fn func(lineNum int, line []byte, findings []Finding)) error

ScanLines calls fn synchronously for each line containing findings, with 1-based line numbers and line-relative byte offsets. The line excludes its LF or CRLF terminator and is a copy that fn may retain.

The buffer starts at 64 KiB and grows to 1 MiB, including space needed for the line terminator. A line that exceeds the buffer limit returns bufio.ErrTooLong; use Scanner.ScanReader for longer lines. Read errors are returned after any callbacks already made.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithEmail())
	input := "safe line\nadmin@example.com\n"
	err := scanner.ScanLines(strings.NewReader(input), func(n int, line []byte, findings []embargo.Finding) {
		for _, f := range findings {
			fmt.Printf("line %d [%d:%d]: %s\n", n, f.Start, f.End, line[f.Start:f.End])
		}
	})
	if err != nil {
		fmt.Println("error:", err)
	}
}
Output:
line 2 [0:17]: admin@example.com

func (*Scanner) ScanReader

func (s *Scanner) ScanReader(r io.Reader) ([]Finding, error)

ScanReader reads all of r into memory and calls Scanner.Scan. A read error returns nil findings and the error; use Scanner.ScanLines for incremental processing.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithEmail())
	reader := strings.NewReader("safe line\nadmin@example.com\n")
	findings, err := scanner.ScanReader(reader)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	for _, f := range findings {
		fmt.Printf("%s [%d:%d]\n", f.RawValue, f.Start, f.End)
	}
}
Output:
admin@example.com [10:27]

func (*Scanner) ScanString

func (s *Scanner) ScanString(text string) []Finding

ScanString calls Scanner.Scan on the bytes of text.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithEmail())
	findings := scanner.ScanString("contact admin@example.com for support")
	fmt.Printf("found %d email(s)\n", len(findings))
	for _, f := range findings {
		fmt.Println(f.RawValue)
	}
}
Output:
found 1 email(s)
admin@example.com

type SensitiveKind

type SensitiveKind = detector.SensitiveKind

SensitiveKind aliases detector.SensitiveKind, a finding category.

revive:disable-next-line:exported

Directories

Path Synopsis
adapters
grpc module
logrus module
otel module
sentry module
zap module
zerolog module
Package detector provides built-in sensitive-data detectors and the Detector extension interface.
Package detector provides built-in sensitive-data detectors and the Detector extension interface.
internal
ascii
Package ascii provides low-level ASCII byte manipulation helpers shared across the embargo module.
Package ascii provides low-level ASCII byte manipulation helpers shared across the embargo module.
Package mask replaces sensitive findings using per-detector Mask or uniform MaskAll strategies.
Package mask replaces sensitive findings using per-detector Mask or uniform MaskAll strategies.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL