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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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{
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user