๐ฅ 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.
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::FilteredAttributesredacts selected instance variables from#inspect. -
Auth::Sanitizer::SanitizedLoggerwraps 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_isolatedThe 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.
This gem is used by the following libraries to ensure clean output:
- oauth
- oauth-tty
- oauth2
- omniauth-ldap
๐ก 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.
| ๐ Amazing test matrix was brought to you by | ๐ appraisal2 ๐ and the color ๐ green ๐ |
|---|---|
| ๐ Check it out! | โจ github.com/appraisal-rb/appraisal2 โจ |
Federated DVCS
| 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! |
Available as part of the Tidelift Subscription.
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-sanitizerIf bundler is not being used to manage dependencies, install the gem by executing:
gem install auth-sanitizer๐ Secure Installation
This gem is cryptographically signed and has verifiable SHA-256 and SHA-512 checksums by stone_checksums. Be sure the gem you install hasnโt been tampered with by following the instructions below.
Add my public key (if you havenโt already; key expires 2045-04-29) as a trusted certificate:
gem cert --add <(curl -Ls https://raw.github.com/galtzo-floss/certs/main/pboling.pem)You only need to do that once. Then proceed to install with:
gem install auth-sanitizer -P HighSecurityThe HighSecurity trust profile will verify signed gems, and not allow the installation of unsigned dependencies.
If you want to up your security game full-time:
bundle config set --global trust-policy MediumSecurityMediumSecurity instead of HighSecurity is necessary if not all the gems you use are signed.
NOTE: Be prepared to track down certs for signed gems and add them the same way you added mine.
โ๏ธ 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
endThis 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
endAuthSanitizer::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: falseor:
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.
Zero Top-Level Namespace Additions
A gem that needs zero new top-level namespaces from this dependency can load the loader itself inside an anonymous
namespace. On Ruby 3.1+, use Kernel.load(path, module):
auth_sanitizer_requirement = Gem::Requirement.new("~> 0.1", ">= 0.1.3")
auth_sanitizer_spec = Gem.loaded_specs["auth-sanitizer"]
unless auth_sanitizer_spec && auth_sanitizer_requirement.satisfied_by?(auth_sanitizer_spec.version)
auth_sanitizer_spec = Gem::Specification.find_by_name("auth-sanitizer", auth_sanitizer_requirement)
end
auth_sanitizer_loader_path = File.join(
auth_sanitizer_spec.full_gem_path,
"lib/auth_sanitizer/loader.rb",
)
unless File.file?(auth_sanitizer_loader_path)
raise LoadError, "auth-sanitizer #{auth_sanitizer_requirement} loader not found at #{auth_sanitizer_loader_path}"
end
auth_sanitizer_loader_namespace = Module.new
Kernel.load(auth_sanitizer_loader_path, auth_sanitizer_loader_namespace)
AUTH_SANITIZER = auth_sanitizer_loader_namespace
.const_get(:AuthSanitizer)
.const_get(:Loader)
.load_isolatedThat 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.
Ruby 2.2 through Ruby 3.0 do not support Kernel.load(path, module). For those versions, evaluate the loader source
inside an anonymous namespace with Module#module_eval:
auth_sanitizer_requirement = Gem::Requirement.new("~> 0.1", ">= 0.1.3")
auth_sanitizer_spec = Gem.loaded_specs["auth-sanitizer"]
unless auth_sanitizer_spec && auth_sanitizer_requirement.satisfied_by?(auth_sanitizer_spec.version)
auth_sanitizer_spec = Gem::Specification.find_by_name("auth-sanitizer", auth_sanitizer_requirement)
end
auth_sanitizer_loader_path = File.join(
auth_sanitizer_spec.full_gem_path,
"lib/auth_sanitizer/loader.rb",
)
unless File.file?(auth_sanitizer_loader_path)
raise LoadError, "auth-sanitizer #{auth_sanitizer_requirement} loader not found at #{auth_sanitizer_loader_path}"
end
auth_sanitizer_loader_namespace = Module.new
auth_sanitizer_loader_namespace.module_eval(
File.read(auth_sanitizer_loader_path),
auth_sanitizer_loader_path,
1,
)
AUTH_SANITIZER = auth_sanitizer_loader_namespace
.const_get(:AuthSanitizer)
.const_get(:Loader)
.load_isolatedFiltered 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 offiltered_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
endDeclared names are matched against instance variable names. For example, filtered_attributes :access_token redacts
@access_token in #inspect.
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 loading pattern.
require "auth_sanitizer/loader"
AUTH_SANITIZER = AuthSanitizer::Loader.load_isolated
class TokenResponse
include AUTH_SANITIZER::FilteredAttributes
endRedact #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:123456 @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.
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.closeMethods 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 (although 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 reek, 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
๐ช 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
๐ Versioning
This Library adheres to .
Violations of this scheme should be reported as bugs.
Specifically, if a minor or patch version is released that breaks backward compatibility,
a new version should be immediately released that restores compatibility.
Breaking changes to the public API will only be introduced with new major versions.
dropping support for a platform is both obviously and objectively a breaking change
โJordan Harband (@ljharb, maintainer of SemVer) in SemVer issue 716
I understand that policy doesn't work universally ("exceptions to every rule!"), but it is the policy here. As such, in many cases it is good to specify a dependency on this library using the Pessimistic Version Constraint with two digits of precision.
For example:
spec.add_dependency("auth-sanitizer", "~> 0.0")SemVer should, IMO, but doesn't explicitly, say that dropping support for specific Platforms is a breaking change to an API, and for that reason the bike shedding is endless.
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:
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.
๐ค 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 โญ โฅ.
Thanks for RTFM. โบ๏ธ