Enable CLI language-aware editing and reuse OIDC authentication
Build and publish container images / images (push) Successful in 14m31s
Release container images / release (push) Successful in 27s

This commit is contained in:
Anya Tokugawa committed 2026-11-01 21:31:04 +09:00
1 parent 5821254535
commit 93f4ecb8f4
11 files changed
+264 -84

No files matched your search

-1
View File
@@ -164,7 +164,6 @@ func (s *Server) verifyCLIAuth(w http.ResponseWriter, r *http.Request) {
}
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)
+2 -2
View File
@@ -11,7 +11,7 @@ func init() {
"auth.cli_approve": "このCLIを承認する",
"auth.cli_deny": "拒否する",
"auth.cli_done": "リクエストは処理済みです。ターミナルに戻って結果を確認してください。この画面は閉じられます。",
"auth.cli_invalid": "確認コードまたはTOTPが正しくないか、リクエストが失効しました。5回失敗した場合はCLIでログインをやり直してください。",
"auth.cli_invalid": "確認コードが正しくないか、リクエストが失効しました。5回失敗した場合はCLIでログインをやり直してください。",
},
"en": {
"auth.cli_title": "Approve terminal access",
@@ -22,7 +22,7 @@ func init() {
"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.",
"auth.cli_invalid": "Incorrect confirmation code or expired request. After five failed attempts, restart login from the CLI.",
},
} {
for key, value := range entries {
+9 -1
View File
@@ -28,7 +28,12 @@ func cliForm(s *Server, path string, form url.Values, cookie, origin string) *ht
}
func TestCLIAuthOIDCFlow(t *testing.T) {
s, _, domain := configFixture(t)
s, api, domain := configFixture(t)
principal := s.mustCLIPrincipal(t, domain, api)
// An enrolled local factor must not add a second challenge to OIDC consent.
if _, err := s.store.DB.Exec(`INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,created_at_ms,updated_at_ms,enabled) VALUES('cli-test-totp',?,'totp',?,'synthetic-invalid',1,1,1)`, principal, principal); err != nil {
t.Fatal(err)
}
p := newOIDCTestProvider(t)
previous := oidcVerifier
oidcVerifier = p.verifier
@@ -93,6 +98,9 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
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())
}
if strings.Contains(w.Body.String(), `name="totp"`) {
t.Fatal("OIDC consent repeated local TOTP")
}
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")
+41 -1
View File
@@ -17,7 +17,14 @@ func TestRemoteCLIHTTPIntegration(t *testing.T) {
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 not installed")
}
s, _, _, _ := editorFixture(t)
s, _, domain, _ := editorFixture(t)
object, err := s.store.CreatePageAtPathInDomain(domain, "/ja-only")
if err != nil {
t.Fatal(err)
}
if _, err := s.store.SaveRevisionForLanguage(object, "<h1>日本語のページ</h1><p>{{children}}</p>", "", "ja"); 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)
@@ -36,6 +43,39 @@ func TestRemoteCLIHTTPIntegration(t *testing.T) {
}
}
func TestRemoteCLILanguageForkRequiresWritePermission(t *testing.T) {
s, token, domain, object := editorFixture(t)
principal := s.mustCLIPrincipal(t, domain, token)
if err := s.store.SetPrincipalState(domain, principal, "readonly"); err != nil {
t.Fatal(err)
}
// Changing account state revokes old sessions. Use a newly authenticated
// readonly session so this exercises write authorization, not expiration.
token, err := s.store.CreateAuthSession(domain, principal)
if err != nil {
t.Fatal(err)
}
body, err := json.Marshal(map[string]any{
"object_uuid": object, "body": "<h1>New language</h1>", "lang": "ja",
"content_type": "text/html", "base_revision_uuid": "", "editor_principal_uuid": principal,
})
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "http://localhost/_/api/v1/revisions/save", bytes.NewReader(body))
r.Header.Set("Authorization", "Bearer "+token)
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Fatalf("readonly language fork: %d %s", w.Code, w.Body.String())
}
revision, err := s.store.GetRevisionMetadataForExactLanguage(object, "ja")
if err != nil || revision.UUID != "" {
t.Fatalf("denied language fork persisted: %s %v", revision.UUID, err)
}
}
func TestRemoteCLIOIDCIntegration(t *testing.T) {
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 not installed")
+7 -17
View File
@@ -124,17 +124,18 @@ func cliChanged(result sql.Result, err error) error {
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 {
// The verified OIDC callback is the only production caller of BindCLIAuth.
// Authenticate at the provider, then require explicit local consent, not a
// second local TOTP challenge. This does not claim the provider performed MFA.
func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser, code, _ string, approve bool) error {
if s.ReadOnly || !strings.HasPrefix(browser, "pw_browser_") {
return ErrAccessDenied
}
now := time.Now().UnixMilli()
var principal, expectedCode string
var 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)
RETURNING code_hash`, id, domain, origin, hashAuthToken(browser), now).Scan(&expectedCode)
if err != nil {
return ErrAccessDenied
}
@@ -143,17 +144,6 @@ func (s *Store) DecideCLIAuth(ctx context.Context, domain, origin, id, browser,
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 {
@@ -224,7 +214,7 @@ func (s *Store) ExchangeCLIAuth(ctx context.Context, domain, origin, device, ver
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))
AND g.id=?
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
+27 -17
View File
@@ -88,9 +88,9 @@ func TestCLIAuthExchangeIsAtomicAndSingleUse(t *testing.T) {
}
func TestCLIAuthBoundariesAndRevocation(t *testing.T) {
for _, mode := range []string{"domain", "origin", "verifier", "device", "expired", "denied", "suspended", "membership", "browser revoked", "new totp"} {
for _, mode := range []string{"domain", "origin", "verifier", "device", "expired", "denied", "suspended", "membership", "browser revoked"} {
t.Run(mode, func(t *testing.T) {
s, principal, browser := cliAuthFixture(t)
s, _, browser := cliAuthFixture(t)
ctx := context.Background()
verifier := strings.Repeat("b", 43)
id, device, code, err := s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
@@ -122,11 +122,6 @@ func TestCLIAuthBoundariesAndRevocation(t *testing.T) {
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 {
@@ -202,7 +197,7 @@ func TestCLIAuthSessionFailureRollsBackConsumption(t *testing.T) {
}
}
func TestCLIAuthRequiresTOTPAndPreservesLevel(t *testing.T) {
func TestCLIAuthOIDCDoesNotRepeatLocalTOTPOrInventMFA(t *testing.T) {
s, principal, browser := cliAuthFixture(t)
ctx := context.Background()
verifier := strings.Repeat("t", 43)
@@ -232,14 +227,7 @@ func TestCLIAuthRequiresTOTPAndPreservesLevel(t *testing.T) {
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 {
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, browser, userCode, "", true); err != nil {
t.Fatal(err)
}
token, _, _, err := s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
@@ -247,7 +235,29 @@ func TestCLIAuthRequiresTOTPAndPreservesLevel(t *testing.T) {
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 != 0 {
t.Fatalf("OIDC must not invent local MFA: %d %v", level, err)
}
// Preserve an actually verified level from the bound browser session.
strongBrowser, err := s.CreateBrowserAuthSession("domain", principal, 1)
if err != nil {
t.Fatal(err)
}
id, device, userCode, err = s.StartCLIAuth(ctx, "domain", cliTestOrigin, hashAuthToken(verifier))
if err != nil {
t.Fatal(err)
}
if err := s.BindCLIAuth(ctx, "domain", cliTestOrigin, id, strongBrowser); err != nil {
t.Fatal(err)
}
if err := s.DecideCLIAuth(ctx, "domain", cliTestOrigin, id, strongBrowser, userCode, "", true); err != nil {
t.Fatal(err)
}
token, _, _, err = s.ExchangeCLIAuth(ctx, "domain", cliTestOrigin, device, verifier)
if err != nil {
t.Fatal(err)
}
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)
t.Fatalf("verified MFA level lost: %d %v", level, err)
}
}