site_paths 0.1.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: f65bebd7e04aafb5aafb3432360b826b1490551c954f26af33c606778e5e2763
4
+ data.tar.gz: f92600124efd7c00d81f31ff04fabb9ee92aa8ae8a00777c31ba7acbe85c5f8b
5
+ SHA512:
6
+ metadata.gz: 3b7cc6eab00ccb4451fc49ef5cd8cff5f7bd984aa0a0f30268dd75b7b721efd3eeb749825a0ac3d07f59acba16e0563aa7855bd0047b5f316faf2fd5d301d9fd
7
+ data.tar.gz: a972da9eb08d43d93174e7358c06d0ad7876fffb59d1f66a9c309b6dd6731897598a724fc596b42cc12aeb107749ed8c41920332f7def5b69093536c786c2919
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,200 @@
1
+ # site_paths
2
+
3
+ Stop your site from telling strangers which private routes exist.
4
+
5
+ If `/admin/reports` answers "sign in" and a made-up address answers
6
+ "not found", anybody can tell that your site has a reports page without
7
+ seeing a single report. Asking for a list of names gives the list of
8
+ what you have. Scanners do that in the first minutes of an attack, and
9
+ what they try next is built on it.
10
+ [Why hide whether a route exists?](https://github.com/webodik/toller-web/blob/main/docs/why.md)
11
+
12
+ This is the wall for Ruby: in your server, it answers every path of a
13
+ private part alike, there or not, for whoever your own code does not
14
+ let in. It is Rack middleware, for Rails, Sinatra and whatever else
15
+ speaks Rack.
16
+
17
+ No dependencies. Apache-2.0.
18
+
19
+ ## Install
20
+
21
+ ```ruby
22
+ # Gemfile
23
+ gem "site_paths"
24
+ ```
25
+
26
+ Ruby 3.3 or later.
27
+
28
+ ## Quick start
29
+
30
+ **1. Ask your deployment what it gives away.** The check is one command
31
+ for a site written in anything, and needs Node.js where it runs, which
32
+ is not on your server. Name the private part and one route in it that
33
+ exists, at the address your visitors use:
34
+
35
+ ```sh
36
+ npx -p site-paths site-paths-check --url https://staging.shop.example --under /admin --has /admin/reports
37
+ ```
38
+
39
+ It asks as a stranger for that route and for made-up names beside it.
40
+ If anything tells them apart, it says what and ends with 1.
41
+ [What the check asks and what it takes](https://github.com/webodik/toller-web/tree/main/js#the-check).
42
+
43
+ **2. If it fails, put a wall before your routes.** On Rails:
44
+
45
+ ```ruby
46
+ # config/initializers/wall.rb
47
+ Rails.application.config.middleware.use SitePaths::Wall,
48
+ under: "/admin",
49
+ allow: ->(env) { env.dig("rack.session", "role") == "staff" }
50
+ ```
51
+
52
+ `allow` is your own decision about who is let in. Whoever is not gets
53
+ the same plain `404` for every path under `/admin`, so a route that is
54
+ there and one that is not look the same, and the request never reaches
55
+ your routes. Staff go on to your routes as before.
56
+
57
+ **3. Run the check again, as your staff as well, and keep it where
58
+ your tests run.** It fails when a later change lets an answer tell
59
+ again. Asked as a stranger alone it passes where a mistake in `allow`
60
+ keeps everybody out, your staff among them, so give it what one of the
61
+ staff sends:
62
+
63
+ ```sh
64
+ WALL_STAFF="cookie: _shop_session=..." npx -p site-paths site-paths-check --url https://staging.shop.example --under /admin --has /admin/reports
65
+ ```
66
+
67
+ ## What a wall keeps
68
+
69
+ Routes of your application: requests that reach it. A file in your
70
+ public folder is answered before that, by nginx or by the middleware
71
+ that serves such files: a wall never sees those requests. Keep what is
72
+ private out of the public folder.
73
+
74
+ ## Rails
75
+
76
+ Added in a file of `config/initializers`, the wall is at the end of the
77
+ middleware: after the session's and after whatever your gems add, and
78
+ before the routes are looked up. `bin/rails middleware` shows the
79
+ order.
80
+
81
+ - **`allow` is called with the request's environment.** The session is
82
+ `env["rack.session"]`, read as your controllers read it. Reading it
83
+ makes no session: a stranger who is kept out leaves none and gets no
84
+ cookie. `env.dig("rack.session", "role")` answers `nil` where there
85
+ is no session at all, as in an application that is an API only.
86
+ - **Who is signed in by a library** is where its middleware left it.
87
+ Devise's is before the wall, and `env["warden"]` is there.
88
+ - **An API that signs its callers in by a token** mostly does so in its
89
+ controllers, which run after a route was found. Before that nothing
90
+ has read the token: have `allow` read it, from
91
+ `env["HTTP_AUTHORIZATION"]`, with what your controllers read it
92
+ with.
93
+ - **Rails finds a route by more than one spelling.** `/admin/users/`,
94
+ `/admin/users.json` and `/admin//users` all reach the route at
95
+ `/admin/users`, and `/admin/%2e%2e/users` reaches a route with a
96
+ parameter. A wall keeps each. It keeps the start of the part with the
97
+ name of a format after it as well: to Rails, `/admin.json` is the
98
+ route at `/admin`.
99
+ - **To answer with your site's own page for a missing path,** the one
100
+ in `public/404.html`, give it as `missing`:
101
+
102
+ ```ruby
103
+ nothing_here = ActionDispatch::PublicExceptions.new(Rails.public_path)
104
+ Rails.application.config.middleware.use SitePaths::Wall,
105
+ under: "/admin",
106
+ allow: ->(env) { env.dig("rack.session", "role") == "staff" },
107
+ missing: ->(env) { nothing_here.call(env.merge("PATH_INFO" => "/404")) }
108
+ ```
109
+
110
+ - **Where your staff sign in** has to be outside the part, or let in by
111
+ `allow` for everybody: nobody can sign in at a page they are kept
112
+ from.
113
+
114
+ ## Sinatra
115
+
116
+ ```ruby
117
+ require "site_paths"
118
+
119
+ use SitePaths::Wall, under: "/admin", allow: ->(env) { env.dig("rack.session", "role") == "staff" }
120
+ ```
121
+
122
+ Sinatra runs what is given to `use` after its own middleware, the
123
+ session's among it, and before its routes. With sessions on, Sinatra
124
+ itself answers every request with a session cookie, whether a wall
125
+ keeps the caller out or not. Sinatra's own page for a path it does not
126
+ have, as a deployment gives it, is this:
127
+
128
+ ```ruby
129
+ missing: ->(_env) { [404, { "content-type" => "text/html;charset=utf-8" }, ["<h1>Not Found</h1>"]] }
130
+ ```
131
+
132
+ Sinatra's own answer carries one header more, `x-cascade`, by which it
133
+ passes a request it does not know on to another application. A wall's
134
+ answer does not: a request that is kept out is passed on to nobody.
135
+
136
+ ## Rack
137
+
138
+ A wall goes around everything that finds routes. Where Rack tries one
139
+ application after another (`Rack::Cascade`), it goes around all of
140
+ them: Rack tries the next application where one answers `404`, which is
141
+ what a wall answers.
142
+
143
+ ## What it hides, and what it does not
144
+
145
+ A wall hides which routes its part has. It does not hide that a part is
146
+ kept: what a caller who is kept out gets says `cache-control: private,
147
+ no-store`, so that a cache between does not give it to whoever asks
148
+ next, the staff among them, and your site's own `404` may say
149
+ otherwise. The check notes that with a warning and does not fail for
150
+ it. If that matters to you, have your site's page for a missing path
151
+ say the same of caches, and give that page as `missing`.
152
+
153
+ Your answers to the staff are yours to keep from caches, with
154
+ `cache-control: private` or `no-store`. A cache in front of the site
155
+ that keeps one gives it to whoever asks next, and never asks the wall.
156
+
157
+ ## Options
158
+
159
+ | Option | |
160
+ | --- | --- |
161
+ | `under` | The start of the part, as a visitor asks for it: the path itself and everything below it, however a request spells it. `/` is the whole site |
162
+ | `match` | A pattern for the paths that are kept, in place of `under`: `%r{\A/(en\|de)/admin(/\|\z)}` for a part under each language. It is given a second for a path unless it has a time limit of its own (`Regexp.new(source, timeout: 2)`): a path it runs out of time on is kept |
163
+ | `allow` | Your decision, called with the request's environment. Only `true` itself lets a caller in: anything else keeps the caller out, and so does whatever goes wrong in it, a mistake too. What went wrong is written to `rack.errors`, where your server writes what goes wrong. It is not cut short, so give what it asks a time limit of its own |
164
+ | `missing` | A Rack application that answers a caller who is kept out, in place of the plain `404`. It is called with the request's environment as it came, and is not your site: nothing that is kept out is passed on to it. Where it fails or answers with no response Rack takes, the plain `404` is answered, and what went wrong is written as for `allow` |
165
+
166
+ A wall cannot be made with no part or two, with a start or a pattern
167
+ that names nothing, or with no `allow`: a wall that keeps nothing, or
168
+ everything by a setting that was not made, is not one to find out
169
+ about later.
170
+
171
+ ## How a path is read
172
+
173
+ A wall keeps a path that stands in its part at any point as it is read,
174
+ segment by segment, and not only where it ends: `/admin/../users` is
175
+ kept by a wall under `/admin`, since a server that does not resolve
176
+ dots finds a route by it. Escapes are decoded, a backslash or a doubled
177
+ slash is one slash, what follows a semicolon in a segment is left out,
178
+ and the letters A to Z are made small. A path of more than 64 segments
179
+ is kept by every wall. `SitePaths.plain` gives a path as it is read.
180
+
181
+ An application mounted below another keeps its part whether `under`
182
+ names it from the top of the site or from where the application is
183
+ mounted.
184
+
185
+ The reading is held to the two lists in
186
+ [`vectors`](https://github.com/webodik/toller-web/tree/main/vectors),
187
+ which the walls for every language share.
188
+
189
+ ## What it was tried on
190
+
191
+ Ruby 3.3, 3.4 and 4.0. Rails 8.1 and Sinatra 4, each behind Puma and
192
+ asked by the check as a stranger, a customer and the staff, who sign in
193
+ to the framework's own session: without the wall the check fails, with
194
+ it the check passes. Every answer of a wall is held to what Rack 3 asks
195
+ of one. It was not put behind nginx or a CDN here, and not before an
196
+ application that is an API only.
197
+
198
+ ## License
199
+
200
+ Apache-2.0: see `LICENSE`.
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SitePaths
4
+ # The part of a site that a wall keeps.
5
+ class Part
6
+ # Seconds a pattern is given for a path where it is given none of its
7
+ # own: a path it runs out of time on is kept.
8
+ PATIENCE = 1.0
9
+
10
+ # `under` is the start of the part: the path itself and everything
11
+ # below it, however a request spells it; `/` is the whole of a site.
12
+ # `match` is a pattern for the paths that are kept, in its place,
13
+ # tried on every place a path stands at, in its plain form.
14
+ def initialize(under: nil, match: nil)
15
+ raise ArgumentError, "a wall keeps what is under a path, or what fits a pattern" if under.nil? == match.nil?
16
+ # A setting that was read from nowhere is an empty one, and would
17
+ # keep the whole of a site.
18
+ raise ArgumentError, "the start of a wall's part names nothing: the whole of a site is `/`" if under && under.to_s.strip.empty?
19
+
20
+ @base = under && Paths.read(under.to_s).plain.chomp("/")
21
+ @pattern = match && pattern_of(match)
22
+ end
23
+
24
+ # Whether a request is in the part: its path stands there at some
25
+ # point, in some spelling of it, or is deeper than a path is read.
26
+ # Mostly the spellings are one, and it is read once.
27
+ def covers?(spellings)
28
+ spellings.uniq.any? do |spelled|
29
+ read = Paths.read(spelled, whole: false)
30
+ read.deep || read.stood.any? { |place| holds?(place) }
31
+ end
32
+ end
33
+
34
+ private
35
+
36
+ # A pattern of the owner's, with a time it may take.
37
+ def pattern_of(match)
38
+ raise ArgumentError, "the pattern of a wall is a Regexp, or the text of one" unless match.is_a?(Regexp) || match.is_a?(String)
39
+
40
+ source = match.is_a?(Regexp) ? match.source : match
41
+ # An empty pattern fits every path, and is what a setting that was
42
+ # read from nowhere gives.
43
+ raise ArgumentError, "the pattern of a wall names nothing: the whole of a site is `under: \"/\"`" if source.strip.empty?
44
+ # A pattern with a time of its own, or of every pattern's, is
45
+ # taken as it is: a copy of one has no such limit.
46
+ return match if match.is_a?(Regexp) && (match.timeout || Regexp.timeout)
47
+
48
+ Regexp.new(source, match.is_a?(Regexp) ? match.options : 0, timeout: PATIENCE)
49
+ end
50
+
51
+ def holds?(place)
52
+ return @pattern.match?(place) if @pattern
53
+ return true if place == @base || place.start_with?("#{@base}/")
54
+
55
+ # The start of the part with the name of a format after it is the
56
+ # route at the start of the part to a framework that takes such a
57
+ # name after any route, as Rails takes /admin.json for /admin.
58
+ format = place.start_with?("#{@base}.") ? place[(@base.length + 1)..] : ""
59
+ !format.empty? && !format.match?(%r{[./]})
60
+ rescue Regexp::TimeoutError
61
+ # A pattern that was given no more time says neither that the
62
+ # place fits nor that it does not, and the place is kept.
63
+ true
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SitePaths
4
+ # How a path is read.
5
+ #
6
+ # A wall compares a request's path with the part it keeps. Servers read
7
+ # a path in more than one way, so the path is read as the most forgiving
8
+ # of them would: escapes decoded, a backslash or a doubled slash as one
9
+ # slash, what follows a semicolon in a segment left out, dots resolved,
10
+ # the letters A to Z made small. Some servers take what follows a
11
+ # semicolon for parameters of the segment and find the route without
12
+ # them.
13
+ #
14
+ # The reading is held to two lists that every implementation of it
15
+ # shares, in `vectors` at the top of the repository.
16
+ module Paths
17
+ # The most segments a path is read to. No site has a page deeper, and
18
+ # reading on would cost time that whoever writes a long address
19
+ # decides.
20
+ DEEPEST = 64
21
+
22
+ # A path as it was read: its plain form; every place it stands at on
23
+ # the way there, each the plain form of a start of it, and its plain
24
+ # form last; and whether it has more segments than are read. A server
25
+ # that does not resolve dots finds a route by the path as it is
26
+ # written, so /admin/../users stands in /admin to that server though
27
+ # its plain form is /users.
28
+ Reading = Struct.new(:plain, :stood, :deep)
29
+
30
+ module_function
31
+
32
+ # Reads a path as it was asked for, escapes and all. A wall asks only
33
+ # where a path stands and whether it is deeper than paths are read:
34
+ # with `whole` false no more of a path is read than says that.
35
+ def read(path, whole: true)
36
+ # The path's bytes: an escape is the byte it names. Bytes that are
37
+ # no letter read as the mark for one.
38
+ bytes = path.b.gsub(/%(\h\h)/n) { Regexp.last_match(1).hex.chr }
39
+ merged = bytes.force_encoding(Encoding::UTF_8).scrub("�").tr("\\", "/").downcase(:ascii)
40
+ ends_in_slash = merged.end_with?("/")
41
+ slash = ends_in_slash
42
+ # Where the path stands so far. It is added to as it is, and not
43
+ # written anew at each segment, so that a long path costs no more
44
+ # than its length.
45
+ place = +""
46
+ stood = []
47
+ segments = 0
48
+ merged.scan(%r{[^/]+}) do |segment|
49
+ piece = segment.split(";", 2).first.to_s
50
+ next if piece.empty?
51
+
52
+ segments += 1
53
+ break if !whole && segments > DEEPEST
54
+
55
+ if [".", ".."].include?(piece)
56
+ place.slice!((place.rindex("/") || 0)..) if piece == ".."
57
+ slash = true
58
+ next
59
+ end
60
+ place << "/" << piece
61
+ stood << place.dup if segments <= DEEPEST
62
+ slash = ends_in_slash
63
+ end
64
+ plain = if place.empty? then "/" elsif slash then "#{place}/" else place.dup end
65
+ stood << plain unless stood.last == plain
66
+ Reading.new(plain, stood, segments > DEEPEST)
67
+ end
68
+
69
+ # A path that a server has decoded already, as one that is read once.
70
+ # A percent sign in it is a percent sign that was asked for, and not
71
+ # the start of an escape: reading it as one would decode twice.
72
+ def decoded_once(path)
73
+ path.b.gsub("%", "%25")
74
+ end
75
+
76
+ # The path of an address as it was sent, where it has one. A proxy is
77
+ # asked with the whole address; what is no address, as the `*` of
78
+ # OPTIONS, has no path to read.
79
+ def sent(target)
80
+ # As bytes: a server may say that an address is letters where it
81
+ # holds bytes that are none.
82
+ path = target.to_s.b.split("?", 2).first.to_s
83
+ return path if path.start_with?("/")
84
+
85
+ after = path.split("://", 2)[1]
86
+ "/#{after.split("/", 2)[1]}" if after
87
+ end
88
+ end
89
+
90
+ # A path as the most forgiving server would read it.
91
+ def self.plain(path)
92
+ Paths.read(path).plain
93
+ end
94
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SitePaths
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SitePaths
4
+ # A wall for Rack: Rails, Sinatra and whatever else speaks it.
5
+ #
6
+ # use SitePaths::Wall, under: "/admin", allow: ->(env) { env["rack.session"]["role"] == "staff" }
7
+ #
8
+ # Put it where it runs after whatever says who is signed in and before
9
+ # the routes are looked up. In Rails that is the end of the middleware:
10
+ # `config.middleware.use SitePaths::Wall, ...`.
11
+ #
12
+ # `under`, or `match` in its place, says which part.
13
+ #
14
+ # `allow` is the site's own decision: called with the request's
15
+ # environment, it answers `true` for a caller who is let in. Anything
16
+ # else, and whatever goes wrong in it, mean that the caller is not;
17
+ # what went wrong is written to the request's error stream. It is not
18
+ # cut short: give what it asks a time of its own to answer in.
19
+ #
20
+ # `missing` answers a caller who is kept out, in place of the wall's
21
+ # own bare 404: a Rack application that answers with the site's page
22
+ # for a path it does not have. It is called with the request's
23
+ # environment as it came, and is not the site: nothing that is kept out
24
+ # is passed on to the site. Where it fails or answers with no response,
25
+ # the bare 404 is answered, and what went wrong is written as for
26
+ # `allow`.
27
+ #
28
+ # Whatever answers, the answer says that no cache may keep it.
29
+ class Wall
30
+ # What every answer to a caller who is kept out says of caches,
31
+ # whoever made the answer: no cache between may keep it. It would be
32
+ # given to whoever asks next, the staff among them.
33
+ KEPT_BY_NO_CACHE = "private, no-store"
34
+
35
+ # The wall's own answer for a caller who is kept out.
36
+ NOTHING_THERE = "Not Found\n"
37
+
38
+ def initialize(app, allow:, under: nil, match: nil, missing: nil)
39
+ raise ArgumentError, "a wall needs the site's own decision of who is let in" unless allow.respond_to?(:call)
40
+ unless missing.nil? || missing.respond_to?(:call)
41
+ raise ArgumentError, "what answers a caller who is kept out is called, and is no path: a wall passes nothing that is kept out on to the site"
42
+ end
43
+
44
+ @app = app
45
+ @part = Part.new(under: under, match: match)
46
+ @allow = allow
47
+ @missing = missing
48
+ end
49
+
50
+ def call(env)
51
+ return @app.call(env) if !@part.covers?(spellings(env)) || allows?(env)
52
+
53
+ status, headers, body = own_answer(env) || bare(env)
54
+ # Whoever made the answer, no cache between may keep it.
55
+ [status, headers.merge("cache-control" => KEPT_BY_NO_CACHE), body]
56
+ end
57
+
58
+ private
59
+
60
+ # A request's path as it was sent, and as the server passes it on. A
61
+ # server passes it on as it was written or decoded once: which,
62
+ # depends on the server. An application that is mounted below another
63
+ # is passed the rest of the path, and its owner may name a part from
64
+ # the top of the site or from where the application is mounted. Each
65
+ # is a reading. They are read as bytes: a server may say of one that
66
+ # it is letters and of another that it is not.
67
+ def spellings(env)
68
+ script = env["SCRIPT_NAME"].to_s.b
69
+ info = env["PATH_INFO"].to_s.b
70
+ sent = [env["REQUEST_URI"], env["REQUEST_PATH"]].filter_map { |target| Paths.sent(target) }
71
+ spelled = [script + info, Paths.decoded_once(script + info), *sent]
72
+ unless script.empty?
73
+ spelled.push(info, Paths.decoded_once(info))
74
+ sent.each { |one| spelled << (one.delete_prefix(script).then { |rest| rest.empty? ? "/" : rest }) if one.start_with?(script) }
75
+ end
76
+ spelled
77
+ end
78
+
79
+ # Asks the site's own decision. Only true itself lets a caller in,
80
+ # and nothing that says it is equal to true.
81
+ def allows?(env)
82
+ true.equal?(@allow.call(env))
83
+ rescue StandardError => failed
84
+ report(env, failed)
85
+ false
86
+ end
87
+
88
+ # What the site's own application answers a caller who is kept out
89
+ # with, where one is given and it answers as Rack asks: a status, the
90
+ # headers, and a body that is read piece by piece or called. The
91
+ # names of the headers are made small, as Rack asks them to be.
92
+ def own_answer(env)
93
+ return unless @missing
94
+
95
+ status, headers, body = answer = @missing.call(env)
96
+ if answer.is_a?(Array) && answer.size == 3 && status.is_a?(Integer) && status >= 100 && (body.respond_to?(:each) || body.respond_to?(:call))
97
+ return [status, headers.to_h.transform_keys { |name| name.to_s.downcase }.except("cache-control"), body]
98
+ end
99
+
100
+ body.close if answer.is_a?(Array) && body.respond_to?(:close)
101
+ raise TypeError, "what answers a caller who is kept out answered with no response: #{answer.inspect[0, 80]}"
102
+ rescue StandardError => failed
103
+ report(env, failed)
104
+ nil
105
+ end
106
+
107
+ def bare(env)
108
+ headers = { "content-type" => "text/plain; charset=utf-8", "content-length" => NOTHING_THERE.bytesize.to_s }
109
+ [404, headers, env["REQUEST_METHOD"] == "HEAD" ? [] : [NOTHING_THERE]]
110
+ end
111
+
112
+ # Writes what went wrong in the owner's code where the server writes
113
+ # what goes wrong, so that a mistake there does not keep the staff
114
+ # out unseen. Whatever goes wrong in writing it changes nothing.
115
+ def report(env, failed)
116
+ (env["rack.errors"] || $stderr).puts("A wall went on without its owner's code, which failed: #{failed.class}: #{failed.message} (#{failed.backtrace&.first})")
117
+ rescue StandardError
118
+ nil
119
+ end
120
+ end
121
+ end
data/lib/site_paths.rb ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Keeps a part of a site from whoever the site does not let in.
4
+ #
5
+ # Most sites answer one way for a private route that exists and another
6
+ # for one that does not, so anybody can list what a site has by asking.
7
+ # A wall asks the site's own decision before a route is looked up, and
8
+ # answers every path of the part alike, there or not, for whoever is not
9
+ # let in.
10
+ #
11
+ # use SitePaths::Wall, under: "/admin", allow: ->(env) { staff?(env) }
12
+ #
13
+ # Whether a deployment keeps its part is asked from outside by the one
14
+ # check there is, `site-paths-check` of the package `site-paths` at npm,
15
+ # which asks a site written in anything.
16
+ module SitePaths
17
+ end
18
+
19
+ require_relative "site_paths/version"
20
+ require_relative "site_paths/paths"
21
+ require_relative "site_paths/part"
22
+ require_relative "site_paths/wall"
metadata ADDED
@@ -0,0 +1,48 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: site_paths
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Bodik
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ executables: []
13
+ extensions: []
14
+ extra_rdoc_files: []
15
+ files:
16
+ - LICENSE
17
+ - README.md
18
+ - lib/site_paths.rb
19
+ - lib/site_paths/part.rb
20
+ - lib/site_paths/paths.rb
21
+ - lib/site_paths/version.rb
22
+ - lib/site_paths/wall.rb
23
+ homepage: https://github.com/webodik/toller-web
24
+ licenses:
25
+ - Apache-2.0
26
+ metadata:
27
+ source_code_uri: https://github.com/webodik/toller-web/tree/main/ruby
28
+ bug_tracker_uri: https://github.com/webodik/toller-web/issues
29
+ rubygems_mfa_required: 'true'
30
+ rdoc_options: []
31
+ require_paths:
32
+ - lib
33
+ required_ruby_version: !ruby/object:Gem::Requirement
34
+ requirements:
35
+ - - ">="
36
+ - !ruby/object:Gem::Version
37
+ version: '3.3'
38
+ required_rubygems_version: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '0'
43
+ requirements: []
44
+ rubygems_version: 3.6.9
45
+ specification_version: 4
46
+ summary: 'Stop a site from telling strangers which private routes exist: a wall for
47
+ Rack (Rails, Sinatra). No dependencies.'
48
+ test_files: []