Add OIDC browser approval and PKCE session handoff for pages CLI
This commit is contained in:
1 parent
2af87b4f58
commit
60f5fb1881
18 files changed
+1397
-23
No files matched your search
@@ -0,0 +1,186 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
var cliProofPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)
|
||||
var cliVerifierPattern = regexp.MustCompile(`^[A-Za-z0-9._~-]{43,128}$`)
|
||||
|
||||
func cliOrigin(r *http.Request) string { return strings.ToLower(externalURL(r, "")) }
|
||||
func cliSecureTransport(r *http.Request) bool {
|
||||
if requestIsHTTPS(r) {
|
||||
return true
|
||||
}
|
||||
host := r.Host
|
||||
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = h
|
||||
}
|
||||
return host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]"
|
||||
}
|
||||
func cliVerifyPath(id string) string { return "/_/auth/cli/verify?request=" + url.QueryEscape(id) }
|
||||
func cliConsentCSRF(token, id string) string {
|
||||
sum := sha256.Sum256([]byte("pages-cli-consent:" + token + ":" + id))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Server) handleCLIAuth(w http.ResponseWriter, r *http.Request, action string) {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
if !cliSecureTransport(r) {
|
||||
writeEventJSON(w, 400, map[string]string{"error": "https_required"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
r = r.WithContext(ctx)
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
config, err := s.store.AuthProviderConfig(domain, "oidc")
|
||||
if err != nil || !config.Enabled {
|
||||
writeEventJSON(w, 403, map[string]string{"error": "oidc_disabled"})
|
||||
return
|
||||
}
|
||||
if action == "cli/verify" {
|
||||
s.verifyCLIAuth(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", "POST")
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
switch action {
|
||||
case "cli/start":
|
||||
challenge := r.PostForm.Get("code_challenge")
|
||||
if !cliProofPattern.MatchString(challenge) || r.PostForm.Get("code_challenge_method") != "S256" {
|
||||
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
id, device, code, err := s.store.StartCLIAuth(ctx, domain, cliOrigin(r), challenge)
|
||||
if err != nil {
|
||||
cliAuthError(w, err)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"device_code": device, "verification_uri": cliVerifyPath(id), "user_code": code[:4] + "-" + code[4:], "expires_in": 300, "interval": 5})
|
||||
case "cli/token":
|
||||
device, verifier := r.PostForm.Get("device_code"), r.PostForm.Get("code_verifier")
|
||||
if !cliProofPattern.MatchString(device) || !cliVerifierPattern.MatchString(verifier) {
|
||||
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||
return
|
||||
}
|
||||
token, name, expires, err := s.store.ExchangeCLIAuth(ctx, domain, cliOrigin(r), device, verifier)
|
||||
if err != nil {
|
||||
cliAuthError(w, err)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"access_token": token, "token_type": "Bearer", "username": name, "expires_in": max(1, (expires-time.Now().UnixMilli())/1000)})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func cliAuthError(w http.ResponseWriter, err error) {
|
||||
code, status := "temporarily_unavailable", 503
|
||||
switch {
|
||||
case errors.Is(err, store.ErrCLIPending):
|
||||
code, status = "authorization_pending", 400
|
||||
case errors.Is(err, store.ErrCLISlowDown):
|
||||
code, status = "slow_down", 400
|
||||
case errors.Is(err, store.ErrCLIExpired):
|
||||
code, status = "expired_token", 400
|
||||
case errors.Is(err, store.ErrAccessDenied):
|
||||
code, status = "access_denied", 403
|
||||
case errors.Is(err, store.ErrCLILimit):
|
||||
code, status = "too_many_requests", 429
|
||||
}
|
||||
writeEventJSON(w, status, map[string]string{"error": code})
|
||||
}
|
||||
|
||||
func (s *Server) verifyCLIAuth(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", "GET, POST")
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid request", 400)
|
||||
return
|
||||
}
|
||||
id := r.URL.Query().Get("request")
|
||||
if r.Method == http.MethodPost {
|
||||
id = r.PostForm.Get("request")
|
||||
}
|
||||
if !cliProofPattern.MatchString(id) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
grant, err := s.store.CLIAuthRequest(r.Context(), domain, cliOrigin(r), id)
|
||||
if err != nil {
|
||||
http.Error(w, "CLI request expired; restart pages login --oidc", 410)
|
||||
return
|
||||
}
|
||||
data := map[string]any{"CLIAuth": true, "CLIOrigin": grant.Origin, "CLIRequest": id}
|
||||
if grant.State != "pending" {
|
||||
data["CLIDone"] = true
|
||||
s.renderAuthPage(w, r, data)
|
||||
return
|
||||
}
|
||||
if grant.BrowserHash == "" {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "OIDC login required", 403)
|
||||
return
|
||||
}
|
||||
data["CLILogin"] = "/_/auth/oidc?cli=" + url.QueryEscape(id)
|
||||
s.renderAuthPage(w, r, data)
|
||||
return
|
||||
}
|
||||
token := s.authTokenFromRequest(r)
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
hash := base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
principal, err := s.store.PrincipalForSession(domain, token)
|
||||
if !strings.HasPrefix(token, "pw_browser_") || hash != grant.BrowserHash || err != nil {
|
||||
http.Error(w, "This request belongs to another browser. Restart CLI login.", 403)
|
||||
return
|
||||
}
|
||||
data["CLIUsername"] = principal.Username
|
||||
data["CLICSRF"] = cliConsentCSRF(token, id)
|
||||
data["CLITOTP"] = s.store.HasTOTP(principal.UUID)
|
||||
if r.Method == http.MethodPost {
|
||||
if !validBrowserMutationOrigin(r) || subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(cliConsentCSRF(token, id))) != 1 {
|
||||
http.Error(w, "invalid approval origin or token", 403)
|
||||
return
|
||||
}
|
||||
decision := r.PostForm.Get("decision")
|
||||
if decision != "approve" && decision != "deny" {
|
||||
http.Error(w, "invalid decision", 400)
|
||||
return
|
||||
}
|
||||
err = s.store.DecideCLIAuth(r.Context(), domain, cliOrigin(r), id, token, r.PostForm.Get("user_code"), r.PostForm.Get("totp"), decision == "approve")
|
||||
if err != nil {
|
||||
data["Error"] = translate(s.getLocale(domain), "auth.cli_invalid")
|
||||
} else {
|
||||
data["CLIDone"] = true
|
||||
}
|
||||
}
|
||||
s.renderAuthPage(w, r, data)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestCLIConsentChromium(t *testing.T) {
|
||||
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||
t.Skip("opt-in Chromium")
|
||||
}
|
||||
for _, width := range []string{"1440", "390"} {
|
||||
t.Run(width, func(t *testing.T) {
|
||||
s, api, 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)
|
||||
}
|
||||
browser, err := s.store.CreateBrowserAuthSession(domain, s.mustCLIPrincipal(t, domain, api), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var code string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "GET" && r.URL.Path == "/_/auth/cli/verify" {
|
||||
r.AddCookie(&http.Cookie{Name: authCookieName, Value: browser})
|
||||
rec := httptest.NewRecorder()
|
||||
s.handleAuth(rec, r)
|
||||
for k, values := range rec.Header() {
|
||||
w.Header()[k] = values
|
||||
}
|
||||
s.setAuthCookie(w, r, browser)
|
||||
encoded, _ := json.Marshal(code)
|
||||
script := `<script>(async()=>{try{
|
||||
const form=document.querySelector('.auth-form'); if(!form)throw Error('missing consent form');
|
||||
if(document.documentElement.scrollWidth>innerWidth+2)throw Error('horizontal overflow');
|
||||
const field=form.elements.user_code; if(getComputedStyle(field).backgroundColor==='rgba(0, 0, 0, 0)')throw Error('input theme missing');
|
||||
field.value=` + string(encoded) + `; const data=new URLSearchParams(new FormData(form)); data.set('decision','approve');
|
||||
const response=await fetch(form.action,{method:'POST',body:data}); const html=await response.text();
|
||||
if(!response.ok||html.includes('name="user_code"'))throw Error('approval failed');
|
||||
document.body.dataset.vimReady='true';
|
||||
}catch(e){const p=document.createElement('pre');p.id='error';p.textContent=e.message;document.body.append(p)}})();</script>`
|
||||
w.WriteHeader(rec.Code)
|
||||
_, _ = w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", script+"</body>", 1)))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/_/auth/") {
|
||||
s.withAuthorization(http.HandlerFunc(s.handleAuth)).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
origin := strings.Replace(server.URL, "127.0.0.1", "localhost", 1)
|
||||
id, _, c, err := s.store.StartCLIAuth(context.Background(), domain, origin, strings.Repeat("c", 43))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code = c
|
||||
if err := s.store.BindCLIAuth(context.Background(), domain, origin, id, browser); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||
defer cancel()
|
||||
screenshot := ""
|
||||
if dir := os.Getenv("PAGESWIKI_BROWSER_ARTIFACTS"); dir != "" {
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
screenshot = filepath.Join(dir, "cli-consent-"+width+".png")
|
||||
}
|
||||
command := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", origin+cliVerifyPath(id), t.TempDir(), screenshot, width, "900")
|
||||
if out, err := command.CombinedOutput(); err != nil {
|
||||
t.Fatalf("consent browser: %v %s", err, out)
|
||||
}
|
||||
grant, err := s.store.CLIAuthRequest(context.Background(), domain, origin, id)
|
||||
if err != nil || grant.State != "approved" {
|
||||
t.Fatalf("not persisted: %+v %v", grant, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package server
|
||||
|
||||
func init() {
|
||||
for lang, entries := range map[string]map[string]string{
|
||||
"ja": {
|
||||
"auth.cli_title": "ターミナルからのアクセスを承認",
|
||||
"auth.cli_warning": "自分で pages login --oidc を開始した場合のみ続行してください。他人から送られたURLや確認コードを使って承認しないでください。有効期限は開始から5分です。",
|
||||
"auth.cli_account": "ログインするアカウント",
|
||||
"auth.cli_access": "このCLIはあなたの現在の権限で閲覧・編集できます。専用セッションは設定画面から失効できます。",
|
||||
"auth.cli_code": "ターミナルに表示された確認コード",
|
||||
"auth.cli_approve": "このCLIを承認する",
|
||||
"auth.cli_deny": "拒否する",
|
||||
"auth.cli_done": "リクエストは処理済みです。ターミナルに戻って結果を確認してください。この画面は閉じられます。",
|
||||
"auth.cli_invalid": "確認コードまたはTOTPが正しくないか、リクエストが失効しました。5回失敗した場合はCLIでログインをやり直してください。",
|
||||
},
|
||||
"en": {
|
||||
"auth.cli_title": "Approve terminal access",
|
||||
"auth.cli_warning": "Continue only if you started pages login --oidc yourself. Never approve a URL or code sent by someone else. This request expires five minutes after creation.",
|
||||
"auth.cli_account": "Account",
|
||||
"auth.cli_access": "This CLI can read and edit using your current permissions. Its separate session can be revoked in Settings.",
|
||||
"auth.cli_code": "Confirmation code shown in your terminal",
|
||||
"auth.cli_approve": "Approve this CLI",
|
||||
"auth.cli_deny": "Deny",
|
||||
"auth.cli_done": "This request has been processed. Return to your terminal to check the result. You may close this page.",
|
||||
"auth.cli_invalid": "Incorrect confirmation code or TOTP, or the request expired. After five failed attempts, restart login from the CLI.",
|
||||
},
|
||||
} {
|
||||
for key, value := range entries {
|
||||
translations[lang][key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash string }
|
||||
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash, CLIRequest string }
|
||||
|
||||
func logOIDCFailure(stage, domainUUID, issuer string, err error) {
|
||||
host := "invalid"
|
||||
@@ -56,6 +56,19 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
||||
defer cancel()
|
||||
cliRequest := r.URL.Query().Get("cli")
|
||||
returnPath := safeReturnPath(r.URL.Query().Get("return"))
|
||||
if cliRequest != "" {
|
||||
if !cliSecureTransport(r) || !cliProofPattern.MatchString(cliRequest) {
|
||||
http.Error(w, "invalid CLI request", 400)
|
||||
return
|
||||
}
|
||||
if err := s.store.BeginCLIAuth(ctx, domainUUID, cliOrigin(r), cliRequest); err != nil {
|
||||
http.Error(w, "invalid CLI request", 400)
|
||||
return
|
||||
}
|
||||
returnPath = cliVerifyPath(cliRequest)
|
||||
}
|
||||
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
|
||||
if err != nil {
|
||||
logOIDCFailure("discovery", domainUUID, config.Issuer, err)
|
||||
@@ -64,7 +77,7 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
verifier, nonce, browser := randomURLToken(32), randomURLToken(24), randomURLToken(32)
|
||||
browserDigest := sha256.Sum256([]byte(browser))
|
||||
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: safeReturnPath(r.URL.Query().Get("return")), Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:])}, 5*time.Minute)
|
||||
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: returnPath, Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:]), CLIRequest: cliRequest}, 5*time.Minute)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
@@ -197,6 +210,13 @@ func (s *Server) completeOIDC(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if challenge.CLIRequest != "" {
|
||||
if err := s.store.BindCLIAuth(r.Context(), domainUUID, cliOrigin(r), challenge.CLIRequest, token); err != nil {
|
||||
_ = s.store.RevokeAuthSession(token)
|
||||
http.Error(w, "CLI request expired or already used; restart login", 400)
|
||||
return
|
||||
}
|
||||
}
|
||||
s.setAuthCookie(w, r, token)
|
||||
http.Redirect(w, r, challenge.Return, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -101,6 +101,10 @@ func (s *Server) authTokenFromRequest(r *http.Request) string {
|
||||
func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/auth"), "/")
|
||||
domainUUID := s.domainUUIDForRequest(r)
|
||||
if strings.HasPrefix(action, "cli/") {
|
||||
s.handleCLIAuth(w, r, action)
|
||||
return
|
||||
}
|
||||
switch action {
|
||||
case "wallpaper":
|
||||
s.handleAuthWallpaper(w, r)
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
||||
@@ -33,3 +35,48 @@ func TestRemoteCLIHTTPIntegration(t *testing.T) {
|
||||
t.Fatalf("remote CLI: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteCLIOIDCIntegration(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
t.Skip("python3 not installed")
|
||||
}
|
||||
s, api, domain, _ := editorFixture(t)
|
||||
if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.mux.HandleFunc("/_/auth/", s.handleAuth)
|
||||
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
||||
principal := s.mustCLIPrincipal(t, domain, api)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
// Test-only bridge in this httptest server. The real signed OIDC callback,
|
||||
// browser binding and CSRF flow are covered by TestCLIAuthOIDCFlow.
|
||||
if r.URL.Path == "/__test/cli-approve" {
|
||||
_ = r.ParseForm()
|
||||
browser, err := s.store.CreateBrowserAuthSession(domain, principal, 0)
|
||||
if err == nil {
|
||||
err = s.store.BindCLIAuth(r.Context(), domain, "http://localhost", r.Form.Get("request"), browser)
|
||||
}
|
||||
if err == nil {
|
||||
err = s.store.DecideCLIAuth(r.Context(), domain, "http://localhost", r.Form.Get("request"), browser, r.Form.Get("code"), "", true)
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "synthetic approval failed", 500)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]bool{"approved": true})
|
||||
return
|
||||
}
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "python3", "pages-cli/test_pages.py", "--oidc-integration")
|
||||
input, _ := json.Marshal(map[string]string{"origin": server.URL})
|
||||
cmd.Stdin = bytes.NewReader(input)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("CLI OIDC integration: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user