oficina / agent-access Public

Clone
git clone https://amadan.net/oficina/agent-access

Plain git — no account needed to clone.

Download this file

1package grant
2
3import (
4 "io"
5 "net/http"
6 "net/url"
7 "regexp"
8 "strings"
9 "testing"
10)
11
12const testState = "0123456789abcdefghij"
13
14func authorizeURL(base string, extra url.Values) string {
15 q := url.Values{"client_id": {"oficina-cli"}, "redirect_uri": {"http://127.0.0.1:4567/callback"}, "response_type": {"code"}, "code_challenge": {"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"}, "code_challenge_method": {"S256"}, "resource": {base + "/mcp"}, "scope": {"notes:write"}, "state": {testState}}
16 for k, v := range extra {
17 q[k] = v
18 }
19 return base + "/oauth/authorize?" + q.Encode()
20}
21
22func get(t *testing.T, ts interface{ Client() *http.Client }, raw, session string) (*http.Response, string) {
23 t.Helper()
24 c := *ts.Client()
25 c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
26 req, _ := http.NewRequest("GET", raw, nil)
27 if session != "" {
28 req.Header.Set("Test-Session", session)
29 }
30 resp, err := c.Do(req)
31 if err != nil {
32 t.Fatal(err)
33 }
34 defer resp.Body.Close()
35 body, _ := io.ReadAll(resp.Body)
36 return resp, string(body)
37}
38
39func wantErrorRedirect(t *testing.T, resp *http.Response, code string) {
40 t.Helper()
41 if resp.StatusCode != 303 {
42 t.Fatalf("status %d, want redirect", resp.StatusCode)
43 }
44 loc, err := url.Parse(resp.Header.Get("Location"))
45 if err != nil || loc.Host != "127.0.0.1:4567" || loc.Path != "/callback" {
46 t.Fatalf("redirected to %q", resp.Header.Get("Location"))
47 }
48 q := loc.Query()
49 if q.Get("error") != code || q.Get("state") != testState || q.Get("code") != "" {
50 t.Fatalf("redirect query %v", q)
51 }
52}
53
54// wantErrorHandoff is wantErrorRedirect for an answer to the consent form,
55// which hands the browser on with a page instead of a redirect.
56func wantErrorHandoff(t *testing.T, code string) func(*http.Response, string) {
57 return func(resp *http.Response, body string) {
58 t.Helper()
59 loc := wantHandoff(t, resp, body)
60 if loc.Host != "127.0.0.1:4567" || loc.Path != "/callback" {
61 t.Fatalf("sent to %q", loc)
62 }
63 if q := loc.Query(); q.Get("error") != code || q.Get("state") != testState || q.Get("code") != "" {
64 t.Fatalf("hand-off query %v", q)
65 }
66 }
67}
68
69func TestNoTeamRedirectsToClientWithAccessDenied(t *testing.T) {
70 _, ts, admitted := setup(t)
71 *admitted = false
72 resp, _ := get(t, ts, authorizeURL(ts.URL, nil), "signed-in")
73 wantErrorRedirect(t, resp, "access_denied")
74}
75
76func TestPostValidationAuthorizeErrorsRedirect(t *testing.T) {
77 _, ts, _ := setup(t)
78 resp, _ := get(t, ts, authorizeURL(ts.URL, url.Values{"scope": {"nonsense"}}), "signed-in")
79 wantErrorRedirect(t, resp, "invalid_scope")
80 resp, _ = get(t, ts, authorizeURL(ts.URL, url.Values{"code_challenge_method": {"plain"}}), "signed-in")
81 wantErrorRedirect(t, resp, "invalid_request")
82}
83
84func TestUntrustedClientOrRedirectNeverRedirects(t *testing.T) {
85 _, ts, admitted := setup(t)
86 *admitted = false
87 for _, extra := range []url.Values{{"client_id": {"nope"}}, {"redirect_uri": {"https://evil.example/callback"}}, {"redirect_uri": {"http://localhost:4567/callback"}}} {
88 resp, _ := get(t, ts, authorizeURL(ts.URL, extra), "signed-in")
89 if resp.StatusCode != 400 || resp.Header.Get("Location") != "" {
90 t.Fatalf("%v: %d %q", extra, resp.StatusCode, resp.Header.Get("Location"))
91 }
92 }
93}
94
95func TestConsentPageIsStyledWithUnchangedWords(t *testing.T) {
96 _, ts, _ := setup(t)
97 resp, body := get(t, ts, authorizeURL(ts.URL, nil), "signed-in")
98 csp := resp.Header.Get("Content-Security-Policy")
99 if resp.StatusCode != 200 || !strings.Contains(csp, "style-src 'self'") || strings.Contains(csp, "unsafe-inline") {
100 t.Fatalf("%d csp %q", resp.StatusCode, csp)
101 }
102 if !strings.Contains(body, `rel="stylesheet" href="/static/grant.css"`) || strings.Contains(body, "<style") {
103 t.Fatal("stylesheet not linked")
104 }
105 for _, words := range []string{"Connect to Oficina", "Connect Oficina CLI to Oficina", "This client will receive the content it reads and can act within the permissions you approve.", "Choose teams", "Allow access", "Cancel", "<li>Create and edit notes</li>"} {
106 if !strings.Contains(body, words) {
107 t.Fatalf("missing %q", words)
108 }
109 }
110 if !strings.Contains(body, `value="acme" checked`) {
111 t.Fatal("the only team is not pre-selected")
112 }
113 for _, asset := range []string{"/static/brand/icon.svg", "/static/sky/grain.svg", "/static/sky/filaments.svg", "/static/sky/placeholder-light.png"} {
114 if r, _ := get(t, ts, ts.URL+asset, ""); r.StatusCode != 200 || !strings.Contains(csp, "img-src 'self'") {
115 t.Fatalf("asset %s: %d", asset, r.StatusCode)
116 }
117 }
118 if r, _ := get(t, ts, ts.URL+"/static/../server.go", ""); r.StatusCode == 200 {
119 t.Fatal("served a file outside the closed list")
120 }
121 css, cssBody := get(t, ts, ts.URL+"/static/grant.css", "")
122 if css.StatusCode != 200 || !strings.HasPrefix(css.Header.Get("Content-Type"), "text/css") || !strings.Contains(cssBody, "system-ui") {
123 t.Fatalf("stylesheet %d %s", css.StatusCode, css.Header.Get("Content-Type"))
124 }
125}
126
127func TestConnectionsPageIsStyled(t *testing.T) {
128 _, ts, _ := setup(t)
129 resp, body := get(t, ts, ts.URL+"/connections", "signed-in")
130 if !strings.Contains(resp.Header.Get("Content-Security-Policy"), "style-src 'self'") || !strings.Contains(body, `href="/static/grant.css"`) || !strings.Contains(body, "Your connections") {
131 t.Fatalf("connections not styled: %s", body)
132 }
133}
134
135func TestApproveRefusalRedirectsWithStateButReplayDoesNot(t *testing.T) {
136 _, ts, _ := setup(t)
137 page, body := get(t, ts, authorizeURL(ts.URL, nil), "signed-in")
138 m := regexp.MustCompile(`name="ticket" value="([^"]+)"`).FindStringSubmatch(body)
139 if len(m) != 2 {
140 t.Fatal("no ticket")
141 }
142 post := func(team string) (*http.Response, string) {
143 form := url.Values{"ticket": {m[1]}, "decision": {"approve"}}
144 if team != "" {
145 form.Set("team", team)
146 }
147 req, _ := http.NewRequest("POST", ts.URL+"/oauth/authorize", strings.NewReader(form.Encode()))
148 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
149 req.Header.Set("Origin", ts.URL)
150 req.Header.Set("Test-Session", "signed-in")
151 for _, c := range page.Cookies() {
152 req.AddCookie(c)
153 }
154 c := *ts.Client()
155 c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
156 resp, err := c.Do(req)
157 if err != nil {
158 t.Fatal(err)
159 }
160 defer resp.Body.Close()
161 body, _ := io.ReadAll(resp.Body)
162 return resp, string(body)
163 }
164 wantErrorHandoff(t, "access_denied")(post("not-my-team"))
165 wantErrorHandoff(t, "access_denied")(post(""))
166 if resp, body := post("acme"); wantHandoff(t, resp, body).Query().Get("code") == "" {
167 t.Fatalf("approve sent no code: %s", body)
168 }
169 if resp, _ := post("acme"); resp.StatusCode != 400 || resp.Header.Get("Location") != "" {
170 t.Fatalf("replay %d %q", resp.StatusCode, resp.Header.Get("Location"))
171 }
172}
173