sssecrets 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c53098afd2ccaa38089d3936fa16d7a689779ebb1ab30275922e3140cea54752
4
+ data.tar.gz: 519617649b46d29758f3639195587a28975125e4fe2c54bfdbd5a1226a4121fe
5
+ SHA512:
6
+ metadata.gz: 041e148ff617a8eacf2bd9d9d4f18c879b21beff57a0b8aaac17d7793f8298efd1c6e059a51e2a272ecfbfd32143811fe6d2195520665e4d2eb15e08a987dde0
7
+ data.tar.gz: cdf6ececb842fdda3913d464afac4190215310c7dc4515f8f98af394a0c5d40f237daea9a05a00d6b13a3996e3d900952bcee260c364c1a523614d0112ad5b0e
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in sssecrets.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "rubocop", "~> 1.21"
data/Gemfile.lock ADDED
@@ -0,0 +1,46 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ sssecrets (1.0.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ json (2.6.3)
11
+ minitest (5.17.0)
12
+ parallel (1.22.1)
13
+ parser (3.2.0.0)
14
+ ast (~> 2.4.1)
15
+ rainbow (3.1.1)
16
+ rake (13.0.6)
17
+ regexp_parser (2.6.2)
18
+ rexml (3.2.5)
19
+ rubocop (1.44.1)
20
+ json (~> 2.3)
21
+ parallel (~> 1.10)
22
+ parser (>= 3.2.0.0)
23
+ rainbow (>= 2.2.2, < 4.0)
24
+ regexp_parser (>= 1.8, < 3.0)
25
+ rexml (>= 3.2.5, < 4.0)
26
+ rubocop-ast (>= 1.24.1, < 2.0)
27
+ ruby-progressbar (~> 1.7)
28
+ unicode-display_width (>= 2.4.0, < 3.0)
29
+ rubocop-ast (1.24.1)
30
+ parser (>= 3.1.1.0)
31
+ ruby-progressbar (1.11.0)
32
+ unicode-display_width (2.4.2)
33
+
34
+ PLATFORMS
35
+ arm64-darwin-21
36
+ x86_64-linux
37
+ ruby
38
+
39
+ DEPENDENCIES
40
+ minitest (~> 5.0)
41
+ rake (~> 13.0)
42
+ rubocop (~> 1.21)
43
+ sssecrets!
44
+
45
+ BUNDLED WITH
46
+ 2.3.7
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Charlton Trezevant
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,96 @@
1
+ # Sssecrets
2
+
3
+ Welcome to sssecrets: **S**imple **S**tructured **Secrets**.
4
+
5
+ Sssecrets is a reusable implementation of GitHub's structured secret token format. You can learn more about GitHub's design process and the properties of their API token format on the [GitHub blog](https://github.blog/2021-04-05-behind-githubs-new-authentication-token-formats/).
6
+
7
+ ## Why Structured Secrets?
8
+
9
+ If you're a developer and your application issues some kind of access tokens (API keys, PATs, etc), it's important to format these in a way that both identifies the string as a secret token and provides insight into its permissions. Even better if you provide example (dummy) tokens and regexes for them in your documentation!
10
+
11
+ Simple Structured Secrets help solve this problem: They're a compact format with properties that are optimized for detection with static analysis tools. That makes it possible to automatically detect when secrets are leaked in a codebase using features like [GitHub Secret Scanning](https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning) or GitLab Secret Detection.
12
+
13
+ Here's an example. HashiCorp Vault's API access tokens look like this ([ref](https://developer.hashicorp.com/vault/api-docs#authentication)):
14
+
15
+ `f3b09679-3001-009d-2b80-9c306ab81aa6`
16
+
17
+ You might think that this is pretty is a pretty easy pattern to search for, but here's the issue: It's just a [UUID string](https://en.wikipedia.org/wiki/Universally_unique_identifier).
18
+
19
+ While random, strings in this format are used in many places for non-sensitive purposes. Meaning that, given a random UUID formatted string, it's impossible to know whether it's a sensitive API credential or a garden-variety identifier for something mundane. In cases like these, secret scanning can't help much.
20
+
21
+ ## What's in a Structured Secret?
22
+
23
+ Structured secrets have three parts:
24
+
25
+ - A prefix (defined by you),
26
+ - 30 characters of randomness,
27
+ - A 6 character checksum.
28
+
29
+ That's it!
30
+
31
+ `[prefix]_[randomness][checksum]`
32
+
33
+ ### Prefix
34
+
35
+ Token prefixes are a simple and effective method to make tokens identifiable. [Slack](https://api.slack.com/authentication/token-types), [Stripe](https://stripe.com/docs/api/authentication), [GitHub](https://github.blog/2021-04-05-behind-githubs-new-authentication-token-formats/#identifiable-prefixes), and others have adopted this approach to great effect.
36
+
37
+ Sssecrets allows you to provide two abbreviated strings, `org` and `type`, which together make up the token prefix. Generally, `org` would be used to specify an overarching identifier (like your company or app), while `type` is intended to identify the token type (i.e., OAuth tokens, refresh tokens, etc) in some way. To maintain a compact and consistent format for Sssecret tokens, `org` and `type` together should not exceed 10 characters in length.
38
+
39
+ ### Entropy
40
+
41
+ Simple Structured Secret tokens have an entropy of 178:
42
+
43
+ `Math.log(((“a”..“z”).to_a + (“A”..“Z”).to_a + (0..9).to_a).length)/Math.log(2) * 30 = 178`
44
+
45
+ *See the [GitHub blog](https://github.blog/2021-04-05-behind-githubs-new-authentication-token-formats/#token-entropy).*
46
+
47
+ ### Checksum
48
+
49
+ The random component of the token is used to calculate a CRC32 checksum. This checksum is encoded in Base62 and padded with leading zeroes to ensure it's always 6 characters in length.
50
+
51
+ The token checksum can be used as a first-pass validity check. Using these checksums, false positives can be more or less eliminated when a codebase is being scanned for secrets, as fake tokens can be ignored without the need to query a backend or database.
52
+
53
+ _Note that this library can only check whether a given token is in the correct form and has a valid checksum. To fully determine whether a given token is active, you'll still need to implement your own logic for checking the validity of tokens you've issued._
54
+
55
+ ## Installation
56
+
57
+ Add this gem to your application's Gemfile:
58
+
59
+ ```ruby
60
+ gem 'sssecrets'
61
+ ```
62
+
63
+ And then execute:
64
+
65
+ $ bundle install
66
+
67
+ Or install it yourself as:
68
+
69
+ $ gem install sssecrets
70
+
71
+ ## Usage
72
+
73
+ Sssecrets is designed to be simple and straightforward to use. Here's an example:
74
+
75
+ ```ruby
76
+ require 'sssecrets'
77
+
78
+ test = SimpleStructuredSecrets.new("t", "k")
79
+ tok = test.generate
80
+
81
+ puts "#{tok} is valid!" if test.validate(tok)
82
+ ```
83
+
84
+ ## Development
85
+
86
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
87
+
88
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
89
+
90
+ ## Contributing
91
+
92
+ Bug reports and pull requests are welcome on GitHub at https://github.com/chtzvt/sssecrets.
93
+
94
+ ## License
95
+
96
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
data/lib/sssecrets.rb ADDED
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Based on https://github.com/steventen/base62-rb, with light modifications
4
+ module Base62
5
+ KEYS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
6
+ KEYS_HASH = KEYS.each_char.with_index.each_with_object({}) do |(k, v), h|
7
+ h[k] = v
8
+ end
9
+ BASE = KEYS.length
10
+
11
+ # Encodes base10 (decimal) number to base62 string.
12
+ def base62_encode(num)
13
+ return "0" if num.zero?
14
+ return nil if num.negative?
15
+
16
+ str = ""
17
+ while num.positive?
18
+ # prepend base62 charaters
19
+ str = KEYS[num % BASE] + str
20
+ num /= BASE
21
+ end
22
+ str
23
+ end
24
+
25
+ # Decodes base62 string to a base10 (decimal) number.
26
+ def base62_decode(str)
27
+ num = 0
28
+ i = 0
29
+ len = str.length - 1
30
+ # while loop is faster than each_char or other 'idiomatic' way
31
+ while i < str.length
32
+ pow = BASE**(len - i)
33
+ num += KEYS_HASH[str[i]] * pow
34
+ i += 1
35
+ end
36
+ num
37
+ end
38
+ end
39
+
40
+ # Simple Structured Secrets aims to implement GitHub's authentication
41
+ # token format as faithfully as possible. You can learn more about the
42
+ # design and properties of these tokens at the following link:
43
+ # https://github.blog/2021-04-05-behind-githubs-new-authentication-token-formats/
44
+ class SimpleStructuredSecrets
45
+ class Error < StandardError; end
46
+
47
+ require "zlib"
48
+ require "securerandom"
49
+ include Base62
50
+
51
+ attr_accessor :org, :type
52
+
53
+ def initialize(org, type)
54
+ raise "Prefix is too long." if org.length + type.length > 10
55
+
56
+ @org = org
57
+ @type = type
58
+ end
59
+
60
+ # Generate a Simple Structured Secret token.
61
+ #
62
+ # Example:
63
+ # >> SimpleStructuredSecret.generate
64
+ # => "tk_GUkLdIZV8xnQQZobkuynSyyPkcweVm14nosQ"
65
+ def generate
66
+ random = base62_encode(SecureRandom.rand(10**60)).to_s[0...30]
67
+ "#{@org}#{@type}_#{random}#{calc_checksum(random)}"
68
+ end
69
+
70
+ # Calculate the base62-encoded CRC32 checksum for a given input string.
71
+ # When necessary, this value will be left-padded with 0 to ensure it's
72
+ # always 6 characters long.
73
+ #
74
+ # Example:
75
+ # >> SimpleStructuredSecrets.calc_checksum("GUkLdIZV8xnQQZobkuynSyyPkcweVm")
76
+ # => "14nosQ"
77
+ #
78
+ # Arguments:
79
+ # secret: (String)
80
+ def calc_checksum(secret)
81
+ base62_encode(Zlib.crc32(secret)).ljust(6, "0")
82
+ end
83
+
84
+ # Validate a given Simple Structured Secret token.
85
+ # Note that this only indicates whether a given token is in the correct
86
+ # form and has a valid checksum. You will still need to implement your
87
+ # own logic for checking the validity of tokens you've issued.
88
+ #
89
+ # Example:
90
+ # >> SimpleStructuredSecrets.validate("tk_GUkLdIZV8xnQQZobkuynSyyPkcweVm14nosQ")
91
+ # => true
92
+ #
93
+ # Arguments:
94
+ # secret: (String)
95
+ def validate(secret)
96
+ random = /(?<=_)[A-Za-z0-9]{30}/.match(secret).to_s
97
+ calc_checksum(random) == secret.chars.last(6).join
98
+ end
99
+
100
+ # Append a Simple Structured Secret header to a provided string.
101
+ # This is useful in cases where you'd like to realize the secret
102
+ # scanning benefits of SSS with other token formats.
103
+ #
104
+ # Example:
105
+ # >> SimpleStructuredSecrets.generate_header("5be426ee126b88f9587bbbe767a7592c")
106
+ # => "tk_1e6YXE_5be426ee126b88f9587bbbe767a7592c"
107
+ #
108
+ # Arguments:
109
+ # str: (String)
110
+ def generate_header(str)
111
+ "#{@org}#{@type}_#{calc_checksum(str)}_#{str}"
112
+ end
113
+
114
+ # Validate a Simple Structured Secret header for a given string.
115
+ #
116
+ # Example:
117
+ # >> SimpleStructuredSecrets.validate_header("tk_1e6YXE_5be426ee126b88f9587bbbe767a7592c")
118
+ # => true
119
+ #
120
+ # Arguments:
121
+ # str: (String)
122
+ def validate_header(str)
123
+ matches = /(?<prefix>.*)_(?<checksum>[A-Za-z0-9]{6})_(?<string>.*)/.match(str)
124
+ calc_checksum(matches["string"]) == matches["checksum"]
125
+ end
126
+ end
data/sig/sssecrets.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Sssecrets
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,52 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sssecrets
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Charlton Trezevant
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-02-05 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Easily generate and validate structured secrets for your application
14
+ email:
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - ".rubocop.yml"
20
+ - Gemfile
21
+ - Gemfile.lock
22
+ - LICENSE.txt
23
+ - README.md
24
+ - Rakefile
25
+ - lib/sssecrets.rb
26
+ - sig/sssecrets.rbs
27
+ homepage: https://github.com/chtzvt/sssecrets
28
+ licenses:
29
+ - MIT
30
+ metadata:
31
+ homepage_uri: https://github.com/chtzvt/sssecrets
32
+ source_code_uri: https://github.com/chtzvt/sssecrets
33
+ post_install_message:
34
+ rdoc_options: []
35
+ require_paths:
36
+ - lib
37
+ required_ruby_version: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: 2.6.0
42
+ required_rubygems_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0'
47
+ requirements: []
48
+ rubygems_version: 3.3.7
49
+ signing_key:
50
+ specification_version: 4
51
+ summary: Simple Structured Secrets
52
+ test_files: []