| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "html" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "regexp" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/home/dashboard" |
| 17 | "amadan.net/oficina/home/internal/home/sealtest" |
| 18 | "github.com/go-json-experiment/json" |
| 19 | ) |
| 20 | |
| 21 | type dashboardTransport func(*http.Request) (*http.Response, error) |
| 22 | |
| 23 | func (f dashboardTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| 24 | func dashboardTestBody(t *testing.T, v any) string { |
| 25 | t.Helper() |
| 26 | b, e := json.Marshal(v) |
| 27 | if e != nil { |
| 28 | t.Fatal(e) |
| 29 | } |
| 30 | return string(b) |
| 31 | } |
| 32 | func dashboardTestResponse(body string) *http.Response { |
| 33 | return &http.Response{StatusCode: 200, Header: http.Header{"Cache-Control": {"private, no-store"}}, Body: io.NopCloser(strings.NewReader(body))} |
| 34 | } |
| 35 | |
| 36 | func TestDashboardExchangeIsolationAndPrivacy(t *testing.T) { |
| 37 | p := newExchangePair(t) |
| 38 | credentialSession := signInFully(t, p.credential, sealtest.CanaryAddress) |
| 39 | pending, intent := p.start(t) |
| 40 | token, _ := p.mint(t, intent, credentialSession) |
| 41 | directorySession := p.finish(t, token, pending) |
| 42 | teams := []dashboardTeam{{ID: "blue", Name: "Blue", Sources: []dashboardSource{{"docs", "https://blue.docs.oficina.works"}}}, {ID: "red", Name: "Red", Sources: []dashboardSource{{"docs", "https://red.docs.oficina.works"}}}} |
| 43 | p.directory.runtime.dashboard = teams |
| 44 | p.credential.runtime.dashboard = teams |
| 45 | subject := subjectOf(t, p.credential, credentialSession) |
| 46 | calls := 0 |
| 47 | p.directory.dash.client.Transport = dashboardTransport(func(r *http.Request) (*http.Response, error) { |
| 48 | calls++ |
| 49 | if r.URL.Host != "red.docs.oficina.works" { |
| 50 | t.Error("crossed selected team") |
| 51 | } |
| 52 | c, e := dashboard.Verify(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), Origin, "https://red.docs.oficina.works", directoryOrigin, "red", p.credential.runtime.keys, time.Now()) |
| 53 | if e != nil || c.Subject != subject { |
| 54 | t.Error("invalid source authority") |
| 55 | } |
| 56 | return dashboardTestResponse(dashboardTestBody(t, dashboard.Response{Version: 1, Team: "red", Kind: "documents", Items: []dashboard.Item{{ID: "one", Title: "Dashboard private title <script>", URL: "https://red.docs.oficina.works/d/private-canary", Updated: time.Now()}}})), nil |
| 57 | }) |
| 58 | start := exchangeRequest(p.directory, "GET", directoryOrigin+"/?team=red", "", nil, directorySession) |
| 59 | if start.Code != 303 { |
| 60 | t.Fatal("start", start.Code) |
| 61 | } |
| 62 | nonce := namedCookie(t, start, dashboardCookie) |
| 63 | preference := namedCookie(t, start, dashboardTeamCookie) |
| 64 | begin := exchangeRequest(p.credential.App, "GET", start.Header().Get("Location"), "", nil) |
| 65 | dashboardIntent := namedCookie(t, begin, dashboardIntentCookie) |
| 66 | unsigned := exchangeRequest(p.credential.App, "GET", Origin+"/dashboard/resume", "", nil, dashboardIntent) |
| 67 | if unsigned.Code != 303 { |
| 68 | t.Fatal("missing sign-in gate", unsigned.Code) |
| 69 | } |
| 70 | signin := exchangeRequest(p.credential.App, "GET", Origin+unsigned.Header().Get("Location"), "", nil, dashboardIntent) |
| 71 | if namedCookie(t, signin, returnCookie).Value != "/dashboard/resume" { |
| 72 | t.Fatal("lost sign-in return") |
| 73 | } |
| 74 | minted := exchangeRequest(p.credential.App, "GET", Origin+"/dashboard/resume", "", nil, dashboardIntent, credentialSession) |
| 75 | if minted.Code != 200 { |
| 76 | t.Fatal("mint", minted.Code) |
| 77 | } |
| 78 | m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(minted.Body.String()) |
| 79 | if len(m) != 2 { |
| 80 | t.Fatal("no form") |
| 81 | } |
| 82 | form := url.Values{"assertion": {html.UnescapeString(m[1])}} |
| 83 | for _, origin := range []string{"", "https://evil.invalid"} { |
| 84 | if rec := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, origin, form, nonce); rec.Code != 400 { |
| 85 | t.Fatal("accepted wrong origin") |
| 86 | } |
| 87 | } |
| 88 | if rec := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, form, nonce, nonce); rec.Code != 400 { |
| 89 | t.Fatal("accepted duplicate cookie") |
| 90 | } |
| 91 | callback := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, form, nonce) |
| 92 | if callback.Code != 303 { |
| 93 | t.Fatal("callback", callback.Code) |
| 94 | } |
| 95 | if rec := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, form, nonce); rec.Code != 400 { |
| 96 | t.Fatal("callback replay") |
| 97 | } |
| 98 | finishURL := directoryOrigin + callback.Header().Get("Location") |
| 99 | if rec := exchangeRequest(p.directory, "GET", strings.Replace(finishURL, "team=red", "team=blue", 1), "", nil, nonce, directorySession); rec.Code != 400 { |
| 100 | t.Fatal("team substitution", rec.Code) |
| 101 | } |
| 102 | if rec := exchangeRequest(p.directory, "GET", finishURL, "", nil, nonce, directorySession, directorySession); rec.Code != 400 { |
| 103 | t.Fatal("ambiguous session") |
| 104 | } |
| 105 | finish := exchangeRequest(p.directory, "GET", finishURL, "", nil, nonce, directorySession) |
| 106 | if finish.Code != 200 || calls != 1 { |
| 107 | t.Fatal("finish", finish.Code, calls) |
| 108 | } |
| 109 | if rec := exchangeRequest(p.directory, "GET", finishURL, "", nil, nonce, directorySession); rec.Code != 200 || calls != 1 { |
| 110 | t.Fatal("canonical reload spent a token again") |
| 111 | } |
| 112 | page := exchangeRequest(p.directory, "GET", directoryOrigin+"/", "", nil, directorySession, preference) |
| 113 | if page.Code != 200 || !strings.Contains(page.Body.String(), "Dashboard private title <script>") || strings.Contains(page.Body.String(), "https://blue.docs.oficina.works/") || calls != 1 { |
| 114 | t.Fatal("selection, rendering, or cache failed", page.Code) |
| 115 | } |
| 116 | if refresh := exchangeRequest(p.directory, "GET", directoryOrigin+"/?refresh=1", "", nil, directorySession, preference); refresh.Code != 303 { |
| 117 | t.Fatal("refresh reused cached result") |
| 118 | } |
| 119 | if strings.Contains(page.Body.String(), "Nothing scheduled") { |
| 120 | t.Fatal("unconfigured calendar looks empty") |
| 121 | } |
| 122 | for _, path := range []string{p.credential.dbPath, p.directoryPath} { |
| 123 | for _, suffix := range []string{"", "-wal"} { |
| 124 | b, e := os.ReadFile(path + suffix) |
| 125 | if e != nil { |
| 126 | t.Fatal(e) |
| 127 | } |
| 128 | for _, canary := range []string{"Dashboard private title", "private-canary", form.Get("assertion")} { |
| 129 | if strings.Contains(string(b), canary) { |
| 130 | t.Fatal("content retained on disk") |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | if strings.Contains(p.logs.String(), "private title") || strings.Contains(p.logs.String(), "private-canary") { |
| 136 | t.Fatal("content logged") |
| 137 | } |
| 138 | p.directory.dash.mu.Lock() |
| 139 | p.directory.dash.sweep(time.Now().Add(121 * time.Second)) |
| 140 | n := len(p.directory.dash.cache) |
| 141 | p.directory.dash.mu.Unlock() |
| 142 | if n != 0 { |
| 143 | t.Fatal("hard expiry") |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | func TestDashboardPullRejectsInvalidSourceData(t *testing.T) { |
| 148 | p := newExchangePair(t) |
| 149 | source := dashboardSource{"docs", "https://blue.docs.oficina.works"} |
| 150 | team := dashboardTeam{ID: "blue", Sources: []dashboardSource{source}} |
| 151 | good := dashboardTestBody(t, dashboard.Response{Version: 1, Team: "blue", Kind: "documents", Items: []dashboard.Item{}}) |
| 152 | cases := []struct { |
| 153 | name, body, cache string |
| 154 | status int |
| 155 | }{ |
| 156 | {"valid", good, "private, no-store", 200}, |
| 157 | {"missing items", `{"v":1,"team":"blue","kind":"documents"}`, "no-store", 200}, |
| 158 | {"wrong team", strings.Replace(good, "blue", "red", 1), "no-store", 200}, |
| 159 | {"oversized", strings.Repeat("x", dashboard.MaxBody+1), "no-store", 200}, |
| 160 | {"malformed", "{", "no-store", 200}, |
| 161 | {"cacheable", good, "public, no-store", 200}, |
| 162 | {"fake cache directive", good, "x-no-store", 200}, |
| 163 | {"redirect", good, "no-store", 302}, |
| 164 | {"disconnected", "", "no-store", 403}, |
| 165 | } |
| 166 | for _, tc := range cases { |
| 167 | t.Run(tc.name, func(t *testing.T) { |
| 168 | p.directory.dash.client.Transport = dashboardTransport(func(r *http.Request) (*http.Response, error) { |
| 169 | res := dashboardTestResponse(tc.body) |
| 170 | res.StatusCode = tc.status |
| 171 | res.Header.Set("Cache-Control", tc.cache) |
| 172 | res.Header.Set("Location", "https://evil.invalid") |
| 173 | return res, nil |
| 174 | }) |
| 175 | got := p.directory.pullDashboard(context.Background(), team, map[string]string{source.Origin: "token"}) |
| 176 | if len(got) != 1 || (got[0].Status == "") != (tc.name == "valid") { |
| 177 | t.Fatal("incorrect provider state") |
| 178 | } |
| 179 | }) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | func TestDashboardCacheDirectives(t *testing.T) { |
| 184 | for _, s := range []string{"x-no-store", "public, no-store", "no-store, max-age=1", "no-store, s-maxage=1", "no-store=1"} { |
| 185 | if dashboardNoStore([]string{s}) { |
| 186 | t.Fatal("accepted", s) |
| 187 | } |
| 188 | } |
| 189 | if !dashboardNoStore([]string{"private", "NO-STORE"}) { |
| 190 | t.Fatal("rejected no-store") |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | func TestDashboardDuplicateOriginRefused(t *testing.T) { |
| 195 | p := newExchangePair(t) |
| 196 | r := httptest.NewRequest("POST", directoryOrigin+dashboardCallback, strings.NewReader("assertion=x")) |
| 197 | r.Header["Origin"] = []string{Origin, Origin} |
| 198 | r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 199 | w := httptest.NewRecorder() |
| 200 | p.directory.Router().ServeHTTP(w, r) |
| 201 | if w.Code != 400 { |
| 202 | t.Fatal(w.Code) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // Four document requests suffice with live sessions. The authenticated GET |
| 207 | // after the cross-origin POST still binds consumption to the current session. |
| 208 | func TestDashboardAuthenticatedFastPath(t *testing.T) { |
| 209 | p := newExchangePair(t) |
| 210 | credentialSession := signInFully(t, p.credential, sealtest.CanaryAddress) |
| 211 | pending, intent := p.start(t) |
| 212 | token, _ := p.mint(t, intent, credentialSession) |
| 213 | directorySession := p.finish(t, token, pending) |
| 214 | team := dashboardTeam{ID: "blue", Name: "Blue", Sources: []dashboardSource{{"docs", "https://blue.docs.oficina.works"}}} |
| 215 | p.directory.runtime.dashboard = []dashboardTeam{team} |
| 216 | p.credential.runtime.dashboard = []dashboardTeam{team} |
| 217 | calls := 0 |
| 218 | p.directory.dash.client.Transport = dashboardTransport(func(r *http.Request) (*http.Response, error) { |
| 219 | calls++ |
| 220 | return dashboardTestResponse(dashboardTestBody(t, dashboard.Response{Version: 1, Team: team.ID, Kind: "documents", Items: []dashboard.Item{}})), nil |
| 221 | }) |
| 222 | // Explicit refresh must consume the new proof even with a fresh cached page. |
| 223 | for _, query := range []string{"?team=blue", "?team=blue&refresh=1"} { |
| 224 | start := exchangeRequest(p.directory, "GET", directoryOrigin+"/"+query, "", nil, directorySession) |
| 225 | if start.Code != 303 { |
| 226 | t.Fatal("start", start.Code) |
| 227 | } |
| 228 | nonce := namedCookie(t, start, dashboardCookie) |
| 229 | minted := exchangeRequest(p.credential.App, "GET", start.Header().Get("Location"), "", nil, credentialSession) |
| 230 | if minted.Code != 200 { |
| 231 | t.Fatal("unnecessary credential redirect", minted.Code) |
| 232 | } |
| 233 | m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(minted.Body.String()) |
| 234 | if len(m) != 2 { |
| 235 | t.Fatal("no assertion form") |
| 236 | } |
| 237 | script := regexp.MustCompile(`<script src='(/static/assertion.js\?v=[0-9a-f]{16})' async></script>`).FindStringSubmatch(minted.Body.String()) |
| 238 | if len(script) != 2 { |
| 239 | t.Fatal("handoff script blocks on styles or revalidates") |
| 240 | } |
| 241 | asset := exchangeRequest(p.credential.App, "GET", Origin+script[1], "", nil) |
| 242 | if asset.Code != 200 || asset.Header().Get("Cache-Control") != "public, max-age=31536000, immutable" { |
| 243 | t.Fatal("handoff asset not immutable") |
| 244 | } |
| 245 | form := url.Values{"assertion": {html.UnescapeString(m[1])}} |
| 246 | callback := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, form, nonce) |
| 247 | if callback.Code != 303 || callback.Header().Get("Location") != "/?team=blue" { |
| 248 | t.Fatal("callback must finish at canonical URL") |
| 249 | } |
| 250 | before := calls |
| 251 | // Duplicate current-session cookies fail without consuming the pending batch. |
| 252 | bad := exchangeRequest(p.directory, "GET", directoryOrigin+"/?team=blue", "", nil, nonce, directorySession, directorySession) |
| 253 | if bad.Code != 400 || calls != before { |
| 254 | t.Fatal("ambiguous session consumed pending proof") |
| 255 | } |
| 256 | finish := exchangeRequest(p.directory, "GET", directoryOrigin+"/?team=blue", "", nil, nonce, directorySession) |
| 257 | if finish.Code != 200 || calls != before+1 || !strings.Contains(finish.Body.String(), "Recent") { |
| 258 | t.Fatal("finish", finish.Code, calls) |
| 259 | } |
| 260 | if finish.Header().Get("Cache-Control") != "no-store" { |
| 261 | t.Fatal("cacheable private dashboard") |
| 262 | } |
| 263 | replay := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, form, nonce) |
| 264 | if replay.Code != 400 { |
| 265 | t.Fatal("accepted consumed callback") |
| 266 | } |
| 267 | again := exchangeRequest(p.directory, "GET", directoryOrigin+"/?team=blue", "", nil, directorySession) |
| 268 | if again.Code != 200 || calls != before+1 { |
| 269 | t.Fatal("warm page pulled again") |
| 270 | } |
| 271 | } |
| 272 | // An old callback in flight across a deployment still cleans up its nonce URL. |
| 273 | p.directory.dash.mu.Lock() |
| 274 | for k := range p.directory.dash.cache { |
| 275 | delete(p.directory.dash.cache, k) |
| 276 | } |
| 277 | p.directory.dash.mu.Unlock() |
| 278 | start := exchangeRequest(p.directory, "GET", directoryOrigin+"/?team=blue", "", nil, directorySession) |
| 279 | nonce := namedCookie(t, start, dashboardCookie) |
| 280 | minted := exchangeRequest(p.credential.App, "GET", start.Header().Get("Location"), "", nil, credentialSession) |
| 281 | m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(minted.Body.String()) |
| 282 | exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, url.Values{"assertion": {html.UnescapeString(m[1])}}, nonce) |
| 283 | legacyURL := directoryOrigin + "/?team=blue&dashboard=" + url.QueryEscape(nonce.Value) |
| 284 | legacy := exchangeRequest(p.directory, "GET", legacyURL, "", nil, nonce, directorySession) |
| 285 | if legacy.Code != 303 || legacy.Header().Get("Location") != "/?team=blue" { |
| 286 | t.Fatal("legacy callback cleanup") |
| 287 | } |
| 288 | if replay := exchangeRequest(p.directory, "GET", legacyURL, "", nil, nonce, directorySession); replay.Code != 400 { |
| 289 | t.Fatal("legacy nonce replay") |
| 290 | } |
| 291 | } |
| 292 | |