File
Blob: tun/server/waf_rpc_test.go
| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "go.miragespace.co/specter/spec/protocol" |
| 14 | "go.miragespace.co/specter/spec/tun" |
| 15 | "go.miragespace.co/specter/waf" |
| 16 | |
| 17 | "github.com/stretchr/testify/mock" |
| 18 | "github.com/stretchr/testify/require" |
| 19 | "github.com/twitchtv/twirp" |
| 20 | ) |
| 21 | |
| 22 | func TestHostWAFPolicyOwnershipAndVersion(t *testing.T) { |
| 23 | s, n, _, cert := sessionFixture(t) |
| 24 | ctx, _ := sessionContext(t, cert) |
| 25 | owner, _, err := extractAuthenticated(ctx) |
| 26 | require.NoError(t, err) |
| 27 | hostname := "owned-host" |
| 28 | key := []byte(tun.HostWAFKey(hostname)) |
| 29 | prefix := []byte(tun.ClientHostnamesPrefix(owner)) |
| 30 | lease := []byte(tun.ClientLeaseKey(owner)) |
| 31 | n.On("PrefixContains", mock.Anything, prefix, []byte(hostname)).Return(true, nil).Times(4) |
| 32 | n.On("Acquire", mock.Anything, lease, mock.Anything).Return(uint64(1), nil).Twice() |
| 33 | n.On("Release", mock.Anything, lease, uint64(1)).Return(nil).Twice() |
| 34 | n.On("Get", mock.Anything, key).Return(nil, nil).Times(3) |
| 35 | |
| 36 | // Successful absence is reusable, but saving an override invalidates it. |
| 37 | policy, err := s.WAFPolicy(ctx, hostname) |
| 38 | require.NoError(t, err) |
| 39 | require.Equal(t, protocol.WAFPolicy_INHERIT, policy.Mode) |
| 40 | policy, err = s.WAFPolicy(ctx, hostname) |
| 41 | require.NoError(t, err) |
| 42 | require.Equal(t, protocol.WAFPolicy_INHERIT, policy.Mode) |
| 43 | |
| 44 | initial, err := s.GetHostWAF(ctx, &protocol.GetHostWAFRequest{Hostname: hostname}) |
| 45 | require.NoError(t, err) |
| 46 | require.Empty(t, initial.Version) |
| 47 | require.Equal(t, protocol.WAFPolicy_INHERIT, initial.Policy.Mode) |
| 48 | var saved []byte |
| 49 | n.On("Put", mock.Anything, key, mock.Anything).Run(func(args mock.Arguments) { |
| 50 | saved = append([]byte(nil), args.Get(2).([]byte)...) |
| 51 | }).Return(nil).Once() |
| 52 | updated, err := s.SetHostWAF(ctx, &protocol.SetHostWAFRequest{ |
| 53 | Hostname: hostname, Policy: &protocol.WAFPolicy{Mode: protocol.WAFPolicy_OFF}, |
| 54 | }) |
| 55 | require.NoError(t, err) |
| 56 | require.NotEmpty(t, updated.Version) |
| 57 | n.On("Get", mock.Anything, key).Return(saved, nil).Twice() |
| 58 | policy, err = s.WAFPolicy(ctx, hostname) |
| 59 | require.NoError(t, err) |
| 60 | require.Equal(t, protocol.WAFPolicy_OFF, policy.Mode) |
| 61 | _, err = s.SetHostWAF(ctx, &protocol.SetHostWAFRequest{ |
| 62 | Hostname: hostname, Policy: &protocol.WAFPolicy{Mode: protocol.WAFPolicy_MONITOR}, |
| 63 | }) |
| 64 | require.Equal(t, twirp.FailedPrecondition, err.(twirp.Error).Code()) |
| 65 | |
| 66 | // Unavailable ownership checks use the operator default, never cached Off. |
| 67 | n.On("PrefixContains", mock.Anything, prefix, []byte(hostname)).Return(false, errors.New("storage unavailable")).Once() |
| 68 | policy, err = s.WAFPolicy(ctx, hostname) |
| 69 | require.NoError(t, err) |
| 70 | require.Equal(t, protocol.WAFPolicy_INHERIT, policy.Mode) |
| 71 | |
| 72 | // A saved exception loses authority when the hostname leaves its owner, |
| 73 | // even when its policy data is cached. |
| 74 | n.On("PrefixContains", mock.Anything, prefix, []byte(hostname)).Return(false, nil).Once() |
| 75 | policy, err = s.WAFPolicy(ctx, hostname) |
| 76 | require.NoError(t, err) |
| 77 | require.Equal(t, protocol.WAFPolicy_INHERIT, policy.Mode) |
| 78 | n.AssertExpectations(t) |
| 79 | } |
| 80 | |
| 81 | func TestHostWAFCacheExpiryAndErrors(t *testing.T) { |
| 82 | _, n, _, _, s := getFixture(t, require.New(t)) |
| 83 | s.Chord, s.ParentContext = n, t.Context() |
| 84 | hostname := "test" |
| 85 | key := []byte(tun.HostWAFKey(hostname)) |
| 86 | previous := &protocol.HostWAFRecord{Schema: 1, Owner: []byte("owner"), Policy: &protocol.WAFPolicy{Mode: protocol.WAFPolicy_OFF}} |
| 87 | // An expired Off policy must not mask a failed refresh. |
| 88 | require.True(t, s.hostWAFCache.SetWithTTL(hostname, &hostWAFCacheEntry{ |
| 89 | record: previous, expiresAt: time.Now().Add(-time.Second), |
| 90 | }, 512, hostWAFCacheTTL)) |
| 91 | unavailable := errors.New("storage unavailable") |
| 92 | n.On("Get", mock.Anything, key).Return(nil, unavailable).Once() |
| 93 | policy, err := s.WAFPolicy(t.Context(), hostname) |
| 94 | require.NoError(t, err) |
| 95 | require.Equal(t, protocol.WAFPolicy_INHERIT, policy.Mode) |
| 96 | |
| 97 | cancelled, cancel := context.WithCancel(t.Context()) |
| 98 | cancel() |
| 99 | _, err = s.WAFPolicy(cancelled, hostname) |
| 100 | require.ErrorIs(t, err, context.Canceled) |
| 101 | |
| 102 | n.On("Get", mock.Anything, key).Return([]byte(`{"schema":2,"owner":"b3duZXI=","policy":{"mode":"INHERIT"}}`), nil).Once() |
| 103 | _, err = s.WAFPolicy(t.Context(), hostname) |
| 104 | require.ErrorContains(t, err, "unsupported saved WAF policy") |
| 105 | |
| 106 | // Failed reads must not be cached as absence. |
| 107 | n.On("Get", mock.Anything, key).Return(nil, nil).Once() |
| 108 | policy, err = s.WAFPolicy(t.Context(), hostname) |
| 109 | require.NoError(t, err) |
| 110 | require.Equal(t, protocol.WAFPolicy_INHERIT, policy.Mode) |
| 111 | n.AssertExpectations(t) |
| 112 | } |
| 113 | |
| 114 | func TestHostWAFPreviousOwnerAndCustomAuthority(t *testing.T) { |
| 115 | s, n, _, cert := sessionFixture(t) |
| 116 | ctx, _ := sessionContext(t, cert) |
| 117 | owner, client, err := extractAuthenticated(ctx) |
| 118 | require.NoError(t, err) |
| 119 | hostname := "app.example.com" |
| 120 | previousOwner := &protocol.ClientToken{Token: []byte("previous-owner")} |
| 121 | data, err := waf.MarshalJSON(&protocol.HostWAFRecord{Schema: 1, Owner: previousOwner.Token, Policy: &protocol.WAFPolicy{Mode: protocol.WAFPolicy_OFF}}) |
| 122 | require.NoError(t, err) |
| 123 | custom, err := (&protocol.CustomHostname{ClientIdentity: client, ClientToken: owner}).MarshalVT() |
| 124 | require.NoError(t, err) |
| 125 | n.On("PrefixContains", mock.Anything, []byte(tun.ClientHostnamesPrefix(owner)), []byte(hostname)).Return(true, nil).Once() |
| 126 | n.On("Get", mock.Anything, []byte(tun.CustomHostnameKey(hostname))).Return(custom, nil).Twice() |
| 127 | n.On("Get", mock.Anything, []byte(tun.HostWAFKey(hostname))).Return(data, nil).Twice() |
| 128 | response, err := s.GetHostWAF(ctx, &protocol.GetHostWAFRequest{Hostname: hostname}) |
| 129 | require.NoError(t, err) |
| 130 | require.Empty(t, response.Version) |
| 131 | require.Equal(t, protocol.WAFPolicy_INHERIT, response.Policy.Mode) |
| 132 | |
| 133 | // Even a leftover registration prefix cannot override the current custom |
| 134 | // hostname owner. |
| 135 | n.On("PrefixContains", mock.Anything, []byte(tun.ClientHostnamesPrefix(previousOwner)), []byte(hostname)).Return(true, nil).Once() |
| 136 | policy, err := s.WAFPolicy(ctx, hostname) |
| 137 | require.NoError(t, err) |
| 138 | require.Equal(t, protocol.WAFPolicy_INHERIT, policy.Mode) |
| 139 | n.AssertExpectations(t) |
| 140 | } |
| 141 | |
| 142 | func TestHostWAFRejectsOtherOwners(t *testing.T) { |
| 143 | for _, hostname := range []string{"unowned-label", "app.example.com"} { |
| 144 | t.Run(hostname, func(t *testing.T) { |
| 145 | s, n, _, cert := sessionFixture(t) |
| 146 | ctx, _ := sessionContext(t, cert) |
| 147 | owner, _, err := extractAuthenticated(ctx) |
| 148 | require.NoError(t, err) |
| 149 | custom := strings.Contains(hostname, ".") |
| 150 | n.On("PrefixContains", mock.Anything, []byte(tun.ClientHostnamesPrefix(owner)), []byte(hostname)).Return(custom, nil).Twice() |
| 151 | if custom { |
| 152 | data, err := (&protocol.CustomHostname{ClientToken: &protocol.ClientToken{Token: []byte("another-owner")}}).MarshalVT() |
| 153 | require.NoError(t, err) |
| 154 | n.On("Get", mock.Anything, []byte(tun.CustomHostnameKey(hostname))).Return(data, nil).Twice() |
| 155 | } |
| 156 | lease := []byte(tun.ClientLeaseKey(owner)) |
| 157 | n.On("Acquire", mock.Anything, lease, mock.Anything).Return(uint64(1), nil).Once() |
| 158 | n.On("Release", mock.Anything, lease, uint64(1)).Return(nil).Once() |
| 159 | _, err = s.GetHostWAF(ctx, &protocol.GetHostWAFRequest{Hostname: hostname}) |
| 160 | require.Equal(t, twirp.PermissionDenied, err.(twirp.Error).Code()) |
| 161 | _, err = s.SetHostWAF(ctx, &protocol.SetHostWAFRequest{Hostname: hostname, Policy: &protocol.WAFPolicy{Mode: protocol.WAFPolicy_OFF}}) |
| 162 | require.Equal(t, twirp.PermissionDenied, err.(twirp.Error).Code()) |
| 163 | n.AssertNotCalled(t, "Put", mock.Anything, mock.Anything, mock.Anything) |
| 164 | n.AssertExpectations(t) |
| 165 | }) |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | func TestHostWAFRPCRejectsUnknownModes(t *testing.T) { |
| 170 | s, n, _, cert := sessionFixture(t) |
| 171 | ctx, _ := sessionContext(t, cert) |
| 172 | handler := protocol.NewTunnelServiceServer(s) |
| 173 | for _, mode := range []string{`"FUTURE_MODE"`, `99`, `0`} { |
| 174 | t.Run(mode, func(t *testing.T) { |
| 175 | r := httptest.NewRequest(http.MethodPost, protocol.TunnelServicePathPrefix+"SetHostWAF", strings.NewReader(`{"hostname":"test","policy":{"mode":`+mode+`}}`)) |
| 176 | r.Header.Set("Content-Type", "application/json") |
| 177 | response := httptest.NewRecorder() |
| 178 | handler.ServeHTTP(response, r.WithContext(ctx)) |
| 179 | require.Equal(t, http.StatusBadRequest, response.Code) |
| 180 | require.Contains(t, response.Body.String(), `"code":"invalid_argument"`) |
| 181 | }) |
| 182 | } |
| 183 | n.AssertNotCalled(t, "Put", mock.Anything, mock.Anything, mock.Anything) |
| 184 | } |
| 185 | |
| 186 | func TestReleaseTunnelClearsWAFBeforeOwnership(t *testing.T) { |
| 187 | for _, fail := range []bool{false, true} { |
| 188 | name := "success" |
| 189 | if fail { |
| 190 | name = "reset fails" |
| 191 | } |
| 192 | t.Run(name, func(t *testing.T) { |
| 193 | s, n, _, cert := sessionFixture(t) |
| 194 | ctx, _ := sessionContext(t, cert) |
| 195 | owner, _, err := extractAuthenticated(ctx) |
| 196 | require.NoError(t, err) |
| 197 | hostname := "test" |
| 198 | prefix := []byte(tun.ClientHostnamesPrefix(owner)) |
| 199 | lease := []byte(tun.ClientLeaseKey(owner)) |
| 200 | n.On("Acquire", mock.Anything, lease, mock.Anything).Return(uint64(1), nil).Once() |
| 201 | n.On("Release", mock.Anything, lease, uint64(1)).Return(nil).Once() |
| 202 | n.On("PrefixContains", mock.Anything, prefix, []byte(hostname)).Return(true, nil).Once() |
| 203 | for i := range tun.NumRedundantLinks { |
| 204 | n.On("Delete", mock.Anything, []byte(tun.RoutingKey(hostname, i+1))).Return(nil).Once() |
| 205 | } |
| 206 | data, err := waf.MarshalJSON(&protocol.HostWAFRecord{Schema: 1, Owner: owner.Token, Policy: &protocol.WAFPolicy{Mode: protocol.WAFPolicy_OFF}}) |
| 207 | require.NoError(t, err) |
| 208 | n.On("Get", mock.Anything, []byte(tun.HostWAFKey(hostname))).Return(data, nil).Once() |
| 209 | var resetErr error |
| 210 | if fail { |
| 211 | resetErr = errors.New("storage unavailable") |
| 212 | } |
| 213 | reset := n.On("Delete", mock.Anything, []byte(tun.HostWAFKey(hostname))).Return(resetErr).Once() |
| 214 | if !fail { |
| 215 | n.On("PrefixRemove", mock.Anything, prefix, []byte(hostname)).Return(nil).Once().NotBefore(reset) |
| 216 | n.On("Delete", mock.Anything, []byte(tun.CustomHostnameKey(hostname))).Return(nil).Once() |
| 217 | } |
| 218 | _, err = s.ReleaseTunnel(ctx, &protocol.ReleaseTunnelRequest{Hostname: hostname}) |
| 219 | if fail { |
| 220 | require.Error(t, err) |
| 221 | n.AssertNotCalled(t, "PrefixRemove", mock.Anything, mock.Anything, mock.Anything) |
| 222 | } else { |
| 223 | require.NoError(t, err) |
| 224 | } |
| 225 | n.AssertExpectations(t) |
| 226 | }) |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | func TestHostWAFRPCBodyLimit(t *testing.T) { |
| 231 | handler := limitClientRPCBody(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 232 | if _, err := io.Copy(io.Discard, r.Body); err != nil { |
| 233 | w.WriteHeader(http.StatusRequestEntityTooLarge) |
| 234 | } |
| 235 | })) |
| 236 | for _, tc := range []struct { |
| 237 | method string |
| 238 | size int |
| 239 | status int |
| 240 | }{ |
| 241 | {"SetHostWAF", 2 << 10, http.StatusOK}, |
| 242 | {"SetHostWAF", maxHostWAFBytes + 1, http.StatusRequestEntityTooLarge}, |
| 243 | {"PublishTunnel", 2 << 10, http.StatusRequestEntityTooLarge}, |
| 244 | } { |
| 245 | r := httptest.NewRequest(http.MethodPost, protocol.TunnelServicePathPrefix+tc.method, strings.NewReader(strings.Repeat("x", tc.size))) |
| 246 | response := httptest.NewRecorder() |
| 247 | handler.ServeHTTP(response, r) |
| 248 | require.Equal(t, tc.status, response.Code) |
| 249 | } |
| 250 | } |