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 ¶
- func Mask(text string, findings []Finding) string
- func MaskFunc(text string, findings []Finding, replace func(kind Kind, value string) string) string
- func NewHTTPHandler(next http.Handler, logger *slog.Logger, scanner *Scanner) http.Handler
- func NewSlogHandler(next slog.Handler, scanner *Scanner) slog.Handler
- type Detector
- type Finding
- type Input
- func (i Input[T]) Format(state fmt.State, _ rune)
- func (i Input[T]) GoString() string
- func (i Input[T]) LogValue() slog.Value
- func (i Input[T]) MarshalJSON() ([]byte, error)
- func (i Input[T]) MarshalText() ([]byte, error)
- func (i *Input[T]) Scan(src any) error
- func (i Input[T]) Secret() Secret[T]
- func (i Input[T]) String() string
- func (i *Input[T]) UnmarshalJSON(data []byte) error
- func (i *Input[T]) UnmarshalText(data []byte) error
- type Kind
- type Scanner
- type ScannerOption
- type Secret
Examples ¶
- Package
- Detector
- Finding
- Input
- Input.Format
- Input.GoString
- Input.LogValue
- Input.MarshalJSON
- Input.MarshalText
- Input.Scan
- Input.Secret
- Input.String
- Input.UnmarshalJSON
- Input.UnmarshalJSON (Failure)
- Input.UnmarshalText
- Kind
- Mask
- Mask (Log)
- Mask (Overlap)
- MaskFunc
- NewHTTPHandler
- NewScanner
- NewSecret
- NewSlogHandler
- NewSlogHandler (Short)
- NewSlogHandler (Struct)
- Scanner
- Scanner.MaskJSON
- Scanner.Scan
- Scanner.ScanLines
- Scanner.ScanString
- ScannerOption
- Secret
- Secret.Format
- Secret.GoString
- Secret.LogValue
- Secret.MarshalJSON
- Secret.MarshalText
- Secret.Reveal
- Secret.String
- WithAll
- WithDetector
- WithKinds
- WithMinConfidence
- WithSensitiveKeys
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Mask ¶ added in v0.4.0
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
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
NewHTTPHandler writes masked access records after next handles each request. Authorization, Cookie and Set-Cookie values are always hidden; other header and query keys follow WithSensitiveKeys. Redirect queries receive the same treatment. Request and response bytes passed to the service or client remain unchanged. Bodies are not logged. ResponseController, flushing, hijacking and HTTP/2 push delegate to the original writer; unsupported operations return ErrNotSupported. All three arguments are required. Logging failures drop the record, and fields introduced by the downstream logger require its own masking boundary.
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=%5BREDACTED%5D
func NewSlogHandler ¶ added in v0.4.0
NewSlogHandler scans messages, keys, groups and values before forwarding to next. Both arguments must be non-nil; invalid dependencies panic. The supplied scanner controls selection: NewScanner omits unlabelled entropy tokens. Supplying a scanner with WithKinds reduces per-event detection work when only known formats matter. See https://github.com/nao1215/embargo/blob/main/doc/benchmarks.md for scan costs, excluding encoding. 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]"}
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
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
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
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
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
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
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
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
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
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
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
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.
Built-in comments state matching, validation, heuristic scores and the selection made by NewScanner without options; WithKinds and WithAll override that selection. A business label means order, invoice, tracking, version, build, serial or shipment immediately before a candidate in the same field, within 48 bytes, optionally followed by id, number, ref or code; ASCII case is ignored. Numeric normalization accepts full-width digits and hyphen variants for PAN, JPPhone, MyNumber, ABARouting, BankAccount and the eleven country kinds. Scan decodes one percent-encoding layer for every built-in except Credential. These checks do 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 Slack webhook credential paths; prefix and body checks yield 0.95 without a keyword or remote authentication. ASCII letters, digits, _ and - form bodies of at least 16 bytes after sk-proj-, sk-svcacct-, sk-ant-api03-, sk-ant-admin01-, sk_live_, rk_live_, whsec_, glpat-, npm_, pypi- or GOCSPX-; SG. instead requires 22 and 43 such bytes separated by a dot, and https://hooks.slack.com/services/ or https://hooks.slack-gov.com/services/ requires three slash-separated parts of at least 2, 2 and 16 bytes, reporting only those parts (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. No keyword is required; slash/backslash-adjacent or dotted path components and assignments to id, requestid, traceid, spanid, commit, sha, hash, checksum or uuid (case and key separators ignored) are excluded (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, Bearer/Basic schemes, usernames and hosts. Required assignment keys are password, passwd, secret, token, api_key, authorization, cookie, set-cookie, X-Amz-Signature, sig, AccountKey, SharedAccessSignature, aws_secret_access_key, SecretAccessKey, private_key, client_secret, TWILIO_AUTH_TOKEN or auth_token (ASCII case and _, -, dot or space variants); = or : introduces the value, quotes honor backslash escapes, unquoted values stop at field delimiters, cookies retain spaces/semicolons, [REDACTED] and unquoted Java object references under token are excluded, URL user:password@ after :// and MySQL @tcp(/@unix( need no keyword, and a 40-byte secret using ASCII letters, digits, + or / is accepted within 128 bytes of an AKIA/ASIA access-key ID (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, a failed checksum 0.6, and an attached business label 0.4. No keyword is needed; spaces/hyphens are allowed, prefixes are 4, 51–55 or 2221–2720, 34/37, 3528–3589, 6011/644–649/65, 300–305/36/38 and 62 respectively, with Luhn-valid lengths 13/16, 16, 15, 16, 16, 14–16 and 16–19; other Luhn-valid lengths are rejected (NewScanner default: on). KindPAN Kind = "pan" // 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. Without a keyword, require a nonempty local part without edge/consecutive dots, no leading domain dot or hyphen at label edges, and an alphabetic TLD of at least 2 letters; consecutive domain dots select the lower score, trailing dots/hyphens are trimmed, and known TLDs are com/org/net/edu/gov/mil/int/io/co/us/uk/de/fr/jp/cn/kr/au/ca/info/biz/name/pro/museum/coop/aero (case-insensitive) (NewScanner default: on). KindEmail Kind = "email" // KindJPPhone recognizes 10- or 11-digit Japanese numbers beginning with 0, allowing spaces, hyphens and parentheses; prefix/length checks score landlines 0.8, other accepted types 0.9, and business labels 0.4. No keyword is needed; 11-digit prefixes are 090/080/070/050/020/060/0800, 0120 takes 10 digits, and other 10-digit landlines start 01–09 but exclude 020/021/050/051/057/060/070/071/080/081/090/091 (NewScanner default: on). KindJPPhone Kind = "phone_jp" // KindMyNumber recognizes 12 digits with optional spaces or hyphens as Japanese individual-number candidates; the weighted MOD 11 check gives 0.95, or 0.4 under a business label, without requiring a keyword. Weights on the first 11 digits from right to left are 2,3,4,5,6,7,2,3,4,5,6; a remainder of 0 or 1 requires check digit 0, otherwise 11 minus the remainder (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. Those tiers mean undecodable/non-object header, decoded JSON object without alg, and object with alg of any type; no context keyword, signature verification or payload JSON validation is required (NewScanner default: on). KindJWT Kind = "jwt" // KindAWSKey identifies AKIA or ASIA 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. Case is ignored; registry lengths are 15:NO; 16:BE; 18:DK/FI/FK/FO/GL/NL/SD; 19:MK/SI; 20:AT/BA/EE/KZ/LT/LU/MN/XK; 21:CH/HR/LI/LV; 22:BG/BH/CR/DE/GB/GE/IE/ME/RS/VA; 23:AE/GI/IL/IQ/OM/SO/TL; 24:AD/CZ/ES/MD/PK/RO/SA/SE/SK/TN/VG; 25:LY/PT/ST; 26:IS/TR; 27:BI/DJ/FR/GR/IT/MC/MR/SM; 28:AL/AZ/BY/CY/DO/GT/HN/HU/LB/NI/PL/SV; 29:BR/EG/PS/QA/UA; 30:JO/KW/MU/YE; 31:MT/SC; 32:LC; 33:RU (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 unspecified and loopback addresses with no keyword needed. IPv4 requires 4 octets in 0–255 and token boundaries; the IPv6 branch consumes only hex and colons and rejects IPv4-mapped results (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. The location has 2 characters and the branch 3; all-letter candidates require swift, bic, bank identifier or wire within 50 bytes (case-insensitive substring), digit-bearing candidates need no keyword, and path components are excluded except contextual slash-separated code lists (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. Decimal fragments and values assigned to eventtime, downtime, lock or ino are excluded (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. When the middle pair is 01–12 and either outer pair is 01–31, sort code, sort-code, sortcode, sort_code, sc: or bacs must occur within 40 bytes (case-insensitive substring); other candidates need no keyword (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. Bodies use ASCII letters, digits, _ or -; sk_live_, pk_live_, sk_test_, pk_test_, PAYID-, sq0idp- and sq0csp- require at least 16 body bytes, while tok_, pi_, pm_, cus_, sub_, price_ and prod_ require 8 (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. Required keywords are 口座番号, 口座名義, 振込先, 銀行口座, 預金口座, bank account, account number, acct no or account no (ASCII case-insensitive); the boost needs 名義, 名義人, holder, Holder, beneficiary or Beneficiary within 50 bytes of the digits, with those spellings matched literally (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 for terminal IDs; length and keyword-overlap checks give 0.7 without checksum validation. A keyword must end within 30 bytes of the candidate: merchant id, MID: or MID followed by a space, 加盟店ID or 加盟店 for merchants; terminal id, TID: or TID followed by a space, 端末ID or 端末 for terminals, with ASCII case ignored (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. Legacy decoding must produce 25 bytes with version 0 or 5 and a double-SHA-256 check; bc1 requires the Bech32 alphabet and version 0 with Bech32 or versions 1–16 with Bech32m, but does not decode witness-program padding (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- and xoxs- 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, 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 before the next BEGIN opener when present, otherwise only the header is reported (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, or 0.4 under a business label, with no keyword or checksum required. 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, or 0.4 under a business label, without a keyword or checksum. 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, reduced to 0.4 by a business label, 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, or 0.4 with a business label, and needs no keyword. 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, lowered to 0.4 by business context, without a keyword. 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, or 0.4 under a business label, 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, or 0.4 under a business label, 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, or 0.4 with a business label, 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, or 0.4 under a business label, with no keyword. The first two digits must be 11–15, 21–23, 31–37, 41–46, 50–54, 61–65, 71, 81 or 82; the date at positions 7–14 must exist in year 0001–9999 and positions 15–17 cannot be 000, but district assignment is not checked (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 business labels 0.4. Digit 7 must be 9/0 for the 1800s, 1/2 for the 1900s or 3/4 for the 2000s; after date validation, checksum failure requires an immediately preceding rrn (case-insensitive) or 주민등록번호 label within 48 bytes in the same field, whereas a passing checksum needs no keyword (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, or 0.4 under a business label, without a keyword. 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 25 built-ins; the additional country families and KindHighEntropy are opt-in. WithAll enables all 37 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
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 ¶
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 ¶
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. 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
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
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
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
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
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
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
Source Files
¶
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. |