package server import ( "crypto/sha256" "encoding/base64" "encoding/json" "net/http" "net/http/httptest" "net/url" "strings" "testing" "pageswiki/internal/store" ) func cliForm(s *Server, path string, form url.Values, cookie, origin string) *httptest.ResponseRecorder { r := httptest.NewRequest("POST", "https://localhost"+path, strings.NewReader(form.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") if origin != "" { r.Header.Set("Origin", origin) } if cookie != "" { r.AddCookie(&http.Cookie{Name: authCookieName, Value: cookie}) } w := httptest.NewRecorder() s.withAuthorization(http.HandlerFunc(s.handleAuth)).ServeHTTP(w, r) return w } func TestCLIAuthOIDCFlow(t *testing.T) { s, _, domain := configFixture(t) p := newOIDCTestProvider(t) previous := oidcVerifier oidcVerifier = p.verifier t.Cleanup(func() { oidcVerifier = previous }) if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: p.server.URL, ClientID: "client", ClientSecret: "secret", OIDCMatchBy: "preferred_username"}); err != nil { t.Fatal(err) } verifier := strings.Repeat("x", 43) sum := sha256.Sum256([]byte(verifier)) start := cliForm(s, "/_/auth/cli/start", url.Values{"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}}, "", "") if start.Code != 200 { t.Fatalf("start %d %s", start.Code, start.Body.String()) } var grant struct { Device string `json:"device_code"` URI string `json:"verification_uri"` Code string `json:"user_code"` } if err := json.Unmarshal(start.Body.Bytes(), &grant); err != nil { t.Fatal(err) } u, _ := url.Parse(grant.URI) id := u.Query().Get("request") verify := httptest.NewRecorder() s.handleAuth(verify, httptest.NewRequest("GET", "https://localhost"+grant.URI, nil)) if verify.Code != 200 || !strings.Contains(verify.Body.String(), "/_/auth/oidc?cli=") || strings.Contains(verify.Body.String(), grant.Device) { t.Fatalf("verify landing: %d %s", verify.Code, verify.Body.String()) } begin := httptest.NewRecorder() s.beginOIDC(begin, httptest.NewRequest("GET", "https://localhost/_/auth/oidc?cli="+id, nil)) if begin.Code != 302 { t.Fatalf("oidc begin %d %s", begin.Code, begin.Body.String()) } location, _ := url.Parse(begin.Header().Get("Location")) claims := oidcTestClaims(p.server.URL) claims["nonce"] = location.Query().Get("nonce") p.mu.Lock() p.idToken = oidcTestToken(t, p.key, map[string]string{"alg": "RS256", "kid": "one"}, claims) p.mu.Unlock() callback := httptest.NewRequest("GET", "https://localhost/_/auth/callback/oidc?code=code&state="+url.QueryEscape(location.Query().Get("state")), nil) for _, cookie := range begin.Result().Cookies() { callback.AddCookie(cookie) } complete := httptest.NewRecorder() s.completeOIDC(complete, callback) if complete.Code != 303 || complete.Header().Get("Location") != grant.URI { t.Fatalf("oidc callback %d %s", complete.Code, complete.Body.String()) } var browser string for _, cookie := range complete.Result().Cookies() { if cookie.Name == authCookieName { browser = cookie.Value } } if browser == "" { t.Fatal("missing browser session") } consent := httptest.NewRequest("GET", "https://localhost"+grant.URI, nil) consent.AddCookie(&http.Cookie{Name: authCookieName, Value: browser}) w := httptest.NewRecorder() s.handleAuth(w, consent) if w.Code != 200 || !strings.Contains(w.Body.String(), `name="user_code"`) || !strings.Contains(w.Body.String(), cliConsentCSRF(browser, id)) { t.Fatalf("consent %d %s", w.Code, w.Body.String()) } form := url.Values{"request": {id}, "csrf": {cliConsentCSRF(browser, id)}, "user_code": {grant.Code}, "decision": {"approve"}} if w := cliForm(s, "/_/auth/cli/verify", form, browser, "https://evil.example"); w.Code != 403 { t.Fatal("cross-origin approval accepted") } bad := url.Values{"request": {id}, "csrf": {"bad"}, "user_code": {grant.Code}, "decision": {"approve"}} if w := cliForm(s, "/_/auth/cli/verify", bad, browser, "https://localhost"); w.Code != 403 { t.Fatal("CSRF accepted") } other, err := s.store.CreateBrowserAuthSession(domain, s.mustCLIPrincipal(t, domain, browser), 0) if err != nil { t.Fatal(err) } if w := cliForm(s, "/_/auth/cli/verify", form, other, "https://localhost"); w.Code != 403 { t.Fatal("other browser accepted") } approved := cliForm(s, "/_/auth/cli/verify", form, browser, "https://localhost") if approved.Code != 200 || strings.Contains(approved.Body.String(), `name="user_code"`) { t.Fatalf("approve: %d %s", approved.Code, approved.Body.String()) } poll := url.Values{"device_code": {grant.Device}, "code_verifier": {verifier}} exchange := cliForm(s, "/_/auth/cli/token", poll, "", "") if exchange.Code != 200 { t.Fatalf("exchange %d %s", exchange.Code, exchange.Body.String()) } var result struct { Token string `json:"access_token"` Username string `json:"username"` } if err := json.Unmarshal(exchange.Body.Bytes(), &result); err != nil { t.Fatal(err) } if !strings.HasPrefix(result.Token, "pw_api_") || result.Username != "admin" || result.Token == browser { t.Fatal("invalid delegated credential") } if _, err := s.store.PrincipalForSession(domain, result.Token); err != nil { t.Fatal(err) } if w := cliForm(s, "/_/auth/cli/token", poll, "", ""); w.Code == 200 { t.Fatal("replay accepted") } if err := s.store.RevokeAuthSession(result.Token); err != nil { t.Fatal(err) } if _, err := s.store.PrincipalForSession(domain, result.Token); err == nil { t.Fatal("CLI session not revocable") } } func (s *Server) mustCLIPrincipal(t *testing.T, domain, token string) string { t.Helper() p, err := s.store.PrincipalForSession(domain, token) if err != nil { t.Fatal(err) } return p.UUID } func TestCLITransportAndMethods(t *testing.T) { for _, host := range []string{"localhost.attacker.test", "127.0.0.10", "wiki.example"} { if cliSecureTransport(httptest.NewRequest("POST", "http://"+host+"/_/auth/cli/start", nil)) { t.Fatal("insecure remote", host) } } s, _, domain := configFixture(t) if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil { t.Fatal(err) } for _, path := range []string{"start", "token"} { w := httptest.NewRecorder() s.handleAuth(w, httptest.NewRequest("GET", "https://localhost/_/auth/cli/"+path, nil)) if w.Code != 405 { t.Fatalf("GET %s %d", path, w.Code) } } w := cliForm(s, "/_/auth/cli/start", url.Values{"code_challenge": {strings.Repeat("x", 43)}, "code_challenge_method": {"plain"}}, "", "") if w.Code != 400 { t.Fatal("plain challenge accepted") } }