{{ if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }}
+
{{ if .CLIAuth }}{{ T "auth.cli_title" }}{{ else if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }}
{{ if .Setup }}
{{ T "auth.setup_help" }}
{{ end }}{{ if .Error }}
{{ .Error }}
{{ end }}
-{{ if .Logout }}{{ else if .MFA }}{{ else }}{{ else if .MFA }}{{ else }}
+{{ end }}{{ end }}
+{{ end }}
", script+"", 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)
+ }
+ })
+ }
+}
diff --git a/internal/server/auth_cli_i18n.go b/internal/server/auth_cli_i18n.go
new file mode 100644
index 0000000..6bb7657
--- /dev/null
+++ b/internal/server/auth_cli_i18n.go
@@ -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
+ }
+ }
+}
diff --git a/internal/server/auth_cli_test.go b/internal/server/auth_cli_test.go
new file mode 100644
index 0000000..e935177
--- /dev/null
+++ b/internal/server/auth_cli_test.go
@@ -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")
+ }
+}
diff --git a/internal/server/auth_external.go b/internal/server/auth_external.go
index 04e3581..cae2909 100644
--- a/internal/server/auth_external.go
+++ b/internal/server/auth_external.go
@@ -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)
}
diff --git a/internal/server/auth_handler.go b/internal/server/auth_handler.go
index 0275fb6..e34d3f4 100644
--- a/internal/server/auth_handler.go
+++ b/internal/server/auth_handler.go
@@ -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)
diff --git a/internal/server/remote_cli_test.go b/internal/server/remote_cli_test.go
index ec47bb1..b736035 100644
--- a/internal/server/remote_cli_test.go
+++ b/internal/server/remote_cli_test.go
@@ -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)
+ }
+}
diff --git a/internal/store/auth_cli.go b/internal/store/auth_cli.go
new file mode 100644
index 0000000..32aaa8c
--- /dev/null
+++ b/internal/store/auth_cli.go
@@ -0,0 +1,248 @@
+package store
+
+import (
+ "context"
+ "crypto/rand"
+ "database/sql"
+ "encoding/hex"
+ "errors"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "pageswiki/internal/db"
+)
+
+var cliAuthMigrations = []db.SQLMigration{{Version: 1, Name: "cli_oidc_handoff", Statements: []string{
+ `CREATE TABLE auth_cli_requests (
+ id TEXT PRIMARY KEY, domain_uuid TEXT NOT NULL, origin TEXT NOT NULL,
+ device_hash TEXT NOT NULL UNIQUE, challenge TEXT NOT NULL, code_hash TEXT NOT NULL,
+ state TEXT NOT NULL DEFAULT 'pending', browser_hash TEXT NOT NULL DEFAULT '',
+ principal_uuid TEXT NOT NULL DEFAULT '', mfa_level INTEGER NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0, oidc_attempts INTEGER NOT NULL DEFAULT 0,
+ created_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL, next_poll_ms INTEGER NOT NULL DEFAULT 0)`,
+ `CREATE INDEX auth_cli_domain_created ON auth_cli_requests(domain_uuid,created_ms)`,
+ `CREATE INDEX auth_cli_expiry ON auth_cli_requests(expires_ms)`,
+}, Assertions: []string{
+ schemaColumns("auth_cli_requests", "id,domain_uuid,origin,device_hash,challenge,code_hash,state,browser_hash,principal_uuid,mfa_level,attempts,oidc_attempts,created_ms,expires_ms,next_poll_ms"),
+ schemaUnique("auth_cli_requests", "id"), schemaUnique("auth_cli_requests", "device_hash"),
+ schemaIndex("auth_cli_requests", "auth_cli_domain_created", "domain_uuid,created_ms"),
+ schemaIndex("auth_cli_requests", "auth_cli_expiry", "expires_ms"),
+}}}
+
+var (
+ ErrCLIPending = errors.New("authorization_pending")
+ ErrCLISlowDown = errors.New("slow_down")
+ ErrCLIExpired = errors.New("expired_token")
+ ErrCLILimit = errors.New("too_many_requests")
+)
+
+type CLIAuthRequest struct {
+ ID, Origin, State, BrowserHash, PrincipalUUID string
+ ExpiresMS int64
+}
+
+// Admission is one write statement; concurrent unauthenticated requests cannot
+// race the caps. Requests are retained for ten minutes for issuance accounting.
+func (s *Store) StartCLIAuth(ctx context.Context, domain, origin, challenge string) (id, device, code string, err error) {
+ if s.ReadOnly {
+ return "", "", "", ErrReadOnly
+ }
+ id, _, err = authToken()
+ if err != nil {
+ return
+ }
+ device, _, err = authToken()
+ if err != nil {
+ return
+ }
+ var raw [4]byte
+ if _, err = rand.Read(raw[:]); err != nil {
+ return
+ }
+ code = strings.ToUpper(hex.EncodeToString(raw[:]))
+ now := time.Now().UnixMilli()
+ _, err = s.DB.ExecContext(ctx, `DELETE FROM auth_cli_requests WHERE expires_ms`, now-5*60*1000)
+ if err != nil {
+ return
+ }
+ var result sql.Result
+ result, err = s.DB.ExecContext(ctx, `INSERT INTO auth_cli_requests(id,domain_uuid,origin,device_hash,challenge,code_hash,created_ms,expires_ms)
+ SELECT ?,?,?,?,?,?,?,? WHERE (SELECT count(*) FROM auth_cli_requests)<4096
+ AND (SELECT count(*) FROM auth_cli_requests WHERE domain_uuid=? AND created_ms>?)<64`,
+ id, domain, origin, hashAuthToken(device), challenge, hashAuthToken(code), now, now+300000, domain, now-300000)
+ if err == nil {
+ if n, e := result.RowsAffected(); e != nil {
+ err = e
+ } else if n != 1 {
+ err = ErrCLILimit
+ }
+ }
+ return
+}
+
+func (s *Store) CLIAuthRequest(ctx context.Context, domain, origin, id string) (*CLIAuthRequest, error) {
+ var grant CLIAuthRequest
+ err := s.DB.QueryRowContext(ctx, `SELECT id,origin,state,browser_hash,principal_uuid,expires_ms FROM auth_cli_requests WHERE id=? AND domain_uuid=? AND origin=? AND expires_ms>?`, id, domain, origin, time.Now().UnixMilli()).Scan(&grant.ID, &grant.Origin, &grant.State, &grant.BrowserHash, &grant.PrincipalUUID, &grant.ExpiresMS)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, ErrCLIExpired
+ }
+ return &grant, err
+}
+
+func (s *Store) BeginCLIAuth(ctx context.Context, domain, origin, id string) error {
+ if s.ReadOnly {
+ return ErrReadOnly
+ }
+ result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET oidc_attempts=oidc_attempts+1 WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash='' AND expires_ms>? AND oidc_attempts<3`, id, domain, origin, time.Now().UnixMilli())
+ return cliChanged(result, err)
+}
+
+// Only the verified OIDC callback calls this method. The first successful
+// browser wins; another browser cannot rebind an in-flight approval.
+func (s *Store) BindCLIAuth(ctx context.Context, domain, origin, id, browser string) error {
+ if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
+ return ErrAccessDenied
+ }
+ now := time.Now().UnixMilli()
+ result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET browser_hash=?,principal_uuid=(SELECT principal_uuid FROM auth_sessions WHERE token_hash=?)
+ WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash='' AND expires_ms>?
+ AND EXISTS(SELECT 1 FROM auth_sessions WHERE token_hash=? AND domain_uuid=? AND revoked_at_ms=0 AND expires_at_ms>?)`, hashAuthToken(browser), hashAuthToken(browser), id, domain, origin, now, hashAuthToken(browser), domain, now)
+ return cliChanged(result, err)
+}
+
+func cliChanged(result sql.Result, err error) error {
+ if err != nil {
+ return err
+ }
+ n, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n != 1 {
+ return ErrAccessDenied
+ }
+ return nil
+}
+
+// The browser token, confirmation code and current membership are all checked
+// at mutation time. Attempts are spent before checking TOTP to bound guessing.
+func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser, code, totp string, approve bool) error {
+ if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
+ return ErrAccessDenied
+ }
+ now := time.Now().UnixMilli()
+ var principal, expectedCode string
+ err := s.DB.QueryRowContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1
+ WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash=? AND attempts<5 AND expires_ms>?
+ RETURNING principal_uuid,code_hash`, id, domain, origin, hashAuthToken(browser), now).Scan(&principal, &expectedCode)
+ if err != nil {
+ return ErrAccessDenied
+ }
+ level := 0
+ if approve {
+ if hashAuthToken(strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(code), "-", ""))) != expectedCode {
+ return ErrAccessDenied
+ }
+ // Query errors must not silently bypass enrolled MFA.
+ var has int
+ if err := s.DB.QueryRowContext(ctx, `SELECT count(*) FROM auth_credentials WHERE principal_uuid=? AND kind='totp' AND enabled=1`, principal).Scan(&has); err != nil {
+ return err
+ }
+ if has > 0 {
+ if err := s.VerifyTOTP(principal, totp); err != nil {
+ return ErrAccessDenied
+ }
+ level = 1
+ }
+ }
+ state := "denied"
+ if approve {
+ state = "approved"
+ }
+ result, err := s.DB.ExecContext(ctx, `UPDATE auth_cli_requests SET state=?,mfa_level=? WHERE id=? AND domain_uuid=? AND state='pending' AND browser_hash=? AND expires_ms>?
+ AND EXISTS(SELECT 1 FROM auth_sessions a JOIN principals p ON p.uuid=a.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=a.domain_uuid
+ WHERE a.token_hash=? AND a.domain_uuid=? AND a.revoked_at_ms=0 AND a.expires_at_ms>? AND p.state IN ('active','readonly') AND m.state='active')`, state, level, id, domain, hashAuthToken(browser), now, hashAuthToken(browser), domain, now)
+ if err = cliChanged(result, err); err != nil {
+ return err
+ }
+ return err
+}
+
+// Poll and exchange start with a write, avoiding a WAL read-to-write upgrade.
+// Grant consumption and API-session creation commit together. No replay on a
+// lost HTTP response: a new login is required (no credential stored in grant).
+func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, verifier string) (token, username string, expires int64, err error) {
+ if s.ReadOnly {
+ err = ErrReadOnly
+ return
+ }
+ now := time.Now().UnixMilli()
+ lifetime := s.AuthSessionLifetime(domain).Milliseconds()
+ tx, err := s.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return
+ }
+ defer tx.Rollback()
+ var id, state, browser string
+ err = tx.QueryRowContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=?,state=CASE WHEN state='approved' THEN 'consumed' ELSE state END
+ WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND next_poll_ms<=? AND state IN ('pending','approved','denied')
+ RETURNING id,state,browser_hash`, now+5000, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser)
+ if errors.Is(err, sql.ErrNoRows) {
+ var exists int
+ e := tx.QueryRowContext(ctx, `SELECT count(*) FROM auth_cli_requests WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND state IN ('pending','approved','denied')`, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now).Scan(&exists)
+ if e != nil {
+ err = e
+ } else if exists > 0 {
+ err = ErrCLISlowDown
+ } else {
+ err = ErrCLIExpired
+ }
+ return
+ }
+ if err != nil {
+ return
+ }
+ if state != "consumed" {
+ err = tx.Commit()
+ if err == nil {
+ if state == "denied" {
+ err = ErrAccessDenied
+ } else {
+ err = ErrCLIPending
+ }
+ }
+ return
+ }
+ var raw string
+ raw, _, err = authToken()
+ if err != nil {
+ return
+ }
+ token = "pw_api_" + raw
+ // A disabled user, removed membership or revoked browser cannot delegate.
+ err = tx.QueryRowContext(ctx, `INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level)
+ SELECT ?,?,p.uuid,a.domain_uuid,a.auth_time_ms,min(?,a.expires_at_ms),?,max(a.mfa_level,g.mfa_level)
+ FROM auth_cli_requests g JOIN auth_sessions a ON a.token_hash=g.browser_hash JOIN principals p ON p.uuid=a.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=a.domain_uuid
+ WHERE a.token_hash=? AND a.domain_uuid=? AND a.revoked_at_ms=0 AND a.expires_at_ms>? AND p.state IN ('active','readonly') AND m.state='active'
+ AND g.id=? AND (g.mfa_level>0 OR NOT EXISTS(SELECT 1 FROM auth_credentials WHERE principal_uuid=p.uuid AND kind='totp' AND enabled=1))
+ RETURNING principal_uuid,expires_at_ms`, uuid.NewString(), hashAuthToken(token), now+lifetime, now, browser, domain, now, id).Scan(&username, &expires)
+ if errors.Is(err, sql.ErrNoRows) {
+ err = ErrAccessDenied
+ }
+ if err != nil {
+ token = ""
+ return
+ }
+ var name string
+ err = tx.QueryRowContext(ctx, `SELECT COALESCE((SELECT subject FROM principal_identities WHERE principal_uuid=? AND provider_type='password' LIMIT 1),?)`, username, username).Scan(&name)
+ if err != nil {
+ token = ""
+ return
+ }
+ username = name
+ err = tx.Commit()
+ if err != nil {
+ token = ""
+ }
+ return
+}
diff --git a/internal/store/auth_cli_test.go b/internal/store/auth_cli_test.go
new file mode 100644
index 0000000..ebbbb36
--- /dev/null
+++ b/internal/store/auth_cli_test.go
@@ -0,0 +1,253 @@
+package store
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+const cliTestOrigin = "https://wiki.example"
+
+func cliAuthFixture(t *testing.T) (*Store, string, string) {
+ t.Helper()
+ s := newSchemaTestStore(t)
+ s.authKey = make([]byte, 32) // synthetic key; no on-disk or production secrets
+ if err := s.EnsureAuthSchema(); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.ensureSchemaComponent("cli-auth"); err != nil {
+ t.Fatal(err)
+ }
+ p, err := s.BootstrapOwner("domain", "owner", "correct horse battery staple", "Owner", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ browser, err := s.CreateBrowserAuthSession("domain", p.UUID, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s, p.UUID, browser
+}
+
+func TestCLIAuthExchangeIsAtomicAndSingleUse(t *testing.T) {
+ s, _, browser := cliAuthFixture(t)
+ ctx := context.Background()
+ verifier := strings.Repeat("a", 43)
+ id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); !errors.Is(err, ErrCLIPending) {
+ t.Fatalf("pending: %v", err)
+ }
+ if _, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); !errors.Is(err, ErrCLISlowDown) {
+ t.Fatalf("poll rate: %v", err)
+ }
+ if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err == nil {
+ t.Fatal("request rebound")
+ }
+ if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.DB.Exec(`UPDATE auth_cli_requests SET next_poll_ms=0`); err != nil {
+ t.Fatal(err)
+ }
+ var wg sync.WaitGroup
+ var successes atomic.Int32
+ for range 12 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ token, name, expires, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
+ if err == nil {
+ if !strings.HasPrefix(token, "pw_api_") || name != "owner" || expires <= time.Now().UnixMilli() {
+ t.Errorf("bad issued session")
+ }
+ if _, err := s.PrincipalForSession("domain", token); err != nil {
+ t.Error(err)
+ }
+ successes.Add(1)
+ }
+ }()
+ }
+ wg.Wait()
+ if successes.Load() != 1 {
+ t.Fatalf("issued %d sessions", successes.Load())
+ }
+ var count int
+ if err := s.DB.QueryRow(`SELECT count(*) FROM auth_sessions`).Scan(&count); err != nil || count != 2 {
+ t.Fatalf("sessions=%d %v", count, err)
+ }
+}
+
+func TestCLIAuthBoundariesAndRevocation(t *testing.T) {
+ for _, mode := range []string{"domain", "origin", "verifier", "device", "expired", "denied", "suspended", "membership", "browser revoked", "new totp"} {
+ t.Run(mode, func(t *testing.T) {
+ s, principal, browser := cliAuthFixture(t)
+ ctx := context.Background()
+ verifier := strings.Repeat("b", 43)
+ id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", mode != "denied"); err != nil {
+ t.Fatal(err)
+ }
+ domain, origin := "domain", cliTestOrigin
+ var query string
+ switch mode {
+ case "domain":
+ domain = "other"
+ case "origin":
+ origin = "https://alias.example"
+ case "verifier":
+ verifier = strings.Repeat("c", 43)
+ case "device":
+ device = strings.Repeat("d", 43)
+ case "expired":
+ query = `UPDATE auth_cli_requests SET expires_ms=1`
+ case "suspended":
+ query = `UPDATE principals SET state='suspended'`
+ case "membership":
+ query = `UPDATE domain_memberships SET state='suspended'`
+ case "browser revoked":
+ query = `UPDATE auth_sessions SET revoked_at_ms=1`
+ case "new totp":
+ _, err = s.DB.Exec(`INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,created_at_ms,updated_at_ms,enabled) VALUES('totp',?,'totp',?,'invalid',1,1,1)`, principal, principal)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ if query != "" {
+ if _, err := s.DB.Exec(query); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if token, _, _, err := s.ExchangeCLIAuth(ctx, domain, origin, device, verifier); err == nil || token != "" {
+ t.Fatalf("bypass %s", mode)
+ }
+ var count int
+ if err := s.DB.QueryRow(`SELECT count(*) FROM auth_sessions`).Scan(&count); err != nil || count != 1 {
+ t.Fatalf("session leaked %d %v", count, err)
+ }
+ })
+ }
+}
+
+func TestCLIAuthApprovalAttemptsAndIssuanceCap(t *testing.T) {
+ s, _, browser := cliAuthFixture(t)
+ ctx := context.Background()
+ id, _, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
+ t.Fatal(err)
+ }
+ for range 5 {
+ if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, "wrong", "", true); err == nil {
+ t.Fatal("wrong code accepted")
+ }
+ }
+ if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err == nil {
+ t.Fatal("attempt limit bypassed")
+ }
+ for range 63 {
+ if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); !errors.Is(err, ErrCLILimit) {
+ t.Fatalf("cap: %v", err)
+ }
+ s.ReadOnly = true
+ if _, _, _, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, strings.Repeat("c", 43)); !errors.Is(err, ErrReadOnly) {
+ t.Fatalf("readonly: %v", err)
+ }
+}
+
+func TestCLIAuthSessionFailureRollsBackConsumption(t *testing.T) {
+ s, _, browser := cliAuthFixture(t)
+ ctx := context.Background()
+ verifier := strings.Repeat("e", 43)
+ id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, code, "", true); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.DB.Exec(`CREATE TRIGGER reject_cli_session BEFORE INSERT ON auth_sessions BEGIN SELECT RAISE(ABORT,'synthetic failure'); END`); err != nil {
+ t.Fatal(err)
+ }
+ if token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier); err == nil || token != "" {
+ t.Fatal("failed write accepted")
+ }
+ grant, err := s.CLIAuthRequest(ctx, "domain", cliTestOrigin, id)
+ if err != nil || grant.State != "approved" {
+ t.Fatalf("consumed without session: %+v %v", grant, err)
+ }
+}
+
+func TestCLIAuthRequiresTOTPAndPreservesLevel(t *testing.T) {
+ s, principal, browser := cliAuthFixture(t)
+ ctx := context.Background()
+ verifier := strings.Repeat("t", 43)
+ secret, err := s.BeginTOTPEnrollment(principal)
+ if err != nil {
+ t.Fatal(err)
+ }
+ code, err := totpCode(secret, time.Now().Unix()/30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.ConfirmTOTPEnrollment(principal, code); err != nil {
+ t.Fatal(err)
+ }
+ id, device, userCode, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range 3 {
+ if err := s.BeginCLIAuth(ctx, "domain", cliTestOrigin, id); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.BeginCLIAuth(ctx, "domain", cliTestOrigin, id); err == nil {
+ t.Fatal("OIDC challenge amplification allowed")
+ }
+ if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, browser); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, userCode, "", true); err == nil {
+ t.Fatal("TOTP bypass")
+ }
+ code, err = totpCode(secret, time.Now().Unix()/30+1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, userCode, code, true); err != nil {
+ t.Fatal(err)
+ }
+ token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var level int
+ if err := s.DB.QueryRow(`SELECT mfa_level FROM auth_sessions WHERE token_hash=?`, hashAuthToken(token)).Scan(&level); err != nil || level != 1 {
+ t.Fatalf("MFA not preserved: %d %v", level, err)
+ }
+}
diff --git a/internal/store/schema_modules.go b/internal/store/schema_modules.go
index ed8ff83..b5b7a2f 100644
--- a/internal/store/schema_modules.go
+++ b/internal/store/schema_modules.go
@@ -12,6 +12,7 @@ import (
// Once released, add a new version; never edit an applied definition.
// Auth, City, tasks and calendars remain in their existing migration paths.
var managedStoreSchemas = map[string][]db.SQLMigration{
+ "cli-auth": cliAuthMigrations,
"profile-contacts": profileContactMigrations,
"event-jobs": eventJobMigrations,
"projection-metadata": {{Version: 1, Name: "adopt_projection_metadata", Statements: []string{
diff --git a/internal/store/store.go b/internal/store/store.go
index 68acc91..f2b14c4 100644
--- a/internal/store/store.go
+++ b/internal/store/store.go
@@ -102,6 +102,9 @@ func NewWithDocumentRoot(
if err := st.EnsureAuthSchema(); err != nil {
panic(err)
}
+ if err := st.ensureSchemaComponent("cli-auth"); err != nil {
+ panic(err)
+ }
if err := st.EnsureTasksSchema(); err != nil {
panic(err)
}
diff --git a/pages-cli/README.md b/pages-cli/README.md
index ac99bc2..fa8b3e3 100644
--- a/pages-cli/README.md
+++ b/pages-cli/README.md
@@ -34,6 +34,34 @@ pages[default]:/manual> exit
`exit` はシェルを閉じるだけです。セッションを失効させる場合は `pages logout`。
+### OIDCでログインする
+
+OIDC連携を有効にしたDomainで利用します。サーバーとCLIの両方に **v0.3.0以降** が必要です。
+CLIのファイルだけを更新しても、v0.2.xのサーバーでは利用できません。
+
+```sh
+pages configure --origin https://pages.example.test
+pages login --oidc
+# SSH先など、ブラウザを自動で開かない場合
+pages login --oidc --no-browser
+```
+
+CLIに表示されたURLを手元のPC/スマホで開き、OIDCでログインします。
+続いてアカウント・接続先を確認し、ターミナルの確認コードを入力して承認します。
+ローカルTOTPを設定済みならTOTPも必要です。承認後はCLIが専用セッションを受け取ります。
+OIDCプロバイダーのパスワードやトークンをターミナルに入力する必要はありません。
+
+ユーザー名の指定は省略できます。指定済みならブラウザで認証したユーザーとの一致を確認し、
+不一致時は発行セッションの失効を試みて保存しません。`pages logout` 後に設定を変更できます。
+リクエストは5分で失効します。Ctrl+Cはローカルの待機を終了し、未交換リクエストは期限で失効します。
+他人から送られたURL・コードでは承認しないでください。通信断で交換結果が不明な場合は自動再送せず、
+サーバのセッション管理で不要なセッションを確認・失効してからログインし直します。
+
+`CLI OIDC login is unavailable on this server` は開始APIが利用できない場合の表示です。
+configureの接続先URLを確認し、サーバーも対応版へ更新してください。
+`OIDC login is not enabled for this domain` の場合は、対象DomainのOIDC設定を確認してください。
+`--no-browser` はブラウザーの自動起動だけを抑止し、承認待ちとセッション取得は通常どおり行います。
+
## 設定する
```sh
@@ -94,7 +122,7 @@ pages edit /guide
`pages --help`、`pages configure --help`、`pages edit --help` で引数を確認できます。
Tab補完、上下キーのプロセス内履歴に対応。複雑な引用位置の補完、Ctrl+Pのfuzzy UIは後続です。
-初期版は既存Page・既存言語の更新まで。新規作成、OIDC引き継ぎ、バイナリ更新は未実装です。
+初期版は既存Page・既存言語の更新まで。新規作成、バイナリ更新は未実装です。
競合や通信断で自動上書きせず、ローカル原稿を保持します。HTTPS必須(開発用loopbackのみHTTP可)。
詳しいURI・保存・安全性の契約は[設計書](../docs/design/ja/remote-cli.md)を参照してください。
diff --git a/pages-cli/pages b/pages-cli/pages
index 71b06a4..9c95375 100755
--- a/pages-cli/pages
+++ b/pages-cli/pages
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""pages — navigate and edit PagesWiki from your terminal (pages-cli)."""
import argparse
+import base64
import contextlib
import difflib
import fcntl
@@ -11,6 +12,7 @@ import os
from pathlib import Path
import posixpath
import re
+import secrets
import shlex
import stat
import subprocess
@@ -130,11 +132,69 @@ class Client:
raise
result = self.json('/_/auth/totp', method='POST', form={
'challenge_token': e.payload['challenge_token'], 'code': otp('TOTP: ')})
+ return self.accept_session(result)
+
+ def accept_session(self, result):
token = result.get('access_token')
if not isinstance(token, str) or not re.fullmatch(r'[A-Za-z0-9_.~-]{16,1024}', token) or result.get('token_type') != 'Bearer':
raise Failure('Server did not issue a Bearer session.')
+ duration = result.get('expires_in')
+ if not isinstance(duration, int) or isinstance(duration, bool) or not 1 <= duration <= 30*24*60*60:
+ raise Failure('Invalid session lifetime.')
self.token = token
- return time.time() + int(result['expires_in'])
+ return time.time() + duration
+
+ def login_oidc(self, no_browser=False, expected_username='', *, sleep=time.sleep, clock=time.monotonic):
+ verifier = secrets.token_urlsafe(32)
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
+ try:
+ started = self.json('/_/auth/cli/start', method='POST', form={
+ 'code_challenge': challenge, 'code_challenge_method': 'S256'})
+ except Failure as e:
+ if e.status in (404, 405, 501):
+ raise Failure('CLI OIDC login is unavailable on this server. Check the configured server URL and deploy a server version supporting /_/auth/cli/start.', e.status) from None
+ if e.status == 403 and e.payload.get('error') == 'oidc_disabled':
+ raise Failure('OIDC login is not enabled for this domain. Ask your administrator to enable it.', e.status) from None
+ raise
+ device, route, code = (started.get(k) for k in ('device_code', 'verification_uri', 'user_code'))
+ if (not isinstance(device, str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}', device)
+ or not isinstance(route, str) or not re.fullmatch(r'/_/auth/cli/verify\?request=[A-Za-z0-9_-]{43}', route)
+ or not isinstance(code, str) or not re.fullmatch(r'[A-F0-9]{4}-[A-F0-9]{4}', code)):
+ raise Failure('Invalid browser login response; no browser was opened.')
+ lifetime, interval = int(started.get('expires_in', 0)), int(started.get('interval', 0))
+ if not 1 <= lifetime <= 300 or not 5 <= interval <= 30:
+ raise Failure('Invalid browser login lifetime or polling interval.')
+ deadline = clock() + lifetime
+ print('Open this URL and approve only the request you started:')
+ print(self.base + route)
+ print('Confirmation code:', code)
+ print('Waiting for approval (up to 5 minutes). Ctrl+C cancels locally.', flush=True)
+ if not no_browser:
+ try: webbrowser.open(self.base + route, new=2)
+ except (webbrowser.Error, OSError): pass # URL remains usable on another device.
+ while clock() + interval < deadline:
+ sleep(interval)
+ try:
+ result = self.json('/_/auth/cli/token', method='POST', form={
+ 'device_code': device, 'code_verifier': verifier})
+ except Failure as e:
+ reason = e.payload.get('error')
+ if e.status == 400 and reason == 'authorization_pending': continue
+ if e.status == 400 and reason == 'slow_down':
+ interval = min(30, interval + 5); continue
+ if reason in ('access_denied', 'expired_token', 'oidc_disabled'):
+ raise Failure('Browser login denied, expired or disabled. Restart pages login --oidc.') from None
+ raise # Never retry an ambiguous token exchange or a network failure.
+ name = result.get('username')
+ expires = self.accept_session(result)
+ if (not isinstance(name, str) or not name or any(unicodedata.category(c).startswith('C') for c in name)
+ or (expected_username and name.lower() != expected_username.lower())):
+ try: self.json('/_/auth/logout', method='POST')
+ except Failure: pass
+ self.token = ''
+ raise Failure('The browser account differs from the configured username; attempted to revoke the new session.')
+ return expires, name
+ raise Failure('Browser login expired. Restart pages login --oidc.')
def listing(self, path, prefix=''):
return self.json('/_/api/v1/path-picker?' + url.urlencode({'path': path, 'mode': 'children', 'prefix': prefix}))
@@ -304,7 +364,7 @@ def configure(words, root=None):
# Configuration and session locks use this order. Never retarget an
# active credential to a different Domain or account.
with Profile(name, root).locked() as session:
- if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('username')):
+ if session.data.get('token') and (spec['origin'] != session.data.get('origin') or spec.get('username', '') != session.data.get('configured_username', session.data.get('username'))):
raise Failure('Log out this profile before changing its origin or username.')
data['profiles'][name] = spec
if len(data['profiles']) == 1: data['default_profile'] = name
@@ -480,7 +540,10 @@ def main(argv=None):
parser.print_help(); return
if args.command == 'login':
login = argparse.ArgumentParser(prog='pages login', description='Log into the configured connection. Password and TOTP are prompted privately.')
- login.parse_args(args.args)
+ login.add_argument('--oidc', action='store_true', help='Authenticate and approve in a browser; no local password required')
+ login.add_argument('--no-browser', action='store_true', help='Print the browser login URL without opening it (requires --oidc)')
+ login_args = login.parse_args(args.args)
+ if login_args.no_browser and not login_args.oidc: login.error('--no-browser requires --oidc')
elif '--help' in args.args:
execute(None, None, [args.command] + args.args); return
with contextlib.ExitStack() as stack:
@@ -494,13 +557,17 @@ def main(argv=None):
# Hold the profile lock before releasing the configuration lock.
profile = stack.enter_context(Profile(name).locked())
if args.command == 'login':
- if not spec.get('username'): raise Failure('Set your account with pages configure --username NAME.')
+ if not login_args.oidc and not spec.get('username'): raise Failure('Set your account with pages configure --username NAME, or use pages login --oidc.')
if profile.data.get('token'): raise Failure('Log out this profile before replacing its session.')
client = Client(spec['origin'], lang=lang)
- expires = client.login(spec['username'], getpass.getpass('Password: '))
- same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == spec['username']
+ if login_args.oidc:
+ expires, username = client.login_oidc(login_args.no_browser, spec.get('username', ''))
+ else:
+ username = spec['username']
+ expires = client.login(username, getpass.getpass('Password: '))
+ same_identity = profile.data.get('origin') == client.base and profile.data.get('username') == username
cwd = profile.data.get('cwd', '/') if same_identity else '/'
- profile.data = {'origin': client.base, 'username': spec['username'], 'token': client.token, 'expires': expires, 'cwd': cwd}
+ profile.data = {'origin': client.base, 'username': username, 'configured_username': spec.get('username', ''), 'token': client.token, 'expires': expires, 'cwd': cwd}
try:
profile.save()
except OSError:
@@ -512,7 +579,7 @@ def main(argv=None):
raise Failure('Could not save credentials; attempted to revoke the new session.') from None
print('Logged in. Session saved privately.'); return
if not profile.data.get('token'): raise Failure('Log in first.')
- if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('username') != spec.get('username')):
+ if args.command != 'logout' and (profile.data.get('origin') != spec['origin'] or profile.data.get('configured_username', profile.data.get('username')) != spec.get('username', '')):
raise Failure('Session and configured identity differ. Log out before reconnecting.')
if args.command not in ('logout', 'status') and profile.data.get('expires', 0) <= time.time(): raise Failure('Session expired; log out and log in again.')
client = Client(profile.data['origin'], profile.data['token'], lang)
diff --git a/pages-cli/test_pages.py b/pages-cli/test_pages.py
index 6575648..a40f9c2 100644
--- a/pages-cli/test_pages.py
+++ b/pages-cli/test_pages.py
@@ -1,4 +1,5 @@
import contextlib
+import base64
from email.message import Message
import hashlib
import io
@@ -38,6 +39,94 @@ def reply(h, status, body, mime='application/json'):
class RemoteTests(unittest.TestCase):
+ def test_oidc_polling_pkce_and_no_secret_output(self):
+ now = [0]
+ waits, calls = [], []
+ started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43,
+ 'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
+ client = Client('https://wiki.example')
+ def sleep(seconds): waits.append(seconds); now[0] += seconds
+ def request(route, **kwargs):
+ calls.append((route, kwargs))
+ if route.endswith('/start'): return started
+ polls = len(calls)-1
+ if polls == 1: raise Failure('pending',400,{'error':'authorization_pending'})
+ if polls == 2: raise Failure('slow',400,{'error':'slow_down'})
+ return {'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'anya'}
+ with patch.object(client,'json',side_effect=request), patch.object(m['webbrowser'],'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
+ expires, name = client.login_oidc(True,sleep=sleep,clock=lambda:now[0])
+ self.assertEqual(name,'anya'); self.assertGreater(expires,time.time())
+ self.assertEqual(waits,[5,5,10]); browser.assert_not_called()
+ proof = calls[1][1]['form']['code_verifier']
+ expected=base64.urlsafe_b64encode(hashlib.sha256(proof.encode()).digest()).decode().rstrip('=')
+ self.assertEqual(calls[0][1]['form']['code_challenge'],expected)
+ self.assertNotIn(proof,out.getvalue()); self.assertNotIn(started['device_code'],out.getvalue()); self.assertNotIn(client.token,out.getvalue())
+ self.assertIn('ABCD-1234',out.getvalue())
+
+ def test_oidc_unavailable_server_explained_without_retry(self):
+ for status in (404, 405, 501):
+ with self.subTest(status=status):
+ client = Client('https://wiki.example')
+ with patch.object(client, 'json', side_effect=Failure('Not found or not readable.', status)) as api, patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
+ with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught:
+ client.login_oidc(True)
+ self.assertEqual(caught.exception.status, status)
+ api.assert_called_once()
+ browser.assert_not_called()
+ self.assertEqual(out.getvalue(), '')
+ self.assertEqual(client.token, '')
+
+ def test_oidc_disabled_and_other_start_errors(self):
+ client = Client('https://wiki.example')
+ with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})):
+ with self.assertRaisesRegex(Failure, 'not enabled for this domain'):
+ client.login_oidc(True)
+ for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)):
+ with patch.object(client, 'json', side_effect=error) as api:
+ with self.assertRaises(Failure) as caught:
+ client.login_oidc(True)
+ self.assertIs(caught.exception, error)
+ api.assert_called_once()
+
+ def test_oidc_rejects_external_url_and_wrong_account(self):
+ client=Client('https://wiki.example')
+ started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5}
+ with patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser:
+ with self.assertRaises(Failure): client.login_oidc()
+ browser.assert_not_called()
+ started['verification_uri']='/_/auth/cli/verify?request='+'R'*43
+ token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'}
+ with patch.object(client,'json',side_effect=[started,token,{}]) as api, contextlib.redirect_stdout(io.StringIO()):
+ with self.assertRaises(Failure): client.login_oidc(True,'anya',sleep=lambda _:None,clock=lambda:0)
+ self.assertEqual(api.call_args.args[0],'/_/auth/logout')
+ self.assertEqual(client.token,'')
+
+ def test_oidc_cancellation_denial_and_ambiguous_exchange(self):
+ started={'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5}
+ for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]:
+ client=Client('https://wiki.example')
+ with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()):
+ with self.assertRaises(Failure): client.login_oidc(True,sleep=lambda _:None,clock=lambda:0)
+ self.assertEqual(api.call_count,2)
+ client=Client('https://wiki.example')
+ with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()):
+ def interrupt(_): raise KeyboardInterrupt()
+ with self.assertRaises(KeyboardInterrupt): client.login_oidc(True,sleep=interrupt,clock=lambda:0)
+ self.assertEqual(api.call_count,1)
+
+ def test_oidc_main_without_configured_username(self):
+ with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
+ self.configure(None,'--origin','https://wiki.example')
+ def login(client,*args,**kwargs): client.token='pw_api_'+'s'*43; return time.time()+600,'anya'
+ with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()):
+ m['main'](['login','--oidc','--no-browser'])
+ m['main'](['status'])
+ self.configure(None,'--lang','ja')
+ with Profile('default').locked() as profile:
+ self.assertEqual(profile.data['username'],'anya')
+ self.assertEqual(profile.data['configured_username'],'')
+ with self.assertRaises(Failure): self.configure(None,'--username','other')
+
def configure(self, root, *args):
with contextlib.redirect_stdout(io.StringIO()) as output:
m['configure'](list(args), root)
@@ -204,6 +293,36 @@ class RemoteTests(unittest.TestCase):
self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600)
+def oidc_integration():
+ fixture=json.load(sys.stdin)
+ original=Client.json
+ grant={}
+ def capture(client,route,**kwargs):
+ result=original(client,route,**kwargs)
+ if route=='/_/auth/cli/start': grant.update(result)
+ return result
+ def browser(target,**kwargs):
+ ident=m['url'].parse_qs(m['url'].urlsplit(target).query)['request'][0]
+ original(Client(fixture['origin']),'/__test/cli-approve',method='POST',form={'request':ident,'code':grant['user_code']})
+ return True
+ with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output:
+ m['main'](['configure','--origin',fixture['origin']])
+ with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc'])
+ with Profile('default',root).locked() as session:
+ token=session.data['token']; assert session.data['username']=='admin'
+ m['main'](['ls']); m['main'](['status'])
+ client=Client(fixture['origin'],token)
+ state=client.snapshot('path:/editor-fixture')
+ client.save(state,'# OIDC edit\n\n{{children}}\n',True)
+ assert '{{children}}' in client.snapshot('path:/editor-fixture')['markdown']
+ m['main'](['logout'])
+ assert token not in output.getvalue()
+ try: client.snapshot('path:/editor-fixture')
+ except Failure as e: assert e.status in (401,403,303)
+ else: raise AssertionError('revoked CLI session accepted')
+ print('OIDC CLI configure/login/list/authoring/logout integration passed')
+
+
def integration():
fixture=json.load(sys.stdin)
# Exercise the public entry point with persisted defaults, not only Client.
@@ -261,4 +380,5 @@ def integration():
if __name__=='__main__':
if sys.argv[1:] == ['--integration']: integration()
+ elif sys.argv[1:] == ['--oidc-integration']: oidc_integration()
else: unittest.main()
diff --git a/templates/pages/auth.gohtml b/templates/pages/auth.gohtml
index 60e5240..934370e 100644
--- a/templates/pages/auth.gohtml
+++ b/templates/pages/auth.gohtml
@@ -1,13 +1,13 @@
{{ define "auth.gohtml" }}
-
{{ if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }} · {{ .WikiName }}
+
{{ if .CLIAuth }}{{ T "auth.cli_title" }}{{ else if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }} · {{ .WikiName }}