-
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathauthorization_path_e2e_test.go
More file actions
186 lines (181 loc) 路 5.51 KB
/
Copy pathauthorization_path_e2e_test.go
File metadata and controls
186 lines (181 loc) 路 5.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Copyright 2022 Paul Greenberg greenpau@outlook.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package security
import (
"context"
"crypto/tls"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"testing"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
)
func TestCaddyAuthorizationPathE2E(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestCaddyAuthorizationPathProcess$", "-test.v", "-test.timeout=50s")
cmd.Env = append(os.Environ(), "CADDY_SECURITY_AUTHORIZATION_PATH_CHILD=1")
collectSubprocessCoverage(t, cmd)
cmd.WaitDelay = 5 * time.Second
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Caddy TLS path authorization: %v\n%s", err, output)
}
}
func TestCaddyAuthorizationPathProcess(t *testing.T) {
if os.Getenv("CADDY_SECURITY_AUTHORIZATION_PATH_CHILD") != "1" {
t.Skip("subprocess helper")
}
t.Setenv("XDG_DATA_HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cert, key, roots := cookieTLSCertificate(t)
base := "https://" + lifecycleAddress(t)
input := fmt.Sprintf(`{
admin off
persist_config off
auto_https off
log {
level ERROR
}
security {
authorization policy bypass {
crypto key verify %[1]s
disable auth redirect
allow roles viewer
bypass uri prefix /public/
}
authorization policy method {
crypto key verify %[1]s
disable auth redirect
validate bearer header
acl rule {
prefix match path /admin
deny stop
}
allow roles viewer with GET to /public/
}
authorization policy claim {
crypto key verify %[1]s
disable auth redirect
validate bearer header
validate path acl
allow roles viewer
}
}
}
%[2]s {
tls %[3]q %[4]q
@bypass header X-Test-Policy bypass
@method header X-Test-Policy method
@claim header X-Test-Policy claim
route {
route @bypass {
authorize with bypass
}
route @method {
authorize with method
}
route @claim {
authorize with claim
}
header X-Path-Reached yes
respond "{http.request.uri}" 200
}
}`, authorizationPathKey, base, cert, key)
data, _, err := caddyconfig.GetAdapter("caddyfile").Adapt([]byte(input), nil)
if err != nil {
t.Fatal(err)
}
if err := caddy.Load(data, true); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := caddy.Stop(); err != nil {
t.Error(err)
}
})
for _, http2 := range []bool{false, true} {
t.Run(fmt.Sprintf("http2=%t", http2), func(t *testing.T) {
transport := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}, ForceAttemptHTTP2: http2}
t.Cleanup(transport.CloseIdleConnections)
client := &http.Client{Transport: transport, Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
request := func(t *testing.T, mode, token, target string, allow bool) {
t.Helper()
r, err := http.NewRequestWithContext(t.Context(), "GET", base+target, nil)
if err != nil {
t.Fatal(err)
}
r.Header.Set("X-Test-Policy", mode)
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
}
response, err := client.Do(r)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
body, err := io.ReadAll(io.LimitReader(response.Body, 1<<16))
if err != nil {
t.Fatal(err)
}
want := http.StatusForbidden
if mode == "bypass" {
want = http.StatusUnauthorized
}
if allow {
want = http.StatusOK
}
if response.StatusCode != want || (response.Header.Get("X-Path-Reached") == "yes") != allow {
t.Fatalf("%s %s: status=%d reached=%t, want status=%d", mode, target, response.StatusCode, response.Header.Get("X-Path-Reached") == "yes", want)
}
if allow && string(body) != target {
t.Fatal("authorization changed the downstream URI")
}
if response.TLS == nil || len(response.TLS.VerifiedChains) == 0 || (response.ProtoMajor == 2) != http2 {
t.Fatal("request did not use verified TLS and the selected HTTP protocol")
}
}
for _, mode := range []string{"bypass", "method", "claim"} {
t.Run(mode, func(t *testing.T) {
token := authorizationPathToken(t, "/public/**", "/public/100%")
if mode == "bypass" {
token = ""
}
for round := range 2 {
for _, tc := range authorizationPathCases() {
t.Run(fmt.Sprintf("%d%s", round, tc.target), func(t *testing.T) { request(t, mode, token, tc.target, tc.allow) })
}
}
})
}
for _, tc := range []struct{ pattern, allowed, denied string }{
{"/tenant.v1/**", "/tenant.v1/file", "/tenantXv1/file"},
{"/public/**|/admin", "/public/file%7C/admin", "/admin"},
{"/public/(admin)/*", "/public/(admin)/file", "/public/admin/file"},
} {
t.Run(tc.pattern, func(t *testing.T) {
t.Parallel()
token := authorizationPathToken(t, tc.pattern)
for range 2 {
request(t, "claim", token, tc.denied, false)
request(t, "claim", token, tc.allowed, true)
}
})
}
})
}
}