File: README — Documentation by YARD 0.9.44

# 💎 Auth::Sanitizer

`if ci_badges.map(&:color).detect { it != "green"}` ☝️ let me know, as I may have missed the discord notification.

`if ci_badges.map(&:color).all? { it == "green"}` 👇️ send money so I can do more of this. FLOSS maintenance is now my full-time job.

👣 How will this project approach the September 2025 hostile takeover of RubyGems? 🚑️

I’ve summarized my thoughts in this blog post.

## 🌻 Synopsis

`auth-sanitizer` provides small, dependency-light helpers for keeping OAuth and authentication secrets out of object
inspection and log output.

The gem is intentionally narrow in scope. It does not change HTTP requests, token objects, persistence, or application
configuration for you. Instead, it gives host gems and applications two reusable redaction surfaces:

- `Auth::Sanitizer::FilteredAttributes` redacts selected attributes from standard Ruby `#inspect` output.
- `Auth::Sanitizer::SanitizedLogger` wraps an existing logger and redacts sensitive values from string log messages.

Out of the box, logger sanitization filters the key names most commonly found in OAuth and OpenID Connect debug output:

    Auth::Sanitizer.default_filtered_keys
    # => [
    #      "access_token",
    #      "refresh_token",
    #      "id_token",
    #      "client_secret",
    #      "assertion",
    #      "code_verifier",
    #      "token",
    #    ]

Redacted values are replaced with `"[FILTERED]"` by default. The replacement label can be changed globally by installing
a provider, or per logger by passing `label:` to `Auth::Sanitizer::SanitizedLogger.new`.

The library snapshots filter configuration when a redacting object is initialized. That keeps already-created objects
and logger wrappers stable even if a host application changes its configuration later.

Consumers that need to avoid defining the generic top-level `Auth` namespace can use the isolated loader:

    require "auth_sanitizer/loader"

    AUTH_SANITIZER = AuthSanitizer::Loader.load_isolated

The returned module is an anonymously namespaced `Auth::Sanitizer`, suitable for internal assignment in host gems.
Use `require: false` in gems that want to avoid every new top-level namespace, including `AuthSanitizer`; see
Zero Top-Level Namespace Additions.

Consumers that want a reusable resolver for that stricter loading mode can use
`anonymous_loader`. It handles
explicit paths, RubyGems metadata, and `$LOAD_PATH` fallback resolution while evaluating
the loader under an anonymous namespace.

This gem is used by the following libraries to ensure clean output:

- oauth
- oauth-tty
- oauth2
- omniauth-ldap
- omniauth-identity

## 💡 Info you can shake a stick at

Tokens to Remember |
--- | ---
Works with JRuby |
Works with Truffle Ruby |
Works with MRI Ruby 4 |
Works with MRI Ruby 3 |
Works with MRI Ruby 2 |
Support & Community |
Source |
Documentation |
Compliance |
Style |
Maintainer 🎖️ |
`...` 💖 | 🧊 🐙 🛖 🧪

### Compatibility

Compatible with MRI Ruby 2.2.0+, and concordant releases of JRuby, and TruffleRuby.
CI workflows and Appraisals are generated for MRI Ruby 2.4+.
This test floor is configured by `ruby.test_minimum` in `.kettle-jem.yml` and
may be higher than the gem’s runtime compatibility floor when legacy Rubies are
not practical for the current toolchain.

The amazing test matrix is powered by the kettle-dev stack.

How kettle-dev manages complexity in tests

Gem | Source | Role | Daily download rank
--- | --- | --- | ---
appraisal2 | GitHub | multi-dependency Appraisal matrix generation |
appraisal2-rubocop | GitHub | RuboCop Appraisal generator integration |
kettle-dev | GitHub | development, release, and CI workflow tooling |
kettle-jem | GitHub | Appraisals & CI workflow templates |
kettle-soup-cover | GitHub | SimpleCov coverage policy and reporting |
kettle-test | GitHub | standard test runner and coverage harness |
rubocop-lts | GitHub | Ruby-version-aware linting |
turbo_tests2 | GitHub | parallel test execution |

### Federated DVCS

Find this repo on federated forges (Coming soon!)

Federated DVCS Repository | Status | Issues | PRs | Wiki | CI | Discussions
--- | --- | --- | --- | --- | --- | ---
🧪 ruby-oauth/auth-sanitizer on GitLab | The Truth | 💚 | 💚 | 💚 | 🐭 Tiny Matrix | ➖
🧊 ruby-oauth/auth-sanitizer on CodeBerg | An Ethical Mirror (Donate) | 💚 | 💚 | ➖ | ⭕️ No Matrix | ➖
🐙 ruby-oauth/auth-sanitizer on GitHub | Another Mirror | 💚 | 💚 | 💚 | 💯 Full Matrix | 💚
🎮️ Discord Server |  | Let’s | talk | about | this | library!

### Enterprise Support

Available as part of the Tidelift Subscription.

Need enterprise-level guarantees?

The maintainers of this and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use.

- 💡Subscribe for support guarantees covering all your FLOSS dependencies
- 💡Tidelift is part of Sonar
- 💡Tidelift pays maintainers to maintain the software you depend on!
  📊`@`Pointy Haired Boss: An enterprise support subscription is “never gonna let you down”, and supports open source maintainers

Alternatively:

## ✨ Installation

Install the gem and add to the application’s Gemfile by executing:

    bundle add auth-sanitizer

If bundler is not being used to manage dependencies, install the gem by executing:

    gem install auth-sanitizer

## ⚙️ Configuration

Most applications can use the defaults. Configuration is available when a host gem or application wants to align
redaction with its own logging conventions.

### Loading Mode

This gem has two supported loading modes.

The direct API defines the top-level `Auth` namespace:

    require "auth/sanitizer"

    class TokenResponse
      include Auth::Sanitizer::FilteredAttributes
    end

This is convenient for applications that already own or intentionally use `Auth`.

Libraries and applications that need to avoid the generic top-level `Auth` namespace should use the isolated loader:

    require "auth_sanitizer/loader"

    AUTH_SANITIZER = AuthSanitizer::Loader.load_isolated

    class TokenResponse
      include AUTH_SANITIZER::FilteredAttributes
    end

`AuthSanitizer::Loader.load_isolated` evaluates the sanitizer implementation inside an anonymous module and returns that
module’s `Auth::Sanitizer` constant. Assign the returned module to a constant owned by your library or application, then
include from that constant.

When declaring the dependency in a Gemfile, prefer one of these explicit forms:

    gem "auth-sanitizer", require: false

or:

    gem "auth-sanitizer", require: "auth_sanitizer/loader"

Use `require: false` when the consuming library will decide which loading mode to use internally. Use
`require: "auth_sanitizer/loader"` when Bundler should make the isolated loader available during `Bundler.require`.

When Bundler standalone setup is loaded directly, a dependency can be present on `$LOAD_PATH` without a matching
`Gem.loaded_specs` entry or `GEM_PATH` entry. Consumers that locate the isolated loader themselves should therefore
use `AnonymousLoader.load_path`, or otherwise fall back to `Gem.find_files("auth_sanitizer/loader.rb")`, before failing.

#### Zero Top-Level Namespace Additions

For a gem that needs zero new top-level namespaces from `auth-sanitizer`, use `anonymous_loader` to evaluate
`auth_sanitizer/loader.rb` inside an anonymous namespace, then call `AuthSanitizer::Loader.load_isolated` from that
anonymous namespace:

    require "anonymous_loader"

    auth_sanitizer_requirement = Gem::Requirement.new("~> 0.2", ">= 0.2.1")
    auth_sanitizer_loader_namespace = AnonymousLoader.load_path(
      gem_name: "auth-sanitizer",
      require_path: "auth_sanitizer/loader.rb",
      version_requirement: auth_sanitizer_requirement,
      version_file: "auth/sanitizer/version.rb"
    )

    AUTH_SANITIZER = auth_sanitizer_loader_namespace
      .const_get(:AuthSanitizer)
      .const_get(:Loader)
      .load_isolated

That pattern leaves both `Auth` and `AuthSanitizer` undefined at top level. The consuming gem should assign the returned
module under its own namespace and use that internal constant. It does define `AnonymousLoader`, whose namespace is
specific to the resolver gem and intentionally much less collision-prone than `Auth`.

Declare both dependencies with `require: false` when the consuming library owns its loading path:

    gem "anonymous_loader", "~> 0.1", ">= 0.1.0", require: false
    gem "auth-sanitizer", "~> 0.2", ">= 0.2.1", require: false

If the host application uses `Bundler.require`, use:

    gem "anonymous_loader", "~> 0.1", ">= 0.1.0"
    gem "auth-sanitizer", "~> 0.2", ">= 0.2.1", require: false

`AnonymousLoader.load_path` raises `AnonymousLoader::FileNotFoundError` when it cannot resolve the loader, and
`AnonymousLoader::VersionMismatchError` when it finds a load-path candidate whose adjacent version file does not satisfy
the requested range.

### Filtered Label

The default replacement label is:

    Auth::Sanitizer.filtered_label
    # => "[FILTERED]"

To use a different label globally, install a callable provider:

    Auth::Sanitizer.filtered_label_provider = -> { "[REDACTED]" }

The provider is called when a `FilteredAttributes` object or `SanitizedLogger` wrapper is initialized. Existing
instances keep the label they captured at initialization time:

    Auth::Sanitizer.filtered_label_provider = -> { "[FILTERED]" }
    logger = Auth::Sanitizer::SanitizedLogger.new(Logger.new($stdout))

    Auth::Sanitizer.filtered_label_provider = -> { "[REDACTED]" }

    # `logger` still uses "[FILTERED]"; new wrappers use "[REDACTED]".

This makes it safe for libraries to delegate the label to host configuration:

    Auth::Sanitizer.filtered_label_provider = -> { MyGem.config.filtered_label }

### Logger Keys

`Auth::Sanitizer::SanitizedLogger` defaults to `Auth::Sanitizer.default_filtered_keys`. Pass `filtered_keys:` when your
application logs additional sensitive fields:

    logger = Auth::Sanitizer::SanitizedLogger.new(
      Logger.new($stdout),
      filtered_keys: Auth::Sanitizer.default_filtered_keys + %w[
        api_key
        private_key
        session_secret
      ]
    )

You can also replace the list entirely:

    logger = Auth::Sanitizer::SanitizedLogger.new(
      Logger.new($stdout),
      filtered_keys: %w[my_secret],
      label: "[GONE]"
    )

Logger key matching is case-insensitive for supported string formats. The keys are used to redact:

- JSON-style pairs, such as `"access_token": "abc123"` and `'client_secret': 'abc123'`
- query-string and form-encoded pairs, such as `access_token=abc123&scope=read`
- `Authorization:` header values, regardless of `filtered_keys`

Only string payloads are sanitized. Non-string log payloads are delegated unchanged to the wrapped logger.

### Inspect Attributes

Classes opt in to inspect redaction by including `Auth::Sanitizer::FilteredAttributes` and declaring the attribute names
that should be hidden:

    class OAuthCredential
      include Auth::Sanitizer::FilteredAttributes

      attr_reader :access_token, :expires_at

      filtered_attributes :access_token

      def initialize(access_token, expires_at)
        @access_token = access_token
        @expires_at = expires_at
      end
    end

`FilteredAttributes#inspect` delegates to `super.inspect` first, then redacts only narrow, standard Ruby inspect
fragments for configured names. This preserves host object inspect behavior instead of rebuilding the object’s output.

For example, `filtered_attributes :access_token` redacts `@access_token="..."` in normal object inspect output:

    OAuthCredential.new("secret", Time.now).inspect
    # => #<OAuthCredential:0x... @access_token=[FILTERED], @expires_at=2026-06-04 08:00:00 -0600>

Configured names are also redacted when they appear as string-valued keys inside standard Ruby hash inspect fragments,
which is useful for adapter models that store attributes in an internal hash:

    class IdentityRecord
      include Auth::Sanitizer::FilteredAttributes

      filtered_attributes :password_digest

      def initialize(identity_data)
        @identity_data = identity_data
      end
    end

    IdentityRecord.new({id: 1, password_digest: "$2a$secret"}).inspect
    # => #<IdentityRecord:0x... @identity_data={id: 1, password_digest: [FILTERED]}>

The inspect redactor intentionally leaves unsupported or highly customized inspect formats unchanged. It only replaces
quoted string values in these standard shapes:

- `@name="value"`
- `{name: "value"}`
- `{:name => "value"}`
- `{"name" => "value"}`

This conservative behavior avoids breaking host models whose `inspect` output has application-specific formatting.

Calling `filtered_attributes` again replaces the class-level list:

    OAuthCredential.filtered_attributes(:access_token, :refresh_token)
    OAuthCredential.filtered_attribute_names
    # => [:access_token, :refresh_token]

Passing no attributes clears the class-level list for subsequently initialized objects:

    OAuthCredential.filtered_attributes
    OAuthCredential.filtered_attribute_names
    # => []

As with logger wrappers, the per-object filter is captured during initialization. Objects that already exist keep their
original inspect behavior.

## 🔧 Basic Usage

Require the gem:

    require "auth/sanitizer"

Or load it without defining top-level `Auth`. This still defines top-level `AuthSanitizer`; see
Zero Top-Level Namespace Additions for the stricter `anonymous_loader` pattern.

    require "auth_sanitizer/loader"

    AUTH_SANITIZER = AuthSanitizer::Loader.load_isolated

    class TokenResponse
      include AUTH_SANITIZER::FilteredAttributes
    end

### Redact `#inspect`

Use `Auth::Sanitizer::FilteredAttributes` for objects that may appear in exception messages, console sessions, or debug
output through `#inspect`:

    class TokenResponse
      include Auth::Sanitizer::FilteredAttributes

      attr_reader :access_token, :refresh_token, :scope

      filtered_attributes :access_token, :refresh_token

      def initialize(access_token:, refresh_token:, scope:)
        @access_token = access_token
        @refresh_token = refresh_token
        @scope = scope
      end
    end

    response = TokenResponse.new(
      access_token: "access-token-value",
      refresh_token: "refresh-token-value",
      scope: "profile email"
    )

    response.inspect
    # => #<TokenResponse:0x... @access_token=[FILTERED], @refresh_token=[FILTERED], @scope="profile email">

Only the configured attributes are redacted. Other instance variables remain visible so inspected objects are still
useful while debugging. Inspect filtering is conservative: unsupported custom formats are left unchanged rather than
risking a malformed `inspect` result.

### Redact Logger Output

Wrap an existing logger with `Auth::Sanitizer::SanitizedLogger`:

    require "logger"
    require "auth/sanitizer"

    logger = Auth::Sanitizer::SanitizedLogger.new(Logger.new($stdout))

    logger.debug("access_token=abc123&scope=profile")
    # Logs: access_token=[FILTERED]&scope=profile

    logger.debug('{"client_secret": "super-secret", "grant_type": "client_credentials"}')
    # Logs: {"client_secret": "[FILTERED]", "grant_type": "client_credentials"}

    logger.debug("Authorization: Bearer abc123")
    # Logs: Authorization: "[FILTERED]"

The wrapper implements the common Ruby logger methods and sanitizes string values passed through them:

    logger.add(Logger::DEBUG, "refresh_token=abc123", "oauth")
    logger << "id_token=abc123"

    logger.debug { "code_verifier=abc123" }
    logger.info("token=abc123")
    logger.warn("client_secret=abc123")
    logger.error("assertion=abc123")
    logger.fatal("Authorization: Bearer abc123")
    logger.unknown("access_token=abc123")

The wrapper also delegates common logger configuration to the wrapped logger when supported:

    logger.level = Logger::WARN
    logger.progname = "my-app"
    logger.formatter = proc { |_severity, _time, _progname, message| "#{message}\n" }
    logger.close

Methods not implemented by the wrapper are delegated to the underlying logger when that logger responds to them.

### Custom Logger Keys

Use `filtered_keys:` for application-specific secrets:

    logger = Auth::Sanitizer::SanitizedLogger.new(
      Logger.new($stdout),
      filtered_keys: %w[access_token api_key signing_secret],
      label: "[SECRET]"
    )

    logger.debug("api_key=12345&access_token=abc123")
    # Logs: api_key=[SECRET]&access_token=[SECRET]

`filtered_keys:` applies to JSON-style, query-string, and form-encoded key/value pairs. `Authorization:` headers are
always redacted by `SanitizedLogger`, even if `Authorization` is not listed as a filtered key.

### Important Limits

`auth-sanitizer` is a logging and inspection helper, not a complete secret-management system.

- It redacts supported string patterns before delegating to a logger.
- It does not mutate source hashes, token objects, HTTP requests, or HTTP responses.
- It does not recursively sanitize arbitrary Ruby objects passed to a logger as non-string payloads.
- It cannot protect secrets that are logged through a different logger, printed directly, or interpolated into an
  unsupported format.

For best results, wrap the logger as close as possible to the code that emits authentication debug output, and avoid
logging raw token structures unless they pass through the sanitizer first.

## 🦷 FLOSS Funding

While ruby-oauth tools are free software and will always be, the project would benefit immensely from some funding.
Raising a monthly budget of… “dollars” would make the project more sustainable.

We welcome both individual and corporate sponsors! We also offer a
wide array of funding channels to account for your preferences.
Currently, Open Collective is our preferred funding platform.

If you’re working in a company that’s making significant use of ruby-oauth tools we’d
appreciate it if you suggest to your company to become a ruby-oauth sponsor.

You can support the development of ruby-oauth tools via
GitHub Sponsors,
Liberapay,
PayPal,
Open Collective
and Tidelift.

📍 NOTE
If doing a sponsorship in the form of donation is problematic for your company from an accounting standpoint, we’d recommend the use of Tidelift, where you can get a support-like subscription instead.

### Open Collective for Individuals

Support us with a monthly donation and help us continue our activities. [Become a backer]

NOTE: kettle-readme-backers updates this list every day, automatically.

No backers yet. Be the first!

### Open Collective for Organizations

Become a sponsor and get your logo on our README on GitHub with a link to your site. [Become a sponsor]

NOTE: kettle-readme-backers updates this list every day, automatically.

No sponsors yet. Be the first!

### Another way to support open-source

I’m driven by a passion to foster a thriving open-source community – a space where people can tackle complex problems, no matter how small. Revitalizing libraries that have fallen into disrepair, and building new libraries focused on solving real-world challenges, are my passions. I was recently affected by layoffs, and the tech jobs market is unwelcoming. I’m reaching out here because your support would significantly aid my efforts to provide for my family, and my farm (11 🐔 chickens, 2 🐶 dogs, 3 🐰 rabbits, 8 🐈‍ cats).

If you work at a company that uses my work, please encourage them to support me as a corporate sponsor. My work on gems you use might show up in `bundle fund`.

I’m developing a new library, floss_funding, designed to empower open-source developers like myself to get paid for the work we do, in a sustainable way. Please give it a look.

Floss-Funding.dev: 👉️ No network calls. 👉️ No tracking. 👉️ No oversight. 👉️ Minimal crypto hashing. 💡 Easily disabled nags

## 🔐 Security

See SECURITY.md.

## 🤝 Contributing

If you need some ideas of where to help, you could work on adding more code coverage,
or if it is already 💯 (see below) check issues or PRs,
or use the gem and think about how it could be better.

We so if you make changes, remember to update it.

See CONTRIBUTING.md for more detailed instructions.

### 🚀 Release Instructions

See CONTRIBUTING.md.

### Code Coverage

Coverage service badges

### 🪇 Code of Conduct

Everyone interacting with this project’s codebases, issue trackers,
chat rooms and mailing lists agrees to follow the .

## 🌈 Contributors

Made with contributors-img.

Also see GitLab Contributors: https://gitlab.com/ruby-oauth/auth-sanitizer/-/graphs/main

⭐️ Star History

</a>

## 📌 Versioning

This library follows for its public API where practical.
For most applications, prefer the Pessimistic Version Constraint with two digits of precision.

For example:

    spec.add_dependency("auth-sanitizer", "~> 0.0")

📌 Is "Platform Support" part of the public API? More details inside.

Dropping support for a platform can be a breaking change for affected users. If a release changes supported platforms, it should be called out clearly in the changelog and versioned with that impact in mind.

To get a better understanding of how SemVer is intended to work over a project’s lifetime, read this article from the creator of SemVer:

- “Major Version Numbers are Not Sacred”

See CHANGELOG.md for a list of releases.

## 📄 License

The gem is available as open source under the terms of
the MIT .

### © Copyright

See LICENSE.md for the official copyright notice.

Copyright holders

- Copyright (c) 2026 Peter H. Boling

## 🤑 A request for help

Maintainers have teeth and need to pay their dentists.
After getting laid off in an RIF in March, and encountering difficulty finding a new one,
I began spending most of my time building open source tools.
I’m hoping to be able to pay for my kids’ health insurance this month,
so if you value the work I am doing, I need your support.
Please consider sponsoring me or the project.

To join the community or get help 👇️ Join the Discord.

To say “thanks!” ☝️ Join the Discord or 👇️ send money.

💌 💌 💌

### Please give the project a star ⭐ ♥.

Many parts of this project are actively managed by a kettle-jem smart template utilizing StructuredMerge.org merge contracts.

Thanks for RTFM. ☺️

| Field | Value |
|—|—|
| Package | auth-sanitizer |
| Description | 💎 Configurable KV output redaction. Sanitize/filter your secrets. |
| Homepage | https://github.com/ruby-oauth/auth-sanitizer |
| Source | https://github.com/ruby-oauth/auth-sanitizer |
| License | `MIT` |
| Funding | https://github.com/sponsors/pboling, https://ko-fi.com/pboling, https://liberapay.com/pboling/donate, https://opencollective.com/ruby-oauth, https://thanks.dev/u/gh/pboling, https://tidelift.com/funding/github/rubygems/auth-sanitizer, https://www.buymeacoffee.com/pboling |