embargo

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 27 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 keeps secrets and personal data out of what a Go program writes: logs, error reports, HTTP access logs and traces. It works inside the application, where the value is written, and the root module has no dependencies outside the standard library.

It exists for four jobs:

You need to embargo provides
Keep a known secret, such as an API key, from ever printing Secret, which prints [REDACTED] through fmt, JSON, XML, templates and loggers
Log the structs, errors and JSON you already have A slog handler and MaskJSON that keep keys, types and nesting, plus adapters for other loggers and SDKs
Catch secrets nobody declared, such as a card number inside an error message 38 built-in detectors that check the values: tokens, URL passwords, cards, bank numbers, email, IPs
Prove in CI that no secret reaches the output embargotest, which fails a test when a fake secret appears in stdout, logs, HTTP responses or child processes

Redaction in a log pipeline can still run after it; embargo stops the leak where it is written. See what it misses, its accuracy and speed.

Quick start

Requires Go 1.26.11 or later.

go get github.com/nao1215/embargo@v0.14.0
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]
}

Values that must never print

Wrap the value once; every formatter then sees the marker.

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

fmt.Println(key)

// Output: [REDACTED]

key.Reveal() returns the value when the program really needs it. Tested outputs lists every path checked to print [REDACTED], and Input loads such values from JSON, config files and SQL rows. Secret, Input and your own types

Measured against the other typed wrapper, go-masker v3's Sensitive, on twelve standard output paths: both hide the value on fmt, JSON, XML, templates and slog, and only Secret stays hidden when it sits in an unexported struct field printed with %+v. Output-path table

Mask structs without changing their types

Log the struct you already have. The handler encodes it as slog.JSONHandler would, masks detected values, and hides whole values under keys such as password, token or authorization.

// An existing type: no tags, no embargo field types.
type User struct {
	Name     string
	Email    string
	Password string
}
logger := slog.New(embargo.NewSlogHandler(next, embargo.NewScanner()))

logger.Info("signup", "user", User{Name: "carol", Email: "carol@example.com", Password: "hunter2"})

// Output: {"level":"INFO","msg":"signup","user":{"Name":"carol","Email":"[REDACTED]","Password":"[REDACTED]"}}

next is the handler your logger writes to, before any With or WithGroup: attributes bound to it earlier never pass through embargo, so add them to the logger built on the result. The same rules apply to JSON that never reaches a logger, such as an API response or an audit export:

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}

Numbers and booleans keep their types. WithSensitiveKeys adds key names; WithoutDefaultSensitiveKeys drops the defaults. Structured values and key rules

Loggers and services

Logger Wrap it with Module
log/slog: TextHandler, JSONHandler or any other slog.Handler embargo.NewSlogHandler(next, scanner) root, standard library only
go.uber.org/zap embargozap.NewWriteSyncer(next, scanner) adapters/zap
github.com/rs/zerolog embargozerolog.NewWriter(next, scanner) adapters/zerolog
github.com/sirupsen/logrus embargologrus.NewFormatter(next, scanner) adapters/logrus
net/http server access log embargo.NewHTTPHandler(next, logger, scanner) root, standard library only
gRPC server, unary and stream embargogrpc.NewUnaryServerInterceptor(logger, scanner) adapters/grpc
OpenTelemetry SDK logs and spans embargootel.NewLogExporter(next, scanner) adapters/otel
Sentry events embargosentry.NewBeforeSend(scanner) adapters/sentry
log, fmt and anything else Secret values, or embargo.Mask on the text before writing root
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]"}

Limits: MaskJSON bounds encoded input/output to 1 MiB, nesting to 64 and cumulative detector input to 4 MiB; logger writers include the newline in their 1 MiB limit. Recorder WithMaxBytes bounds retained bytes and WithTimeout bounds child Run time. Input decoding has no size limit; bound its upstream reader. MarshalJSON, LogValue, String and Error run before these byte limits apply, so their time and memory are not bounded; use Secret or a LogValuer returning a bounded value. Details

Every adapter and hook uses the same detectors and key rules as the slog handler. The HTTP and gRPC hooks mask what they log, not the request your service receives or the response it sends. gin, echo and Connect servers are http.Handlers, so NewHTTPHandler wraps them unchanged; a test runs all three. Installation and limits

Access logs usually need the client address. Select kinds without KindIPAddr to keep it while tokens and addresses in the request line are still masked:

scanner := embargo.NewScanner(embargo.WithKinds(
	embargo.KindCredential, embargo.KindServiceToken, embargo.KindJWT, embargo.KindEmail, embargo.KindPAN,
))
line := `203.0.113.7 - - [17/Nov/2026:10:00:00 +0000] "GET /reset?email=alice@example.com&token=sk-proj-Fake0Fake0Fake0Fake0Fake0Fake0 HTTP/1.1" 302 0`
fmt.Println(embargo.Mask(line, scanner.ScanString(line)))
// Output: 203.0.113.7 - - [17/Nov/2026:10:00:00 +0000] "GET /reset?email=[REDACTED]&token=[REDACTED] HTTP/1.1" 302 0

On the same five JSON slog events, go-masker takes 0.97 to 1.21 times the time of embargo given the same email and card rules. With its default scanner, embargo takes 0.34 to 0.59 times the time of pii-shield's default policy. Time per event

Find and mask sensitive text

embargo has 38 built-in detectors (26 run by default). NewScanner() runs the first five groups below except the entropy heuristic. The national IDs and the heuristic are opt-in: name them in WithKinds, or turn on everything with WithAll. 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 Detectors What is detected
Credentials 9 URL and DSN passwords, password= and auth headers, tokens from AWS, GitHub, Slack, OpenAI and others, JWT, PEM keys
Cards 5 Card numbers (Luhn), CVV, expiry, payment tokens, merchant ID
Bank 6 IBAN, SWIFT/BIC, ABA routing, UK sort code, bank account, ACH trace
Crypto 2 Bitcoin and Ethereum addresses
Personal 5 Email, IP address, US and Japanese phone numbers, and My Number, including full-width digits
National IDs 11 Opt-in US, UK, Indian, Brazilian, Chinese, Korean and Canadian identifiers; rules and measured limits
Matching rules and validation for all 38 kinds

The cells excerpt each constant's godoc; follow the Kind link for the full rule and confidence tiers. Default refers to NewScanner() without options.

Kind What it matches How it is checked Default
KindServiceToken covers provider-prefixed secrets and webhook credential paths prefix, alphabet and length checks yield 0.95 without a keyword or remote authentication on
KindHighEntropy looks for unlabeled runs of 32–256 ASCII letters, digits, _, - or + Shannon entropy of at least 4.5 bits per byte and three of lowercase, uppercase, digit and symbol classes yield 0.3 off
KindCredential locates nonempty assignment values, Authorization credentials and URL/DSN passwords delimiter and quoting checks give 0.95, preserving labels, initial auth schemes, usernames and hosts on
KindPAN finds 13–19 digits with Visa, Mastercard, Amex, JCB, Discover, Diners or UnionPay prefixes Luhn plus issuer length scores 1.0 and 0.4 under a record label such as user_id; a failed checksum is not a card, nor … on
KindEmail extracts ASCII local parts using letters, digits and .+-_ before @ and dotted domains using letters, digits and .- … structure checks score 0.7 or 0.8 for an unknown TLD and 0.9 or 1.0 for a known TLD on
KindJPPhone recognizes 10- or 11-digit Japanese numbers beginning with 0 or written as +81 without the leading 0, allowing … prefix/length checks score landlines 0.8, other accepted types 0.9, and 0.4 under a record label such as user_id on
KindUSPhone recognizes separated ten-digit North American numbers such as (202) 555-0123 or 202.555.0123, with an optional +1 or … numbering-plan and matching-separator checks score 0.7, 0.9 after a phone, tel, mobile, cell, fax, call or contact … on
KindMyNumber recognizes 12 digits with optional spaces or hyphens as Japanese individual-number candidates the weighted MOD 11 check gives 0.95 without requiring a keyword; a contiguous 12-digit account field of a syntactic … on
KindJWT parses eyJ-prefixed base64url text with exactly two dots and nonempty header and payload segments header checks yield 0.5, 0.7 or 0.8 with an empty signature, and 0.7, 0.9 or 1.0 otherwise on
KindAWSKey identifies AKIA (long-term), ASIA (temporary), ABIA (STS service bearer) or ACCA (context-specific) followed by … length, alphabet and alphanumeric boundary checks give 0.95 without a context keyword or authentication on
KindIBAN accepts two ASCII country letters, two digits and an alphanumeric BBAN with optional internal spaces country length and MOD 97 checks give 0.95, rejecting check digits 00, 01 and 99 without requiring a keyword on
KindIPAddr extracts dotted IPv4 decimal octets and colon-separated IPv6 hexadecimal text, including :: shorthand net.ParseIP validation gives 0.8, excluding IPv4 addresses whose first octet is zero (the this-network block, which … on
KindSWIFTBIC accepts 8 or 11 ASCII alphanumerics as four bank letters, two country letters, location and optional branch country and structure checks give 0.85, with case ignored and no institution lookup on
KindABARouting selects 9 consecutive digits beginning 01–12, 21–32, 61–72 or 80 as US routing candidates the repeating 3,7,1 weighted MOD 10 checksum must pass, giving 0.85 without a keyword; a record identifier label such … on
KindUKSortCode picks six digits in three pairs separated consistently by hyphens or spaces with matching separators, excluding … structure checks give 0.7, or 0.55 for contextual date-like candidates, without a checksum on
KindCVV finds 3 or 4 consecutive digits within 30 bytes of a verification-code keyword end length and non-overlap checks yield 0.85 without a checksum on
KindCardExpiry reads MM/YY, MM/YYYY, MM-YY or MM-YYYY near expiration labels month 01–12 and adjacent-digit checks yield 0.85, without checking whether the date is in the future on
KindPaymentToken covers Stripe identifiers and keys, PayPal PAYID- and Square sq0idp-/sq0csp- tokens prefix and minimum-body checks yield 0.9 with no keyword or authentication on
KindBankAccount looks for 4–17 consecutive digits within 50 bytes of a banking keyword end length checks give 0.5, raised to 0.65 by nearby holder context, without a checksum on
KindACHTrace takes 15 consecutive digits within 50 bytes of an ACH or trace keyword end prefix validation requires 01–12, 21–32, 61–72 or 80 and scores 0.75 without a checksum on
KindMerchantID finds 15 ASCII alphanumerics for merchant IDs or 8 consecutive digits at alphanumeric boundaries for terminal IDs length and keyword-overlap checks give 0.7 without checksum validation on
KindBTC recognizes mainnet 1/3 Base58 text of 25–34 characters or single-case bc1 text of 42 or 62 characters Base58Check or Bech32/Bech32m checksum validation gives 0.95 without a keyword on
KindETH captures 0x or 0X followed by exactly 40 hexadecimal characters at identifier boundaries uniform-case hex scores 0.8 without checksum validation, while mixed case must pass EIP-55 (Keccak-256) for 0.95 … on
KindGitHubToken distinguishes classic ghp_/gho_/ghu_/ghs_/ghr_ tokens from github_pat_ tokens body-length and token-boundary checks yield 0.95 without a keyword or authentication on
KindSlackToken recognizes xoxb-, xoxp-, xoxa-, xoxo-, xoxr-, xoxs- and xoxe- followed by ASCII letters, digits or hyphens a body of at least 10 characters and token-boundary checks yield 0.9, with no context keyword or authentication on
KindGoogleAPIKey looks for AIza followed by exactly 35 ASCII letters, digits, hyphens or underscores the 39-character length and token-boundary checks give 0.9 without a keyword or authentication on
KindPrivateKeyPEM covers -----BEGIN headers whose same-line content ends in PRIVATE KEY or equals PGP PRIVATE KEY BLOCK, closed by five … header grammar alone gives 0.99 without a keyword or key-material validation on
KindUSSSN recognizes 9 digits, either contiguous or grouped 3-2-4 with hyphens field checks yield 0.6, none under a record label such as order_id; a hyphenated value needs no keyword or checksum … off
KindUSITIN finds 9 digits starting with 9, optionally hyphenated 3-2-4 middle-group validation gives 0.6, none under a record label such as order_id; a hyphenated value needs no keyword or … off
KindUKNINO accepts two uppercase ASCII letters, six digits and a suffix A–D, optionally spaced into groups of 2 letters, 2/2/2 … prefix checks score 0.7, none under a record label such as order_id, without requiring context or a checksum off
KindUKNHS collects 10 digits, contiguous or spaced 3-3-4 weighted MOD 11 validation yields 0.95, none under a record label such as order_id; a spaced value needs no keyword … off
KindIndiaAadhaar accepts 12 digits beginning 2–9, contiguous or spaced 4-4-4 Verhoeff checksum validation gives 0.95, none under a record label such as order_id; a spaced value needs no keyword … off
KindIndiaPAN recognizes five uppercase ASCII letters, four digits and one final uppercase letter holder-type and nonzero-serial checks score 0.7, none under a record label such as order_id, with no keyword or checksum off
KindBrazilCPF takes 11 digits, contiguous or formatted DDD.DDD.DDD-DD both MOD 11 check digits must pass for 0.95, none under a record label such as order_id, without a keyword off
KindBrazilCNPJ admits 12 uppercase ASCII alphanumerics and two digits, contiguous or formatted CC.CCC.CCC/CCCC-DD two MOD 11 checks give 0.95, none under a record label such as order_id, without requiring a keyword off
KindChinaResidentID requires 17 digits followed by a digit or uppercase X, including a YYYYMMDD birth date province, date, sequence and MOD 11-2 checks yield 0.95, none under a record label such as order_id, with no keyword off
KindKoreaRRN reads 13 digits, contiguous or hyphenated 6-7, with a birth date and century/sex digit the legacy weighted MOD 11 check scores 0.95, labeled check failures 0.6, and none under a record label such as order_id off
KindCanadaSIN finds 9 digits starting with 1–7 or 9, contiguous or hyphenated 3-3-3 Luhn checksum validation yields 0.95, none under a record label such as order_id; a hyphenated value needs no … off

Every detector and how it validates · Provider token formats

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.ScanLines reads files and streams line by line. Scanner options and custom replacements

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

Fail tests on leaks

Add one line to a package's tests:

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. The canary is matched as raw bytes, hex, standard or URL-safe base64 at any byte alignment, and standard Go/JSON-escaped forms, so that check does not depend on the detectors. It also searches the output once more after one layer of JSON backslash-u and percent escapes is decoded; MIME-wrapped base64 requires decoding before recording. ExampleGuard

For one test, build the logger the way the service does and let a recorder check both that the expected output exists and that no canary escaped. Attributes bound after wrapping pass through embargo; ones bound to next, or added by handlers after it, do not, and this test fails when the wiring lets the canary through:

func TestReadmeCheckOutput(t *testing.T) {
    t.Parallel()
    recorder := embargotest.New(t)
    next := slog.NewJSONHandler(recorder.Writer("logs"), nil)
    // Wrap next first; attributes bound with next.WithAttrs would skip embargo.
    logger := slog.New(embargo.NewSlogHandler(next, embargo.NewScanner())).With("api_token", string(recorder.Canary()))

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

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

Keep your masking, add the leak test shows how to add only embargotest to existing masking. 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

Command line

The embargo command masks a log file or a pipe line by line, keeps JSON lines' shape and depends only on the standard library.

go install github.com/nao1215/embargo/cmd/embargo@v0.14.0
kubectl logs deploy/api | embargo
embargo --format json app.log
embargo --format jsonl app.log
$ printf '%s\n' 'login failed for alice@example.com from 203.0.113.7' | embargo
login failed for [REDACTED] from [REDACTED]

The masked lines are what you paste into a ticket or hand to an LLM. --format json prints per-kind counts with a few locations, and --format jsonl prints one line per finding with its line, column and kind; neither prints a matched value. Because jsonl prints nothing for a clean log, out=$(embargo --format jsonl app.log) && test -z "$out" fails a CI step on a finding and on an unreadable input alike; the exit status alone only says whether embargo ran. Flags, limits and comparing settings

Tested outputs

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

Output Actual output (excerpt for SDKs)
fmt embargo.Secret[string]([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

Audit your own logs: count findings by Kind, inspect masked offsets and test settings that preserve diagnostic IDs.

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

Per-detector precision, recall and charts.

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 phone_us private_key_pem
slack_token swiftbic uk_sortcode

Public-log chart and measured results.

15 public datasets, 239.9 MB, 1,048,835 lines: LogHub system logs plus web access, Kubernetes audit and CloudTrail logs. Licenses, classification rules, per-kind and per-configuration FP/GB. Rates are sample estimates on previously seen splits; contact and endpoint references count as sensitive data, and no recall claim is made.

Testing

Technique Bug class caught here
Examples and unit tests Wrong public outputs
Generated properties Missing checksum combinations
Metamorphic relations Inconsistent transformed findings
Quint and model replay Invalid lifecycle transitions
Lean reference proofs Arithmetic and interval errors
Intentional snapshots Changed output structure
Independent differential oracles Shared oracle mistakes
Structure-aware fuzzing Malformed nested inputs
Mutation testing Assertions missing changed logic
Real logger and SDK output Serializer and SDK leaks
Race and lifecycle tests Races and hanging pipes
Paired CI benchmarks Runner noise hiding regressions
Prose and policy checks Stale docs and rules
Adversarial budgets Resource amplification and spoofing

Coverage 99.4% · mutation score 89.18% · 13 fuzz targets, 2208636 executions.

Commands, measurement scope and conditions.

Benchmarks

Time per log event

The same event through slog alone, embargo with the email and card rules masq and go-masker are given, embargo's default scanner against pii-shield's default policy, masq and go-masker. Configurations, medians and allocations · Full scanner benchmark plot.

Recorded scanner medians (ten interleaved samples):

Selection Clean ns/op Dirty ns/op Clean / dirty speedup over WithAll
all 64,763 6,837,398 1.00× / 1.00×
kinds1 101 22,310 641.22× / 306.47×
kinds3 8,648 496,620 7.49× / 13.77×
kinds8 10,174 1,541,042 6.37× / 4.44×

kinds1/3/8 definitions, input sizes and uncertainty. Narrower selection avoids irrelevant detections and gives up their recall.

Machine, method, profiles and full results.

Compared with other Go libraries

The same scenarios, service probe and log events run against pii-shield, ferret-scan, masq, go-masker, slog-formatter, go-mask and godlp, and the typed-wrapper paths against ggwhite/go-masker v3. A catch means the original planted value was removed; partial masks count. These configured examples are not a production accuracy estimate.

Job Strongest measured option Where others win or tie
Keep a known secret from printing embargo Secret, hidden on every tested path including unexported fields ggwhite/go-masker v3 Sensitive ties on fmt, JSON, XML and slog (table)
Log existing structs and JSON with their shape embargo: keys, groups and custom JSON output are scanned as structure pii-shield and ferret-scan rewrite any logger's encoded line
Catch values nobody declared embargo removes the most planted values below and, with pii-shield, every logged service leak Tag-only values: masq, go-masker and go-mask catch the one embargo misses
Prove in CI that nothing leaked embargo embargotest, with canaries in logs, responses and child processes None of the measured libraries; embargotest works with any of them

Scenario catch rate

pii-shield also runs as a Kubernetes sidecar outside the process, and ferret-scan scans documents and images; embargo stays inside the Go process where the value is written. Its default scanner keeps the invalid-Luhn control visible, because a number that fails the Luhn check is not an issued card; masq masks it. Exact outputs, setup, runtime dependencies and speed document the strengths and limits of every configuration.

The service probe below also checks a redirect that bypasses every logger. embargotest.HTTP catches that response leak:

Service output embargo slog embargo zap pii-shield v3.0.0 ferret-scan v2.4.3 masq v0.2.3 slog-formatter v1.3.0 go-mask v0.6.2 go-masker v0.6.1 godlp v1.2.15
Password under the key password caught caught caught caught caught caught caught caught leaked
Config struct holding a database DSN caught caught caught leaked caught leaked leaked caught leaked
DSN inside a wrapped error caught caught caught leaked caught leaked leaked caught leaked
DSN and an API key joined with errors.Join caught caught caught leaked leaked leaked leaked caught leaked
Bearer header value in a log message caught caught caught leaked leaked leaked leaked caught leaked
Third-party API key in a log message caught caught caught leaked leaked leaked leaked leaked leaked
Redirect URL query, never logged leaked leaked leaked leaked leaked leaked leaked leaked leaked

Service setup and full results.

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.

Artwork details and license terms are in image attribution.

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 omit unlabelled entropy tokens; WithAll includes them. 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. Masking text twice may mask more, so mask each original value once; the marker is not a trusted-input bypass.

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 NewHTTPHandler added in v0.5.0

func NewHTTPHandler(next http.Handler, logger *slog.Logger, scanner *Scanner) http.Handler

NewHTTPHandler writes one masked access record to logger after next handles each request. Authorization, Proxy-Authorization, Cookie and Set-Cookie values are always hidden, other header and query keys follow WithSensitiveKeys, and bodies are not logged; requests and responses pass through unchanged. All arguments are required. If masking fails, the record keeps only time, level, status, duration and a fixed reason. The logging guide covers contexts, panics and the failure record.

Example
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

	"github.com/nao1215/embargo"
)

func main() {
	var logs bytes.Buffer
	logger := slog.New(slog.NewJSONHandler(&logs, nil))
	next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
	handler := embargo.NewHTTPHandler(next, logger, embargo.NewScanner())
	request := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/profile?email=alice@example.com", http.NoBody)
	response := httptest.NewRecorder()
	handler.ServeHTTP(response, request)
	var event struct {
		Target string `json:"target"`
	}
	if err := json.Unmarshal(logs.Bytes(), &event); err != nil {
		panic(err)
	}
	fmt.Println(response.Code)
	fmt.Println(event.Target)
}
Output:
204
/profile?email=[REDACTED]

func NewSlogHandler added in v0.4.0

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

NewSlogHandler masks messages, keys, groups and values with scanner before forwarding records to next. Any values keep their JSON shape and clean scalars keep their types. Each encoded value is limited to 1 MiB and nesting depth 64. Both arguments must be non-nil; nil panics.

A record that cannot be masked is replaced by one with the same time and level, a fixed message and a withheld_attributes count; no original field survives. See the logging guide for value handling and error observation.

Pass the sink handler before any attributes are bound to it, and call With and WithGroup on the logger built from the result. Attributes already bound with next.WithAttrs or next.WithGroup, and fields next adds itself, never pass through embargo: they are written unmasked, also beside a withheld diagnostic.

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]"}
Example (Struct)
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

	// An existing type: no tags, no embargo field types.
	type User struct {
		Name     string
		Email    string
		Password string
	}
	logger := slog.New(embargo.NewSlogHandler(next, embargo.NewScanner()))

	logger.Info("signup", "user", User{Name: "carol", Email: "carol@example.com", Password: "hunter2"})
	// README:end

}
Output:
{"level":"INFO","msg":"signup","user":{"Name":"carol","Email":"[REDACTED]","Password":"[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 is a DTO field that decodes JSON, text or SQL into a Secret; call Secret after decoding. Do not decode or display the same Input concurrently. 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, _ 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. This method has no input size bound; limit the upstream reader before decoding the enclosing document.

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.

Each built-in constant states what it matches, how it is checked, its scores and whether NewScanner enables it; WithKinds and WithAll change that selection.

The label right before a candidate is read in this order. A key that names a secret, such as password, hides its value through KindCredential whatever the other kinds decide, because Mask merges overlapping findings. A record label, such as order_id, user_id or 注文番号, names a record rather than the number: it rules out My Number, ABA routing and country candidates unless a word naming the number, such as ssn or routing, is also there. A remaining candidate must pass its shape and check digits, and a bare digit run of an SSN, ITIN, SIN, NHS number or Aadhaar also needs a label naming it. Confidence comes last: a record label lowers a payment card or phone number to 0.4 instead of ruling it out, and WithMinConfidence drops what falls below its threshold. Scan also reads full-width digits, Unicode dashes and one layer of percent-encoding; the detector rules give the exact normalization. A match does not establish that an account, credential or identity exists.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

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

	fmt.Println(kind)

}
Output:
project_token
const (
	// KindServiceToken covers provider-prefixed secrets and webhook credential paths; prefix, alphabet and length checks yield 0.95 without a keyword or remote authentication. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindservicetoken (NewScanner default: on).
	KindServiceToken Kind = "service_token"
	// KindHighEntropy looks for unlabeled runs of 32–256 ASCII letters, digits, _, - or +; Shannon entropy of at least 4.5 bits per byte and three of lowercase, uppercase, digit and symbol classes yield 0.3. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindhighentropy (NewScanner default: off).
	KindHighEntropy Kind = "high_entropy"
	// KindCredential locates nonempty assignment values, Authorization credentials and URL/DSN passwords; delimiter and quoting checks give 0.95, preserving labels, initial auth schemes, usernames and hosts. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindcredential (NewScanner default: on).
	KindCredential Kind = "credential"
	// KindPAN finds 13–19 digits with Visa, Mastercard, Amex, JCB, Discover, Diners or UnionPay prefixes; Luhn plus issuer length scores 1.0 and 0.4 under a record label such as user_id; a failed checksum is not a card, nor is a 13-digit number that also passes the EAN-13 check, such as a JAN product code. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindpan (NewScanner default: on).
	KindPAN Kind = "pan"
	// KindEmail extracts ASCII local parts using letters, digits and .+-_ before @ and dotted domains using letters, digits and .-, also in full-width letters around the full-width @; structure checks score 0.7 or 0.8 for an unknown TLD and 0.9 or 1.0 for a known TLD. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindemail (NewScanner default: on).
	KindEmail Kind = "email"
	// KindJPPhone recognizes 10- or 11-digit Japanese numbers beginning with 0 or written as +81 without the leading 0, allowing spaces, hyphens and parentheses; prefix/length checks score landlines 0.8, other accepted types 0.9, and 0.4 under a record label such as user_id. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindjpphone (NewScanner default: on).
	KindJPPhone Kind = "phone_jp"
	// KindUSPhone recognizes separated ten-digit North American numbers such as (202) 555-0123 or 202.555.0123, with an optional +1 or 1 country code; numbering-plan and matching-separator checks score 0.7, 0.9 after a phone, tel, mobile, cell, fax, call or contact label, and 0.4 under a record label such as user_id. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindusphone (NewScanner default: on).
	KindUSPhone Kind = "phone_us"
	// KindMyNumber recognizes 12 digits with optional spaces or hyphens as Japanese individual-number candidates; the weighted MOD 11 check gives 0.95 without requiring a keyword; a contiguous 12-digit account field of a syntactic ARN with an AWS partition and a value labeled as a record identifier, such as accountId, user_id, account, tracking or 注文番号, are excluded, while a My Number or 個人番号 label keeps it. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindmynumber (NewScanner default: on).
	KindMyNumber Kind = "mynumber"
	// KindJWT parses eyJ-prefixed base64url text with exactly two dots and nonempty header and payload segments; header checks yield 0.5, 0.7 or 0.8 with an empty signature, and 0.7, 0.9 or 1.0 otherwise. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindjwt (NewScanner default: on).
	KindJWT Kind = "jwt"
	// KindAWSKey identifies AKIA (long-term), ASIA (temporary), ABIA (STS service bearer) or ACCA (context-specific) followed by exactly 16 uppercase ASCII letters or digits (20 characters total); length, alphabet and alphanumeric boundary checks give 0.95 without a context keyword or authentication (NewScanner default: on).
	KindAWSKey Kind = "awskey"
	// KindIBAN accepts two ASCII country letters, two digits and an alphanumeric BBAN with optional internal spaces; country length and MOD 97 checks give 0.95, rejecting check digits 00, 01 and 99 without requiring a keyword. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindiban (NewScanner default: on).
	KindIBAN Kind = "iban"
	// KindIPAddr extracts dotted IPv4 decimal octets and colon-separated IPv6 hexadecimal text, including :: shorthand; net.ParseIP validation gives 0.8, excluding IPv4 addresses whose first octet is zero (the this-network block, which contains the unspecified address), the IPv6 unspecified address and loopback addresses with no keyword needed; version labels and product/version tokens such as agent/5.1.2.3 exclude IPv4 candidates. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindipaddr (NewScanner default: on).
	KindIPAddr Kind = "ipaddr"
	// KindSWIFTBIC accepts 8 or 11 ASCII alphanumerics as four bank letters, two country letters, location and optional branch; country and structure checks give 0.85, with case ignored and no institution lookup. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindswiftbic (NewScanner default: on).
	KindSWIFTBIC Kind = "swiftbic"
	// KindABARouting selects 9 consecutive digits beginning 01–12, 21–32, 61–72 or 80 as US routing candidates; the repeating 3,7,1 weighted MOD 10 checksum must pass, giving 0.85 without a keyword; a record identifier label such as user_id excludes the candidate unless a routing label precedes. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindabarouting (NewScanner default: on).
	KindABARouting Kind = "aba_routing"
	// KindUKSortCode picks six digits in three pairs separated consistently by hyphens or spaces with matching separators, excluding all-zero codes; structure checks give 0.7, or 0.55 for contextual date-like candidates, without a checksum. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kinduksortcode (NewScanner default: on).
	KindUKSortCode Kind = "uk_sortcode"
	// KindCVV finds 3 or 4 consecutive digits within 30 bytes of a verification-code keyword end; length and non-overlap checks yield 0.85 without a checksum. The required keywords are cvv, cvc, cid, cvv2, cvc2, security code or セキュリティコード, with ASCII case ignored (NewScanner default: on).
	KindCVV Kind = "cvv"
	// KindCardExpiry reads MM/YY, MM/YYYY, MM-YY or MM-YYYY near expiration labels; month 01–12 and adjacent-digit checks yield 0.85, without checking whether the date is in the future. Search starts within 50 bytes before or after the required case-insensitive keyword exp, exp date, expiry, expires, expiration, expiration date, valid thru, valid through or 有効期限 (NewScanner default: on).
	KindCardExpiry Kind = "card_expiry"
	// KindPaymentToken covers Stripe identifiers and keys, PayPal PAYID- and Square sq0idp-/sq0csp- tokens; prefix and minimum-body checks yield 0.9 with no keyword or authentication. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindpaymenttoken (NewScanner default: on).
	KindPaymentToken Kind = "payment_token"
	// KindBankAccount looks for 4–17 consecutive digits within 50 bytes of a banking keyword end; length checks give 0.5, raised to 0.65 by nearby holder context, without a checksum. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindbankaccount (NewScanner default: on).
	KindBankAccount Kind = "bank_account"
	// KindACHTrace takes 15 consecutive digits within 50 bytes of an ACH or trace keyword end; prefix validation requires 01–12, 21–32, 61–72 or 80 and scores 0.75 without a checksum. Context is mandatory: ach, ach trace, trace number, trace no, trace # or trace# with ASCII case ignored (NewScanner default: on).
	KindACHTrace Kind = "ach_trace"
	// KindMerchantID finds 15 ASCII alphanumerics for merchant IDs or 8 consecutive digits at alphanumeric boundaries for terminal IDs; length and keyword-overlap checks give 0.7 without checksum validation. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindmerchantid (NewScanner default: on).
	KindMerchantID Kind = "merchant_id"
	// KindBTC recognizes mainnet 1/3 Base58 text of 25–34 characters or single-case bc1 text of 42 or 62 characters; Base58Check or Bech32/Bech32m checksum validation gives 0.95 without a keyword. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindbtc (NewScanner default: on).
	KindBTC Kind = "btc"
	// KindETH captures 0x or 0X followed by exactly 40 hexadecimal characters at identifier boundaries; uniform-case hex scores 0.8 without checksum validation, while mixed case must pass EIP-55 (Keccak-256) for 0.95, with no context keyword required (NewScanner default: on).
	KindETH Kind = "eth"
	// KindGitHubToken distinguishes classic ghp_/gho_/ghu_/ghs_/ghr_ tokens from github_pat_ tokens; body-length and token-boundary checks yield 0.95 without a keyword or authentication. Classic bodies require exactly 36 ASCII letters/digits; fine-grained bodies require at least 22 ASCII letters/digits/underscores (NewScanner default: on).
	KindGitHubToken Kind = "github_token"
	// KindSlackToken recognizes xoxb-, xoxp-, xoxa-, xoxo-, xoxr-, xoxs- and xoxe- followed by ASCII letters, digits or hyphens; a body of at least 10 characters and token-boundary checks yield 0.9, with no context keyword or authentication (NewScanner default: on).
	KindSlackToken Kind = "slack_token"
	// KindGoogleAPIKey looks for AIza followed by exactly 35 ASCII letters, digits, hyphens or underscores; the 39-character length and token-boundary checks give 0.9 without a keyword or authentication (NewScanner default: on).
	KindGoogleAPIKey Kind = "google_api_key"
	// KindPrivateKeyPEM covers -----BEGIN headers whose same-line content ends in PRIVATE KEY or equals PGP PRIVATE KEY BLOCK, closed by five hyphens; header grammar alone gives 0.99 without a keyword or key-material validation. Any algorithm text is accepted; the span extends through an identical -----END label when present, otherwise the span extends to end of input (NewScanner default: on).
	KindPrivateKeyPEM Kind = "private_key_pem"
)
const (
	// KindUSSSN recognizes 9 digits, either contiguous or grouped 3-2-4 with hyphens; field checks yield 0.6, none under a record label such as order_id; a hyphenated value needs no keyword or checksum, a bare one a label such as ssn or social security number. Area 000, 666 and 900–999, group 00 and serial 0000 are rejected (NewScanner default: off).
	KindUSSSN Kind = "us_ssn"
	// KindUSITIN finds 9 digits starting with 9, optionally hyphenated 3-2-4; middle-group validation gives 0.6, none under a record label such as order_id; a hyphenated value needs no keyword or checksum, a bare one a label such as itin or taxpayer. The fourth/fifth digits must be 50–65, 70–88, 90–92 or 94–99 (NewScanner default: off).
	KindUSITIN Kind = "us_itin"
	// KindUKNINO accepts two uppercase ASCII letters, six digits and a suffix A–D, optionally spaced into groups of 2 letters, 2/2/2 digits and 1 letter; prefix checks score 0.7, none under a record label such as order_id, without requiring context or a checksum. Both prefix letters exclude D/F/I/Q/U/V, the second also excludes O, and BG/GB/KN/NK/NT/TN/ZZ are forbidden (NewScanner default: off).
	KindUKNINO Kind = "uk_nino"
	// KindUKNHS collects 10 digits, contiguous or spaced 3-3-4; weighted MOD 11 validation yields 0.95, none under a record label such as order_id; a spaced value needs no keyword, a bare one a label such as nhs. The first 9 digits use weights 10 down to 2, a check value of 10 is rejected, and repeated single-digit values are excluded (NewScanner default: off).
	KindUKNHS Kind = "uk_nhs"
	// KindIndiaAadhaar accepts 12 digits beginning 2–9, contiguous or spaced 4-4-4; Verhoeff checksum validation gives 0.95, none under a record label such as order_id; a spaced value needs no keyword, a bare one a label such as aadhaar. Repeated single-digit values are rejected (NewScanner default: off).
	KindIndiaAadhaar Kind = "in_aadhaar"
	// KindIndiaPAN recognizes five uppercase ASCII letters, four digits and one final uppercase letter; holder-type and nonzero-serial checks score 0.7, none under a record label such as order_id, with no keyword or checksum. The fourth letter must be P/C/H/A/B/G/J/L/F/T and the four digits cannot be 0000 (NewScanner default: off).
	KindIndiaPAN Kind = "in_pan"
	// KindBrazilCPF takes 11 digits, contiguous or formatted DDD.DDD.DDD-DD; both MOD 11 check digits must pass for 0.95, none under a record label such as order_id, without a keyword. Repeated digits are rejected; the first check weights the initial 9 digits from 10 down to 2 and the second weights the first 10 from 11 down to 2 (NewScanner default: off).
	KindBrazilCPF Kind = "br_cpf"
	// KindBrazilCNPJ admits 12 uppercase ASCII alphanumerics and two digits, contiguous or formatted CC.CCC.CCC/CCCC-DD; two MOD 11 checks give 0.95, none under a record label such as order_id, without requiring a keyword. Character values are ASCII minus 48, right-to-left weights cycle 2–9, and repeated single-character values are rejected (NewScanner default: off).
	KindBrazilCNPJ Kind = "br_cnpj"
	// KindChinaResidentID requires 17 digits followed by a digit or uppercase X, including a YYYYMMDD birth date; province, date, sequence and MOD 11-2 checks yield 0.95, none under a record label such as order_id, with no keyword. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindchinaresidentid (NewScanner default: off).
	KindChinaResidentID Kind = "cn_resident_id"
	// KindKoreaRRN reads 13 digits, contiguous or hyphenated 6-7, with a birth date and century/sex digit; the legacy weighted MOD 11 check scores 0.95, labeled check failures 0.6, and none under a record label such as order_id. Full rules: https://github.com/nao1215/embargo/blob/main/doc/detectors.md#kindkorearrn (NewScanner default: off).
	KindKoreaRRN Kind = "kr_rrn"
	// KindCanadaSIN finds 9 digits starting with 1–7 or 9, contiguous or hyphenated 3-3-3; Luhn checksum validation yields 0.95, none under a record label such as order_id; a hyphenated value needs no keyword, a bare one a label such as sin or social insurance number. Repeated single-digit values are excluded (NewScanner default: off).
	KindCanadaSIN Kind = "ca_sin"
)

type Scanner

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

Scanner holds immutable scan policy. Its zero value uses the same selection as NewScanner. 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 starts with 26 built-ins; the additional country families and KindHighEntropy are opt-in. WithAll enables all 38 families; WithKinds selects the regions and formats an application handles. Minimum confidence defaults to 0, so ambiguous numeric and contextual candidates remain. Select WithKinds when the application knows which data it handles; fewer detectors reduce work and unrelated findings. See https://github.com/nao1215/embargo/blob/main/doc/benchmarks.md for measured kind sets. 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 (s *Scanner) MaskJSON(data []byte) ([]byte, error)

MaskJSON returns a compact copy of one JSON document with sensitive values masked, keeping object order, duplicate keys, types and clean numbers exactly; a value under a sensitive key becomes a marker, and a sensitive number becomes a marker string. Input and output are limited to 1 MiB and nesting to 64. Invalid input or an exceeded limit returns no bytes and a fixed error that contains no input data. Use it before sending JSON API responses, exports or audit records; the logging guide describes the remaining bounds.

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) MaskJSONContext added in v0.5.1

func (s *Scanner) MaskJSONContext(ctx context.Context, data []byte) ([]byte, error)

MaskJSONContext applies MaskJSON's policy while checking ctx before and between scalar scans. A canceled or nil context returns no bytes and a fixed error, which errors.Is matches with the context's error, such as context.Canceled. An already running detector cannot be interrupted. Use it for request-scoped or telemetry work that should stop after cancellation.

Example
package main

import (
	"context"
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	safe, err := embargo.NewScanner().MaskJSONContext(ctx, []byte(`{"email":"alice@example.com"}`))
	fmt.Println(len(safe), err != nil)
}
Output:
0 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); KindCredential keeps original URL/DSN delimiters and also scans normalized assignments. Literal + and invalid escapes are preserved; offsets always refer to original bytes. KindCredential also scans up to four Go/JSON quote and backslash escape layers, including hexadecimal and Unicode quote escapes. 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. A selected PEM finding carries through its matching END line or end of input; subsequent key-material lines receive line-relative PEM findings.

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 enables national identifiers from every supported country and unlabelled entropy candidates. WithKinds avoids scanning for formats the application never handles and usually costs less. Measurements and the recall tradeoff are in https://github.com/nao1215/embargo/blob/main/doc/benchmarks.md.

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. An unknown kind panics; the message quotes it and suggests the nearest built-in only when it is a likely misspelling, within two edits of one. 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
Example (AccessLog)

Access logs usually need the client address for incident response. Leaving KindIPAddr out of the selection keeps it while credentials, provider tokens, email addresses and cards in the request line are still masked.

package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	scanner := embargo.NewScanner(embargo.WithKinds(
		embargo.KindCredential, embargo.KindServiceToken, embargo.KindJWT, embargo.KindEmail, embargo.KindPAN,
	))
	line := `203.0.113.7 - - [17/Nov/2026:10:00:00 +0000] "GET /reset?email=alice@example.com&token=sk-proj-Fake0Fake0Fake0Fake0Fake0Fake0 HTTP/1.1" 302 0`
	fmt.Println(embargo.Mask(line, scanner.ScanString(line)))
}
Output:
203.0.113.7 - - [17/Nov/2026:10:00:00 +0000] "GET /reset?email=[REDACTED]&token=[REDACTED] HTTP/1.1" 302 0

func WithMinConfidence

func WithMinConfidence(threshold float64) ScannerOption

WithMinConfidence keeps findings at or above threshold; the default is 0. For example, 0.7 excludes PAN and phone candidates under a record label such as user_id (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 adds names to the sensitive key policy; repeated options add to each other and the defaults stay. Defaults are password, passwd, secret, token, api_key, authorization, proxy-authorization, cookie, set-cookie, access_token, refresh_token, id_token, x-api-key, DB_PASSWORD, Private-Token, client_secret, auth_token, PGPASSWORD, otp, pin, passcode, passphrase, session, session_id, session_token, JSESSIONID and PHPSESSID; structured keys also accept the bare pass and pwd, which text assignments leave alone because pass=12 and PWD=/srv are common public text. Keys also match when the last separator/camel-case segment is password, passwd, pwd, passcode, passphrase, otp, secret, token, credential or auth, or pass after another segment (DB_PASS); key requires an api, secret, private, access, account, auth or master segment before it. Thus SECRET_KEY, POSTGRES_PASSWORD, GITHUB_TOKEN, X-Auth-Token and spring.datasource.password match, but primary_key, sort_key and token_count do not. WithoutDefaultSensitiveKeys drops the defaults and this suffix rule. 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. An object that keeps a setting as separate members, such as {"name":"DB_PASSWORD","value":"x"} in Kubernetes env, ECS, SSM or CloudFormation, has its value string masked when the name, key, ParameterKey, ParameterName, OptionName or variable member is a sensitive key; the last segment of a parameter path such as /prod/db/password counts. 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("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}

func WithoutDefaultSensitiveKeys added in v0.14.0

func WithoutDefaultSensitiveKeys() ScannerOption

WithoutDefaultSensitiveKeys drops the default names and the suffix rule, so only names added with WithSensitiveKeys mask whole values; with none, the key policy is off. Use it when a default name such as token holds public data, and add back the names that do hold secrets.

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

func main() {
	// This API returns a public pagination cursor named token.
	scanner := embargo.NewScanner(embargo.WithKinds(), embargo.WithoutDefaultSensitiveKeys(), embargo.WithSensitiveKeys("password"))
	safe, err := scanner.MaskJSON([]byte(`{"token":"page-2","password":"opaque"}`))
	if err != nil {
		panic(err)
	}
	fmt.Println(string(safe))
}
Output:
{"token":"page-2","password":"[REDACTED]"}

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. The value lives inside a closure, so reflection-based printers that skip methods, such as go-spew and the diffs of testify and go-cmp, reach only a function value.

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 (s Secret[T]) Format(state fmt.State, verb rune)

Format writes the marker without examining T. The %#v form also names its type. 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:
embargo.Secret[string]([REDACTED])

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

func (s Secret[T]) GoString() string

GoString includes the instantiated type, for example embargo.Secret[string]([REDACTED]).

Example
package main

import (
	"fmt"

	"github.com/nao1215/embargo"
)

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

	fmt.Println(value.GoString())

}
Output:
embargo.Secret[string]([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 writes a JSON marker string; persisting it discards the wrapped value.

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 encodes only the marker, so this representation cannot restore the value.

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
cmd
embargo command
Command embargo masks secrets and personal data in log lines read from files or stdin and writes them to stdout; --format json and --format jsonl report finding counts and locations instead, without echoing input.
Command embargo masks secrets and personal data in log lines read from files or stdin and writes them to stdout; --format json and --format jsonl report finding counts and locations instead, without echoing input.
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.
saferecord
Package saferecord builds diagnostic records without retaining application data.
Package saferecord builds diagnostic records without retaining application data.

Jump to

Keyboard shortcuts

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