: nply/foundationpkgs

commit 05a1dd6671387abe5e98193ad877a53aa63838d0
parent fda27eb4b4108c856924fc4b0171ddff0c020fdd
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Fri, 30 Oct 2026 00:47:02 +0530

Patch FXA authorization-code exchanges to enforce S256 PKCE
3 files changed, 244 insertions(+), 8 deletions(-)
M
Unix/minimal-fxa-server/APKBUILD
|
8
+++++---
A
Unix/minimal-fxa-server/enforce-pkce.patch
|
221
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
M
docs/firefox-sync.md
|
23
++++++++++++++++++-----
diff --git a/Unix/minimal-fxa-server/APKBUILD b/Unix/minimal-fxa-server/APKBUILD
@@ -1,6 +1,6 @@
 pkgname=minimal-fxa-server
 pkgver=0_git20260225
-pkgrel=1
+pkgrel=2
 pkgdesc="Minimal Firefox Accounts server and local user management CLI"
 url="https://github.com/ahyattdev/minimal-fxa-server"
 arch="x86_64 aarch64"

@@ -9,9 +9,11 @@ makedepends="go>=1.25.5"
 # Go's linker already strips both binaries; no target-prefixed strip is needed.
 options="net !strip"
 _commit=8ec5f0d160269f5079431d2b75574337f0552940
-source="$url/archive/$_commit.tar.gz"
+source="$url/archive/$_commit.tar.gz
+	enforce-pkce.patch"
 sha256sums="
 d336c2d13f58b915dca33a3cd20a9d44239d800fa02b38a19b1ee7fd5efbc08a  $_commit.tar.gz
+12162d02df485ec02e668f6b9591458c44c5fd2a7823908f8f620956e0a60348  enforce-pkce.patch
 "
 builddir="$srcdir/$pkgname-$_commit"
 

@@ -26,7 +28,7 @@ build() {
 	export GOOS=linux CGO_ENABLED=0
 	cd "$builddir"
 	# Explicit exe overrides abuild's default PIE flag: no glibc/musl loader needed.
-	# Serial builds fit the small CI host; upstream source remains unchanged.
+	# Serial builds fit the small CI host; only the listed PKCE patch is applied.
 	go build -p 1 -buildmode=exe -mod=readonly -trimpath -ldflags="-s -w" -o minimal-fxa-server .
 	go build -p 1 -buildmode=exe -mod=readonly -trimpath -ldflags="-s -w" -o fxa-user ./cmd/fxa-user
 	# Pure-Go Linux binaries can be checked on Debian despite the Alpine ABI target.
diff --git a/Unix/minimal-fxa-server/enforce-pkce.patch b/Unix/minimal-fxa-server/enforce-pkce.patch
@@ -0,0 +1,221 @@
+diff --git a/oauth/handler.go b/oauth/handler.go
+index cfb8862..49998c3 100644
+--- a/oauth/handler.go
++++ b/oauth/handler.go
+@@ -7,6 +7,7 @@ import (
+ 	"crypto/rand"
+ 	"crypto/rsa"
+ 	"crypto/sha256"
++	"crypto/subtle"
+ 	"encoding/base64"
+ 	"encoding/json"
+ 	"fmt"
+@@ -502,6 +503,26 @@ func (h *Handler) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
+ 	w.Write([]byte(html))
+ }
+ 
++// validateAuthCode binds an authorization code to its client and S256 PKCE verifier.
++func validateAuthCode(code *database.AuthCode, clientID, verifier string) error {
++	if clientID == "" || clientID != code.ClientID {
++		return fmt.Errorf("client_id does not match authorization code")
++	}
++	if code.CodeChallengeMethod != "S256" {
++		return fmt.Errorf("authorization code requires S256 PKCE")
++	}
++	if len(verifier) < 43 || len(verifier) > 128 ||
++		strings.Trim(verifier, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") != "" {
++		return fmt.Errorf("invalid PKCE verifier")
++	}
++	hash := sha256.Sum256([]byte(verifier))
++	challenge := base64.RawURLEncoding.EncodeToString(hash[:])
++	if subtle.ConstantTimeCompare([]byte(challenge), []byte(code.CodeChallenge)) != 1 {
++		return fmt.Errorf("PKCE verifier does not match authorization code")
++	}
++	return nil
++}
++
+ func (h *Handler) handleToken(w http.ResponseWriter, r *http.Request) {
+ 	if err := r.ParseForm(); err != nil {
+ 		http.Error(w, "Bad request", http.StatusBadRequest)
+@@ -524,6 +545,9 @@ func (h *Handler) handleToken(w http.ResponseWriter, r *http.Request) {
+ 		if result.Error != nil {
+ 			return result.Error
+ 		}
++		if err := validateAuthCode(&authCode, r.FormValue("client_id"), r.FormValue("code_verifier")); err != nil {
++			return err
++		}
+ 
+ 		// Delete the auth code immediately to prevent reuse
+ 		if err := tx.Delete(&authCode).Error; err != nil {
+@@ -1050,6 +1074,9 @@ func (h *Handler) handleAuthToken(w http.ResponseWriter, r *http.Request) {
+ 		if err := tx.Where("code = ? AND expires_at > ?", req.Code, time.Now()).First(&authCode).Error; err != nil {
+ 			return err
+ 		}
++		if err := validateAuthCode(&authCode, req.ClientID, req.CodeVerifier); err != nil {
++			return err
++		}
+ 
+ 		// Delete the auth code immediately to prevent reuse
+ 		if err := tx.Delete(&authCode).Error; err != nil {
+diff --git a/oauth/handler_test.go b/oauth/handler_test.go
+new file mode 100644
+index 0000000..ed6286a
+--- /dev/null
++++ b/oauth/handler_test.go
+@@ -0,0 +1,156 @@
++package oauth
++
++import (
++	"crypto/rand"
++	"crypto/rsa"
++	"crypto/sha256"
++	"encoding/base64"
++	"encoding/json"
++	"net/http"
++	"net/http/httptest"
++	"net/url"
++	"os"
++	"strings"
++	"testing"
++	"time"
++
++	"github.com/ahyattdev/minimal-fxa-server/database"
++	"gorm.io/driver/postgres"
++	"gorm.io/gorm"
++)
++
++// RFC 7636, Appendix B.
++const testVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
++const testChallenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
++
++func TestValidateAuthCode(t *testing.T) {
++	for _, tc := range []struct {
++		name     string
++		verifier string
++		valid    bool
++	}{
++		{"RFC 7636 vector", testVerifier, true},
++		{"maximum length", strings.Repeat("a", 128), true},
++		{"all unreserved characters", strings.Repeat("a", 43) + "AZaz09-._~", true},
++		{"empty", "", false},
++		{"too short", strings.Repeat("a", 42), false},
++		{"too long", strings.Repeat("a", 129), false},
++		{"invalid character", strings.Repeat("a", 43) + "+", false},
++	} {
++		t.Run(tc.name, func(t *testing.T) {
++			hash := sha256.Sum256([]byte(tc.verifier))
++			challenge := base64.RawURLEncoding.EncodeToString(hash[:])
++			if tc.verifier == testVerifier && challenge != testChallenge {
++				t.Fatal("incorrect RFC 7636 test vector")
++			}
++			code := database.AuthCode{ClientID: "firefox", CodeChallenge: challenge, CodeChallengeMethod: "S256"}
++			if err := validateAuthCode(&code, "firefox", tc.verifier); (err == nil) != tc.valid {
++				t.Fatalf("valid = %v, error = %v", tc.valid, err)
++			}
++		})
++	}
++}
++
++// Run with FXA_TEST_DATABASE_URI pointing to a disposable PostgreSQL database.
++// The tables are migrated once; each case runs in a rolled-back transaction.
++func TestAuthorizationCodeExchange(t *testing.T) {
++	dsn := os.Getenv("FXA_TEST_DATABASE_URI")
++	if dsn == "" {
++		t.Skip("set FXA_TEST_DATABASE_URI to a disposable PostgreSQL database")
++	}
++	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
++	if err != nil {
++		t.Fatal(err)
++	}
++	sqlDB, err := db.DB()
++	if err != nil {
++		t.Fatal(err)
++	}
++	t.Cleanup(func() { sqlDB.Close() })
++	if err := db.AutoMigrate(&database.AuthCode{}, &database.User{}, &database.OAuthToken{}); err != nil {
++		t.Fatal(err)
++	}
++	key, err := rsa.GenerateKey(rand.Reader, 2048)
++	if err != nil {
++		t.Fatal(err)
++	}
++
++	for _, endpoint := range []string{"/oauth/v1/token", "/auth/v1/oauth/token"} {
++		for _, tc := range []struct {
++			name      string
++			clientID  string
++			verifier  string
++			challenge string
++			method    string
++			status    int
++		}{
++			{"valid S256", "firefox", testVerifier, testChallenge, "S256", http.StatusOK},
++			{"wrong verifier", "firefox", strings.Repeat("x", 43), testChallenge, "S256", http.StatusBadRequest},
++			{"missing verifier", "firefox", "", testChallenge, "S256", http.StatusBadRequest},
++			{"wrong client", "another-client", testVerifier, testChallenge, "S256", http.StatusBadRequest},
++			{"missing client", "", testVerifier, testChallenge, "S256", http.StatusBadRequest},
++			{"missing challenge", "firefox", testVerifier, "", "S256", http.StatusBadRequest},
++			{"missing method", "firefox", testVerifier, testChallenge, "", http.StatusBadRequest},
++			{"plain downgrade", "firefox", testVerifier, testVerifier, "plain", http.StatusBadRequest},
++		} {
++			t.Run(endpoint+"/"+tc.name, func(t *testing.T) {
++				tx := db.Begin()
++				if tx.Error != nil {
++					t.Fatal(tx.Error)
++				}
++				t.Cleanup(func() { tx.Rollback() })
++				code := database.AuthCode{
++					Code: "test-code", ClientID: "firefox", UserID: "test-user",
++					CodeChallenge: tc.challenge, CodeChallengeMethod: tc.method,
++					ExpiresAt: time.Now().Add(time.Minute),
++				}
++				if err := tx.Create(&code).Error; err != nil {
++					t.Fatal(err)
++				}
++				mux := http.NewServeMux()
++				NewHandler("https://example.invalid", nil, tx, key, VAPIDConfig{}).RegisterRoutes(mux)
++				values := url.Values{
++					"grant_type": {"authorization_code"}, "code": {code.Code},
++					"client_id": {tc.clientID}, "code_verifier": {tc.verifier},
++				}
++				body, contentType := values.Encode(), "application/x-www-form-urlencoded"
++				if endpoint == "/auth/v1/oauth/token" {
++					payload := make(map[string]string)
++					for k := range values {
++						payload[k] = values.Get(k)
++					}
++					encoded, err := json.Marshal(payload)
++					if err != nil {
++						t.Fatal(err)
++					}
++					body, contentType = string(encoded), "application/json"
++				}
++				r := httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(body))
++				r.Header.Set("Content-Type", contentType)
++				w := httptest.NewRecorder()
++				mux.ServeHTTP(w, r)
++				if w.Code != tc.status {
++					t.Fatalf("status = %d, want %d", w.Code, tc.status)
++				}
++				var response map[string]any
++				if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
++					t.Fatal(err)
++				}
++				var remaining, tokens int64
++				if err := tx.Model(&database.AuthCode{}).Where("code = ?", code.Code).Count(&remaining).Error; err != nil {
++					t.Fatal(err)
++				}
++				if err := tx.Model(&database.OAuthToken{}).Where("user_id = ?", code.UserID).Count(&tokens).Error; err != nil {
++					t.Fatal(err)
++				}
++				if tc.status == http.StatusOK {
++					if response["access_token"] == nil || remaining != 0 || tokens != 1 {
++						t.Fatal("valid exchange must issue a token and consume the code")
++					}
++				} else if response["error"] != "invalid_grant" || remaining != 1 || tokens != 0 {
++					t.Fatal("invalid exchange must preserve the code and issue no tokens")
++				}
++			})
++		}
++	}
++}
diff --git a/docs/firefox-sync.md b/docs/firefox-sync.md
@@ -2,14 +2,19 @@
 
 ## Deployment
 
-`Unix/minimal-fxa-server/APKBUILD` packages unchanged upstream commit
-`8ec5f0d160269f5079431d2b75574337f0552940` as `0_git20260225-r1`.
+`Unix/minimal-fxa-server/APKBUILD` packages upstream commit
+`8ec5f0d160269f5079431d2b75574337f0552940` as `0_git20260225-r2`, with
+`enforce-pkce.patch`: 27 production lines enforce S256 PKCE and client-ID
+binding in both authorization-code exchange endpoints, plus regression tests.
+Missing PKCE and `plain` exchanges are intentionally rejected. Existing sessions
+and refresh-token exchanges are unchanged. Firefox Desktop 158.0.1's bundled
+source sends the required fields; a real browser login remains unverified.
 It builds both `minimal-fxa-server` and `fxa-user` with CGO disabled, explicit
 Linux/Go architecture selection and static `-buildmode=exe` output. Go strips
 symbols itself; abuild's target-prefixed strip is disabled for these binaries.
 Use the repository's CI artifacts for deployment, not ad hoc server builds.
 
-The existing deployed **r0 tarball** (not replaced by publishing the r1 APK)
+The original deployed **r0 tarball** (not replaced merely by publishing an APK)
 was published by CI for repository revision
 `0fea439e434b278805ab3aaaa8fd4c39fc5a3ff3`, build key
 `48709aa96c4dee2eb5483d471d0b1866ebc7b2584741f69e7fc42f905228be44`:

@@ -127,8 +132,16 @@ may still have their own Mozilla Push connections until configured otherwise.
 The server-side authentication/storage path is local; total client-side Mozilla
 network independence remains unverified.
 
-The user explicitly accepted upstream's deterministic key derivation from user
-ID and timestamp. No security fork or source hardening was introduced.
+**Test-only security posture:** the PKCE patch does not fix predictable Sync
+keys derived from non-secret user ID/timestamp inputs, no-op credential
+revocation, or outstanding Go/runtime dependency findings. Do not interpret
+successful health checks as security approval for sensitive Sync data.
+The original deployment accepted the key-derivation risk; r2 only fixes PKCE.
+
+The patch's unit tests run during package checks. Its PostgreSQL endpoint tests
+require `FXA_TEST_DATABASE_URI` pointing at a disposable database (never the live
+Accounts database); each case rolls back its transaction. Run against the patched
+source with `FXA_TEST_DATABASE_URI='...' go test -race ./oauth`.
 
 Back up all three databases (`minimal_fxa`, `syncstorage_rs`, `tokenserver_rs`)
 and both secret configuration files before upgrades. Preserve signing/master