|
| 1 | +package httpmw_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/httptest" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/require" |
| 9 | + |
| 10 | + "github.com/coder/coder/coderd/httpapi" |
| 11 | + "github.com/coder/coder/coderd/httpmw" |
| 12 | +) |
| 13 | + |
| 14 | +func TestWorkspaceAppCors(t *testing.T) { |
| 15 | + t.Parallel() |
| 16 | + |
| 17 | + regex, err := httpapi.CompileHostnamePattern("*--apps.dev.coder.com") |
| 18 | + require.NoError(t, err) |
| 19 | + |
| 20 | + app := httpapi.ApplicationURL{ |
| 21 | + AppSlugOrPort: "3000", |
| 22 | + AgentName: "agent", |
| 23 | + WorkspaceName: "ws", |
| 24 | + Username: "user", |
| 25 | + } |
| 26 | + |
| 27 | + handler := httpmw.WorkspaceAppCors(regex, app) |
| 28 | + methods := []string{ |
| 29 | + http.MethodOptions, |
| 30 | + http.MethodHead, |
| 31 | + http.MethodGet, |
| 32 | + http.MethodPost, |
| 33 | + http.MethodPut, |
| 34 | + http.MethodPatch, |
| 35 | + http.MethodDelete, |
| 36 | + } |
| 37 | + |
| 38 | + tests := []struct { |
| 39 | + name string |
| 40 | + origin string |
| 41 | + allowed bool |
| 42 | + }{ |
| 43 | + { |
| 44 | + name: "Self", |
| 45 | + origin: "https://3000--agent--ws--user--apps.dev.coder.com", |
| 46 | + allowed: true, |
| 47 | + }, |
| 48 | + { |
| 49 | + name: "SameWorkspace", |
| 50 | + origin: "https://8000--agent--ws--user--apps.dev.coder.com", |
| 51 | + allowed: true, |
| 52 | + }, |
| 53 | + { |
| 54 | + name: "SameUser", |
| 55 | + origin: "https://8000--agent2--ws2--user--apps.dev.coder.com", |
| 56 | + allowed: true, |
| 57 | + }, |
| 58 | + { |
| 59 | + name: "DifferentUser", |
| 60 | + origin: "https://3000--agent--ws--user2--apps.dev.coder.com", |
| 61 | + allowed: false, |
| 62 | + }, |
| 63 | + } |
| 64 | + |
| 65 | + for _, test := range tests { |
| 66 | + test := test |
| 67 | + t.Run(test.name, func(t *testing.T) { |
| 68 | + t.Parallel() |
| 69 | + |
| 70 | + for _, method := range methods { |
| 71 | + r := httptest.NewRequest(method, "http://localhost", nil) |
| 72 | + r.Header.Set("Origin", test.origin) |
| 73 | + rw := httptest.NewRecorder() |
| 74 | + |
| 75 | + handler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 76 | + rw.WriteHeader(http.StatusOK) |
| 77 | + })).ServeHTTP(rw, r) |
| 78 | + |
| 79 | + if test.allowed { |
| 80 | + require.Equal(t, test.origin, rw.Header().Get("Access-Control-Allow-Origin")) |
| 81 | + } else { |
| 82 | + require.Equal(t, "", rw.Header().Get("Access-Control-Allow-Origin")) |
| 83 | + } |
| 84 | + } |
| 85 | + }) |
| 86 | + } |
| 87 | +} |
0 commit comments