embargo

package module
v0.4.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: 18 Imported by: 0

README

embargo

All Contributors

Go Reference MultiPlatformUnitTest reviewdog Gosec Trivy Coverage OpenSSF Scorecard

Go gopher peeking over the embargo title, with email and token values blacked out

embargo finds secrets and personal data in the output of Go programs, masks them in logs and JSON, and fails your tests when one leaks.

  • postgres://reader:forgotten@db.example in a log line becomes postgres://reader:[REDACTED]@db.example without any field rule.
  • slog, zap, zerolog and logrus keep their JSON shape; only the values change.
  • embargo.NewSecret(key) prints [REDACTED] wherever it is formatted.
  • A test fails when a fake secret planted in your code shows up in its output.

Quick start

Requires Go 1.26.11 or later.

go get github.com/nao1215/embargo@latest
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "email=alice@example.com card=4111111111111111"
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail, embargo.KindPAN))

	fmt.Println(embargo.Mask(text, scanner.ScanString(text)))

	// Output: email=[REDACTED] card=[REDACTED]
}

Mask everything a scanner finds, or keep part of a value:

Operation Actual text
Input INFO checkout email=alice@example.com card=4111111111111111
Mask INFO checkout email=[REDACTED] card=[REDACTED]
MaskFunc: keep last four INFO checkout email=[REDACTED] card=[REDACTED]1111
Overlapping matches token=abcdef with abcd cdef → token=[REDACTED]

Scanner options and custom replacements

Detect without rules

The scanner reads the text itself, so no field has to be listed first.

text := "postgres://reader:forgotten@db.example/orders"
scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindCredential))
fmt.Println(embargo.Mask(text, scanner.ScanString(text)))
// Output: postgres://reader:[REDACTED]@db.example/orders
Group What is detected
Credentials URL and DSN passwords, password= and auth headers, provider tokens, JWT, PEM keys
Cards Card numbers (Luhn), CVV, expiry, payment tokens, merchant ID
Bank IBAN, SWIFT/BIC, ABA routing, UK sort code, bank account, ACH trace
Crypto Bitcoin and Ethereum addresses
Personal Email, IP address, Japanese phone numbers and My Number, including full-width digits

Every detector and how it validates · Provider token formats

Pick the kinds you need: on 2.7 KB of log lines with no secret, WithKinds(KindEmail) returns in 0.11 µs because there is no @ to inspect, while WithAll() takes 85 µs. Per-detector benchmarks

Mask logs

next is the handler your logger already uses.

scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail))
logger := slog.New(embargo.NewSlogHandler(next, scanner))

logger.Info("checkout", "email", "alice@example.com")

// Output: {"level":"INFO","msg":"checkout","email":"[REDACTED]"}

Values under keys such as password, token or authorization are masked whole, and structs and maps stay JSON objects. Structured values and key rules

zap (NewWriteSyncer), zerolog (NewWriter) and logrus (NewFormatter) get the same detectors and key rules through optional modules. Installation and limits

Values that must never print

key := embargo.NewSecret("fake-key")

fmt.Println(key)

// Output: [REDACTED]

key.Reveal() returns the value. Tested outputs lists every path checked to print [REDACTED].

Input loads secrets from JSON, config files and SQL rows.

Prefer your own types? Follow the standard-library-only pattern and check them with embargotest.CheckValue.

Fail tests on leaks

func TestMain(m *testing.M) { os.Exit(embargotest.Guard(m)) }

Guard reruns the package tests and fails when a canary (a fake secret) or a detected value appears in stdout, stderr, default slog output or child processes. ExampleGuard

For one test, a recorder checks both that the expected output exists and that no canary escaped:

func TestReadmeCheckOutput(t *testing.T) {
    t.Parallel()
    recorder := embargotest.New(t)
    logger := slog.New(slog.NewJSONHandler(recorder.Writer("logs"), nil))

    logger.Info("accepted", "token", embargo.NewSecret(recorder.Canary()))

    recorder.ExpectJSON("logs", nil, map[string]string{"token": "[REDACTED]"}, 1)
    recorder.Check()
}

HTTP, child processes, and canaries in env, files and headers

In a sample service with planted leaks (a DSN, wrapped errors, an Authorization header, a token in a request body), the slog and zap paths masked every leak that reached a logger. The redirect URL never reaches a logger; embargotest.HTTP catches it. Scenario table

Tested outputs

Each link opens the test that produces and checks the shown output.

Output Actual output (excerpt for SDKs)
fmt [REDACTED]
slog TextHandler level=INFO msg=event token=[REDACTED] nested.again=[REDACTED]
slog JSONHandler {"level":"INFO","msg":"event","token":"[REDACTED]","nested":{"again":"[REDACTED]"}}
encoding/json "[REDACTED]"
encoding/xml <record><token>[REDACTED]</token></record>
text/template [REDACTED]
zap JSON core {"level":"info","msg":"event","token":"[REDACTED]"}
zerolog JSON {"level":"info","token":"[REDACTED]","message":"event"}
logrus JSON {"level":"info","msg":"event","token":"[REDACTED]"}
OTel SDK {"Key":"key","Value":{"Type":"STRING","Value":"[REDACTED]"}}
Sentry "signing":{"key":"[REDACTED]"}
HTTP [REDACTED]
Child panic panic: [REDACTED]

Complete integration checks.

Accuracy

Held-out synthetic set, default minimum confidence 0. Generation, test cases and observed misses · Credential detectors, measured separately

Precision and recall on held-out synthetic samples

Detector details
aba_routing ach_trace awskey
bank_account btc card_expiry
cvv email eth
github_token google_api_key iban
ipaddr jwt merchant_id
mynumber pan payment_token
phone_jp private_key_pem slack_token
swiftbic uk_sortcode

Testing

Technique Tests
Examples and unit tests Examples, masking
Generated properties Properties, Bitcoin
Fuzzing Scanner, recorder
Mutation gremlins command
Real output tests Loggers, HTTP

Coverage 94.9% · mutation score 90.06% · 9 fuzz targets, 2323625 executions.

Commands, measurement scope and conditions.

Benchmarks

Scanner throughput and slog time

All detectors scan sensitive text at 4.76 MB/s; masking a clean slog event takes 2.57 µs, 2.9× the plain handler.

Machine, method, profiles and full results.

Same slog events through masq v0.2.3: 52–78% less time on four of five events, no significant difference on the map event, fewer allocations on all five. Comparison · benchstat

Contributing

Report a bug → add a synthetic regression → open a pull request. You can also sponsor maintenance.

License

MIT License.

The Go gopher was designed by Renee French and is licensed under CC BY 4.0.

Contributors

Thanks to our contributors:

CHIKAMATSU Naohiro
CHIKAMATSU Naohiro

Code Documentation

This project follows the all-contributors specification.

Documentation

Overview

Package embargo detects and masks sensitive text inside a Go program. Use NewScanner and Mask for text, NewSlogHandler for runtime logs, and NewSecret for values that should print as [REDACTED].

Scanning

NewScanner and a zero-value Scanner enable every built-in detector. WithKinds narrows that selection; WithDetector adds an application pattern. Findings contain original byte positions and retain overlaps. MaskFunc supports custom replacements, such as keeping a card's last four digits.

Values and output

Secret hides supported formatted and encoded representations; Secret.Reveal deliberately exposes the value. Input decodes strings or bytes into a Secret snapshot. These types do not erase memory.

The embargotest package captures real log, HTTP and child-process output in tests. It checks a known fake secret, detector findings and expected content.

See the detector cases and output examples for supported representations.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "email=alice@example.com card=4111111111111111"
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail, embargo.KindPAN))

	fmt.Println(embargo.Mask(text, scanner.ScanString(text)))

}
Output:
email=[REDACTED] card=[REDACTED]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Mask added in v0.4.0

func Mask(text string, findings []Finding) string

Mask replaces overlapping spans with [REDACTED]. Adjacent spans remain separate. Invalid ranges redact the entire text. Neither input nor findings is changed.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "email=alice@example.com"

	fmt.Println(embargo.Mask(text, embargo.NewScanner().ScanString(text)))

}
Output:
email=[REDACTED]
Example (Log)
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "INFO checkout email=alice@example.com card=4111111111111111"
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail, embargo.KindPAN))
	findings := scanner.ScanString(text)

	fmt.Println(text)
	fmt.Println(embargo.Mask(text, findings))
	fmt.Println(embargo.MaskFunc(text, findings, func(kind embargo.Kind, value string) string {
		if kind == embargo.KindPAN {
			return "[REDACTED]" + value[len(value)-4:]
		}
		return "[REDACTED]"
	}))

}
Output:
INFO checkout email=alice@example.com card=4111111111111111
INFO checkout email=[REDACTED] card=[REDACTED]
INFO checkout email=[REDACTED] card=[REDACTED]1111
Example (Overlap)
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "token=abcdef"
	findings := []embargo.Finding{
		{Kind: "first", Start: 6, End: 10, Confidence: 1},
		{Kind: "second", Start: 8, End: 12, Confidence: 1},
	}

	fmt.Println(text)
	fmt.Println(text[findings[0].Start:findings[0].End], text[findings[1].Start:findings[1].End])
	fmt.Println(embargo.Mask(text, findings))

}
Output:
token=abcdef
abcd cdef
token=[REDACTED]

func MaskFunc added in v0.4.0

func MaskFunc(text string, findings []Finding, replace func(kind Kind, value string) string) string

MaskFunc replaces each merged span with replace(kind, value), in input order. The kind comes from the highest-confidence finding; ties prefer kind, start, then descending end. The value covers the full merged span. Adjacent spans stay separate. Invalid ranges redact all text without calling replace. A nil callback panics.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "card=4111111111111111"
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindPAN))
	masked := embargo.MaskFunc(text, scanner.ScanString(text), func(_ embargo.Kind, value string) string { return "[REDACTED]" + value[len(value)-4:] })

	fmt.Println(masked)

}
Output:
card=[REDACTED]1111

func NewSlogHandler added in v0.4.0

func NewSlogHandler(next slog.Handler, scanner *Scanner) slog.Handler

NewSlogHandler scans messages, keys, groups and values before forwarding to next. Both arguments must be non-nil; invalid dependencies panic. Any values keep their encoded JSON shape; errors keep their Error text. Clean scalars and record metadata keep their types; WithAttrs freezes values.

Scanner or normalization failures drop the record and return a fixed error. Values added by downstream handlers need their own output check. See the logging guide for value handling and error observation.

Example
package main

import (
	"log/slog"
	"os"

	"github.com/nao1215/embargo"
)

func main() {
	next := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
			if attr.Key == slog.TimeKey {
				return slog.Attr{}
			}
			return attr
		},
	})
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail, embargo.KindPAN))
	logger := slog.New(embargo.NewSlogHandler(next, scanner))
	logger.Info("checkout", "email", "alice@example.com", "card", "4532015112830366")

}
Output:
level=INFO msg=checkout email=[REDACTED] card=[REDACTED]
Example (Short)
package main

import (
	"log/slog"
	"os"

	"github.com/nao1215/embargo"
)

func main() {
	next := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey {
				return slog.Attr{}
			}
			return a
		},
	})

	// README:begin
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail))
	logger := slog.New(embargo.NewSlogHandler(next, scanner))

	logger.Info("checkout", "email", "alice@example.com")
	// README:end

}
Output:
{"level":"INFO","msg":"checkout","email":"[REDACTED]"}

Types

type Detector

type Detector interface {
	// Scan returns findings in data without retaining or modifying it.
	Scan(data []byte) []Finding
}

Detector finds application-specific values. Scan must terminate, leave input unchanged, return nonempty kinds and valid byte spans/scores, and support concurrent calls when shared.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/nao1215/embargo"
)

type projectToken struct{}

func (projectToken) Scan(data []byte) []embargo.Finding {
	const token = "fake_project_token"
	start := bytes.Index(data, []byte(token))
	if start < 0 {
		return nil
	}
	return []embargo.Finding{{Kind: "project_token", Start: start, End: start + len(token), Confidence: 1}}
}

func main() {
	var detector embargo.Detector = projectToken{}

	fmt.Println(len(detector.Scan([]byte("fake_project_token"))))

}
Output:
1

type Finding

type Finding struct {
	// Kind identifies the detection family.
	Kind Kind
	// Start is the inclusive byte offset.
	Start int
	// End is the exclusive byte offset.
	End int
	// Confidence is a heuristic score in [0,1], not a probability.
	Confidence float64
}

Finding locates a sensitive-data candidate in the original input without retaining its value.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "card=4111111111111111"
	finding := embargo.Finding{Kind: embargo.KindPAN, Start: 5, End: 21, Confidence: 1}

	fmt.Println(finding.Kind, finding.Start, finding.End, finding.Confidence)

	fmt.Println(embargo.Mask(text, []embargo.Finding{finding}))

}
Output:
pan 5 21 1
card=[REDACTED]

type Input added in v0.4.0

type Input[T interface{ ~string | ~[]byte }] struct {
	// contains filtered or unexported fields
}

Input decodes a string or byte slice during initialization. Do not decode or display the same Input concurrently. Publish its Secret snapshot afterwards. Decode into a fresh DTO: outer JSON syntax errors and absent fields bypass these methods. Discard the entire DTO when its decoder fails.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var input embargo.Input[string]
	if err := input.UnmarshalText([]byte("fake-key")); err != nil {
		panic(err)
	}

	fmt.Println(input)

}
Output:
[REDACTED]

func (Input[T]) Format added in v0.4.0

func (i Input[T]) Format(state fmt.State, verb rune)

Format writes the marker without examining the input.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var value embargo.Input[string]
	if err := value.UnmarshalText([]byte("fake-key")); err != nil {
		panic(err)
	}

	fmt.Printf("%+#v\n", value)

}
Output:
[REDACTED]

func (Input[T]) GoString added in v0.4.0

func (i Input[T]) GoString() string

GoString returns the fixed redaction marker.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var value embargo.Input[string]
	if err := value.UnmarshalText([]byte("fake-key")); err != nil {
		panic(err)
	}

	fmt.Println(value.GoString())

}
Output:
[REDACTED]

func (Input[T]) LogValue added in v0.4.0

func (i Input[T]) LogValue() slog.Value

LogValue returns the marker as a slog string.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var value embargo.Input[string]
	if err := value.UnmarshalText([]byte("fake-key")); err != nil {
		panic(err)
	}

	fmt.Println(value.LogValue().String())

}
Output:
[REDACTED]

func (Input[T]) MarshalJSON added in v0.4.0

func (i Input[T]) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON string containing the marker, never input data.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var value embargo.Input[string]
	if err := value.UnmarshalText([]byte("fake-key")); err != nil {
		panic(err)
	}
	data, err := value.MarshalJSON()
	if err != nil {
		panic(err)
	}

	fmt.Println(string(data))

}
Output:
"[REDACTED]"

func (Input[T]) MarshalText added in v0.4.0

func (i Input[T]) MarshalText() ([]byte, error)

MarshalText returns the marker, never input data.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var value embargo.Input[string]
	if err := value.UnmarshalText([]byte("fake-key")); err != nil {
		panic(err)
	}
	data, err := value.MarshalText()
	if err != nil {
		panic(err)
	}

	fmt.Println(string(data))

}
Output:
[REDACTED]

func (*Input[T]) Scan added in v0.4.0

func (i *Input[T]) Scan(src any) error

Scan implements sql.Scanner for textual secrets read from a database. Strings and byte slices are copied without invoking user conversion methods; SQL NULL clears the Input. Other types and the redaction marker clear it and return a fixed error. Scan during initialization, then publish Secret(). To write to a database, deliberately pass Secret().Reveal() as the argument; neither Input nor Secret implements driver.Valuer or implicitly reveals data.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var password embargo.Input[string]
	// rows.Scan(&password) calls the same method with the driver's string or bytes.
	if err := password.Scan([]byte("synthetic-database-password")); err != nil {
		panic(err)
	}
	secret := password.Secret()
	fmt.Println(secret)
	fmt.Println(secret.Reveal() == "synthetic-database-password")
}
Output:
[REDACTED]
true

func (Input[T]) Secret added in v0.4.0

func (i Input[T]) Secret() Secret[T]

Secret returns the current snapshot; later decoding does not change it.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var input embargo.Input[string]
	if err := input.UnmarshalText([]byte("first")); err != nil {
		panic(err)
	}
	snapshot := input.Secret()
	if err := input.UnmarshalText([]byte("second")); err != nil {
		panic(err)
	}

	fmt.Println(len(snapshot.Reveal()))

}
Output:
5

func (Input[T]) String added in v0.4.0

func (i Input[T]) String() string

String returns the fixed redaction marker.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var value embargo.Input[string]
	if err := value.UnmarshalText([]byte("fake-key")); err != nil {
		panic(err)
	}

	fmt.Println(value.String())

}
Output:
[REDACTED]

func (*Input[T]) UnmarshalJSON added in v0.4.0

func (i *Input[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts only JSON strings; byte slices use base64 decoding. Named types use their underlying representation, never their own decoders. Failure, including the redaction marker, clears this Input and returns a fixed error. A nil receiver returns the same error.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var config struct {
		Token embargo.Input[string] `json:"token"`
	}
	if err := json.Unmarshal([]byte(`{"token":"fake-key"}`), &config); err != nil {
		panic(err)
	}

	fmt.Println(config.Token.Secret())

}
Output:
[REDACTED]
Example (Failure)
package main

import (
	"encoding/json"
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var config struct {
		First  embargo.Input[string] `json:"first"`
		Second embargo.Input[string] `json:"second"`
	}
	if err := json.Unmarshal([]byte(`{"first":"fake-key","second":"[REDACTED]"}`), &config); err != nil {
		fmt.Println("configuration rejected")
		return // Discard the whole partially decoded config.
	}
	panic("unexpected successful decode")

}
Output:
configuration rejected

func (*Input[T]) UnmarshalText added in v0.4.0

func (i *Input[T]) UnmarshalText(data []byte) error

UnmarshalText copies raw text without trimming or guessing an encoding. The redaction marker is rejected with the same fixed error as JSON failures.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var input embargo.Input[[]byte]
	if err := input.UnmarshalText([]byte("fake-key")); err != nil {
		panic(err)
	}

	fmt.Println(input.Secret())

}
Output:
[REDACTED]

type Kind added in v0.4.0

type Kind string

Kind identifies a built-in or application-defined detection family.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	kind := embargo.Kind("project_token")

	fmt.Println(kind)

}
Output:
project_token
const (
	// KindServiceToken selects documented service prefixes and Slack webhook secrets.
	KindServiceToken Kind = "service_token"
	// KindHighEntropy selects unlabeled random-looking tokens at confidence 0.3.
	KindHighEntropy Kind = "high_entropy"
	// KindCredential selects secret assignments, Authorization values and URL/DSN passwords.
	KindCredential Kind = "credential"
	// KindPAN selects payment card candidates, including lower-confidence checksum failures.
	KindPAN Kind = "pan"
	// KindEmail selects email addresses.
	KindEmail Kind = "email"
	// KindJPPhone selects Japanese telephone numbers.
	KindJPPhone Kind = "phone_jp"
	// KindMyNumber selects Japanese My Number identifiers.
	KindMyNumber Kind = "mynumber"
	// KindJWT selects JSON Web Token candidates.
	KindJWT Kind = "jwt"
	// KindAWSKey selects AWS access key IDs.
	KindAWSKey Kind = "awskey"
	// KindIBAN selects international bank account numbers.
	KindIBAN Kind = "iban"
	// KindIPAddr selects IPv4 and IPv6 addresses.
	KindIPAddr Kind = "ipaddr"
	// KindSWIFTBIC selects SWIFT/BIC candidates.
	KindSWIFTBIC Kind = "swiftbic"
	// KindABARouting selects US ABA routing numbers.
	KindABARouting Kind = "aba_routing"
	// KindUKSortCode selects UK bank sort codes.
	KindUKSortCode Kind = "uk_sortcode"
	// KindCVV selects card verification codes near context keywords.
	KindCVV Kind = "cvv"
	// KindCardExpiry selects card expiry dates near context keywords.
	KindCardExpiry Kind = "card_expiry"
	// KindPaymentToken selects payment-provider token candidates.
	KindPaymentToken Kind = "payment_token"
	// KindBankAccount selects bank account numbers near context keywords.
	KindBankAccount Kind = "bank_account"
	// KindACHTrace selects ACH trace numbers near context keywords.
	KindACHTrace Kind = "ach_trace"
	// KindMerchantID selects merchant IDs near context keywords.
	KindMerchantID Kind = "merchant_id"
	// KindBTC selects Bitcoin addresses.
	KindBTC Kind = "btc"
	// KindETH selects Ethereum addresses.
	KindETH Kind = "eth"
	// KindGitHubToken selects GitHub token candidates.
	KindGitHubToken Kind = "github_token"
	// KindSlackToken selects Slack token candidates.
	KindSlackToken Kind = "slack_token"
	// KindGoogleAPIKey selects Google API key candidates.
	KindGoogleAPIKey Kind = "google_api_key"
	// KindPrivateKeyPEM selects PEM private keys through their END marker, or incomplete headers.
	KindPrivateKeyPEM Kind = "private_key_pem"
)

type Scanner

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

Scanner holds immutable scan policy. Its zero value selects all built-in detectors. Concurrent use requires custom detectors to support concurrent Scan calls.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var scanner embargo.Scanner

	fmt.Println(len(scanner.ScanString("alice@example.com")))

}
Output:
1

func NewScanner

func NewScanner(opts ...ScannerOption) *Scanner

NewScanner selects all built-ins by default, including IP addresses and context-based detectors. The default minimum confidence is 0, including ambiguous candidates. Use WithKinds to narrow selection. Options apply in order; nil options are ignored.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	text := "alice@example.com 192.0.2.1 cvv: 123"

	fmt.Println(len(embargo.NewScanner().ScanString(text)))

	fmt.Println(len(embargo.NewScanner(embargo.WithKinds(embargo.KindEmail)).ScanString(text)))

}
Output:
4
1

func (*Scanner) MaskJSON added in v0.4.0

func (scanner *Scanner) MaskJSON(data []byte) (masked []byte, err error)

MaskJSON masks one JSON document using this scanner's detectors and sensitive key policy. It preserves object order, duplicate keys, arrays, nulls, booleans and clean numbers without rounding. Sensitive numbers become marker strings; a sensitive key replaces its entire value, including containers, with a marker. The returned compact JSON owns its bytes and has no trailing newline. Input and output are limited to 1 MiB, nesting to 64, and cumulative detector input to 4 MiB. Invalid input, exceeded limits and panics return no bytes and a fixed error without input data. It does not modify the source document. Use it before sending JSON API responses, exports or audit records.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail))
	// Sanitize an audit export before uploading it to a support system.
	safe, err := scanner.MaskJSON([]byte(`{"user":{"email":"alice@example.com","password":"opaque"},"amount":125,"paid":true}`))
	if err != nil {
		panic(err)
	}
	fmt.Println(string(safe))
}
Output:
{"user":{"email":"[REDACTED]","password":"[REDACTED]"},"amount":125,"paid":true}

func (*Scanner) Scan

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

Scan returns every finding, including overlaps, ordered by start, descending end, kind, then descending confidence. Built-ins decode one layer of valid percent escapes (%HH), except KindCredential parses original URL/DSN delimiters. Literal + and invalid escapes are preserved; offsets always refer to original bytes. Other encodings are not decoded. Custom detectors receive the original bytes. Invalid custom findings panic with a fixed message.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindPAN))
	for _, f := range scanner.Scan([]byte("card=4111111111111111")) {
		fmt.Println(f.Kind, f.Start, f.End)
	}

}
Output:
pan 5 21

func (*Scanner) ScanLines

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

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

The buffer limit is 1 MiB including delimiter space; longer lines return bufio.ErrTooLong. 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.WithKinds(embargo.KindEmail))
	err := scanner.ScanLines(strings.NewReader("safe\nalice@example.com\n"), func(n int, line []byte, findings []embargo.Finding) {
		fmt.Println(n, embargo.Mask(string(line), findings))
	})
	if err != nil {
		panic(err)
	}

}
Output:
2 [REDACTED]

func (*Scanner) ScanString

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

ScanString scans the bytes of text.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail))

	fmt.Println(len(scanner.ScanString("alice@example.com")))

}
Output:
1

type ScannerOption added in v0.4.0

type ScannerOption interface {
	// contains filtered or unexported methods
}

ScannerOption configures a scanner at construction time.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	options := []embargo.ScannerOption{embargo.WithKinds(embargo.KindEmail), embargo.WithMinConfidence(.9)}

	fmt.Println(len(embargo.NewScanner(options...).ScanString("alice@example.com")))

}
Output:
1

func WithAll

func WithAll() ScannerOption

WithAll selects every built-in, including IP addresses and context-based detectors.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail), embargo.WithAll())

	fmt.Println(len(scanner.ScanString("alice@example.com 192.0.2.1 cvv: 123")))

}
Output:
4

func WithDetector

func WithDetector(d Detector) ScannerOption

WithDetector appends a custom detector independently of the built-in selection. Nil and typed-nil detectors panic.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/nao1215/embargo"
)

type projectToken struct{}

func (projectToken) Scan(data []byte) []embargo.Finding {
	const token = "fake_project_token"
	start := bytes.Index(data, []byte(token))
	if start < 0 {
		return nil
	}
	return []embargo.Finding{{Kind: "project_token", Start: start, End: start + len(token), Confidence: 1}}
}

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(), embargo.WithDetector(projectToken{}))
	text := "token=fake_project_token"

	fmt.Println(embargo.Mask(text, scanner.ScanString(text)))

}
Output:
token=[REDACTED]

func WithKinds added in v0.4.0

func WithKinds(kinds ...Kind) ScannerOption

WithKinds replaces the built-in selection. No kinds selects none; custom detectors remain. Unknown kinds panic. The supplied slice is copied.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindEmail))

	fmt.Println(len(scanner.ScanString("alice@example.com 192.0.2.1")))

}
Output:
1

func WithMinConfidence

func WithMinConfidence(threshold float64) ScannerOption

WithMinConfidence keeps findings at or above threshold; the default is 0. For example, 0.7 excludes PAN checksum failures (0.6) and numeric candidates with attached business labels (0.4), at the risk of missing mislabeled secrets. It also excludes bank-account findings (0.5–0.65) and some sort codes; choose thresholds for the selected kinds. Confidence is a heuristic, not a probability. Non-finite scores or values outside [0,1] panic.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(embargo.KindBankAccount), embargo.WithMinConfidence(.9))

	fmt.Println(len(scanner.ScanString("bank account 12345678")))

}
Output:
0

func WithSensitiveKeys added in v0.4.0

func WithSensitiveKeys(keys ...string) ScannerOption

WithSensitiveKeys replaces the default sensitive key set. No keys disables it. Defaults are password, passwd, secret, token, api_key, authorization, cookie and set-cookie. To extend them, include those names alongside your own keys. Matching ignores ASCII case and the separators underscore, hyphen, dot and space, so apiKey and API-KEY match api_key. Names are copied at construction. A match masks the entire value in slog attributes/groups and encoded JSON objects, including the zap, zerolog and logrus adapters. KindCredential also uses this policy for text assignments; its URL and provider-field rules remain independent. Use MaskJSON to check the complete structured key policy. An empty or separator-only name panics with a fixed message.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(), embargo.WithSensitiveKeys("password", "passwd", "secret", "token", "api_key", "authorization", "cookie", "set-cookie", "recovery_code"))
	safe, err := scanner.MaskJSON([]byte(`{"recoveryCode":"opaque","api-key":"opaque","count":3}`))
	if err != nil {
		panic(err)
	}
	fmt.Println(string(safe))
}
Output:
{"recoveryCode":"[REDACTED]","api-key":"[REDACTED]","count":3}

type Secret added in v0.4.0

type Secret[T any] struct {
	// contains filtered or unexported fields
}

Secret hides a shallow copy of T from supported formatters and serializers. Reveal returns that copy; referenced data remains shared with the caller. A Secret deliberately does not implement error. Its String method masks a direct panic value, but cannot protect revealed values or memory dumps.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	var empty embargo.Secret[string]

	fmt.Println(empty, empty.Reveal() == "")

}
Output:
[REDACTED] true

func NewSecret added in v0.4.0

func NewSecret[T any](v T) Secret[T]

NewSecret wraps v without invoking its methods or copying referenced data.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	key := embargo.NewSecret("fake-key")

	fmt.Println(key)

}
Output:
[REDACTED]

func (Secret[T]) Format added in v0.4.0

func (Secret[T]) Format(state fmt.State, _ rune)

Format writes the marker without examining T, regardless of verb or flags. The fmt package handles %T and %p itself and may expose types or addresses.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	value := embargo.NewSecret("fake-key")

	fmt.Printf("%+#v\n", value)

}
Output:
[REDACTED]

func (Secret[T]) GoString added in v0.4.0

func (Secret[T]) GoString() string

GoString returns the fixed redaction marker.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	value := embargo.NewSecret("fake-key")

	fmt.Println(value.GoString())

}
Output:
[REDACTED]

func (Secret[T]) LogValue added in v0.4.0

func (Secret[T]) LogValue() slog.Value

LogValue returns the marker as a slog string.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	value := embargo.NewSecret("fake-key")

	fmt.Println(value.LogValue().String())

}
Output:
[REDACTED]

func (Secret[T]) MarshalJSON added in v0.4.0

func (Secret[T]) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON string containing the marker.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	value := embargo.NewSecret("fake-key")
	data, err := value.MarshalJSON()
	if err != nil {
		panic(err)
	}

	fmt.Println(string(data))

}
Output:
"[REDACTED]"

func (Secret[T]) MarshalText added in v0.4.0

func (Secret[T]) MarshalText() ([]byte, error)

MarshalText returns the marker as text.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	value := embargo.NewSecret("fake-key")
	data, err := value.MarshalText()
	if err != nil {
		panic(err)
	}

	fmt.Println(string(data))

}
Output:
[REDACTED]

func (Secret[T]) Reveal added in v0.4.0

func (s Secret[T]) Reveal() T

Reveal returns the wrapped value, or T's zero value for a zero Secret.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	key := embargo.NewSecret("fake-key")

	fmt.Println(len(key.Reveal()))

}
Output:
8

func (Secret[T]) String added in v0.4.0

func (Secret[T]) String() string

String returns the fixed redaction marker.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	value := embargo.NewSecret("fake-key")

	fmt.Println(value.String())

}
Output:
[REDACTED]

Directories

Path Synopsis
adapters
grpc module
logrus module
otel module
sentry module
zap module
zerolog module
Package embargotest records application outputs and checks them for a fake secret, configured detector findings and expected content.
Package embargotest records application outputs and checks them for a fake secret, configured detector findings and expected content.
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.
detect
Package detect provides built-in sensitive-data detectors and the Detector extension interface.
Package detect provides built-in sensitive-data detectors and the Detector extension interface.
output
Package output implements the shared JSON boundary for the optional logger adapters.
Package output implements the shared JSON boundary for the optional logger adapters.

Jump to

Keyboard shortcuts

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