Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitleaks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,9 @@ id = "local-workstation-path"
description = "Local workstation home directory path"
regex = '''(/Users|/home)/[A-Za-z0-9_.-]+/'''
keywords = ["/users/", "/home/"]

[[rules]]
id = "fanout-bearer-secret"
description = "Fanout opaque bearer secret"
regex = '''fo[iacr]_[A-Za-z0-9_-]{43}\b'''
keywords = ["foi_", "foa_", "for_", "foc_"]
2 changes: 1 addition & 1 deletion docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ stderr containing a **setup URL**:

Setup credential behavior:

- The credential carries 128 bits of entropy and lives only in memory. It is
- The credential carries 256 bits of entropy and lives only in memory. It is
never written to the database.
- It is consumed the moment the first administrator is committed, before any
other setup work. A later failure in that request does not leave a live
Expand Down
2 changes: 1 addition & 1 deletion docs/proposals/0001-logged-in-ui-shell.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ URLs are unchanged: `/chat`, `/chat/$threadId`, `/dashboards`, `/dashboards/$das
- Code step replaces the `TextInput` with Mantine `PinInput`: `length={6}`, `type="number"`, `oneTimeCode`, autofocus, `aria-label="Verification code"`. When six digits are entered the form submits itself. A failed verify clears the input, shows the server message in the existing `Alert`, and refocuses.
- Under the input: "Sent to <email> · Change email" (returns to the email step and clears the code), a "Resend code" `Button variant="subtle"` with a 30-second client cooldown that shows "Resend in 12s", and the hint "Codes expire in 5 minutes" (the server TTL in `internal/auth/code.go`). Server rate-limit responses from `/api/auth/start` are shown verbatim in the alert.
- Headings on every auth surface: 28px at base, 32px from `sm`. Copy: "Sign in" (no self-signup), "Sign in or create an account" (self-signup) stays but at the smaller size, "Create the first admin", "Save your ingest token".
- Setup success: the copy button copies the full header line (`Authorization: Bearer fo_…`) and the button label becomes "Copy header". A second, smaller "Copy token only" link copies the bare token.
- Setup success: the copy button copies the full header line (`Authorization: Bearer foi_…`) and the button label becomes "Copy header". A second, smaller "Copy token only" link copies the bare token.

## 5. Defects fixed as part of the work

Expand Down
2 changes: 1 addition & 1 deletion internal/api/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ func TestSetupLifecycleAndIngestToken(t *testing.T) {
if body["access_token"] != "" {
t.Fatal("legacy access token must not be returned")
}
if !strings.HasPrefix(body["ingest_token"], "fo_") {
if !strings.HasPrefix(body["ingest_token"], "foi_") {
t.Fatalf("ingest token = %q", body["ingest_token"])
}
if body["ingest_header_name"] != "Authorization" {
Expand Down
51 changes: 51 additions & 0 deletions internal/auth/bearer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package auth

import (
"context"
"errors"
"strings"
"testing"
)

// Nil stores make any database access fail: malformed credentials must return
// the path's normal denial before opening a connection or computing a lookup.
func TestMalformedBearerSecretsSkipDatabase(t *testing.T) {
ctx := context.Background()
store := &OAuthStore{}
links := &CodeStore{}
for _, value := range []string{"", "bad", strings.Repeat("a", 32), strings.Repeat("a", 48), "fo_" + strings.Repeat("a", 48), "foa_" + strings.Repeat("!", 43)} {
if _, err := store.VerifyAccessToken(ctx, value, ""); !errors.Is(err, ErrInvalidOAuthToken) {
t.Fatalf("access: %v", err)
}
if _, err := store.RotateRefreshToken(ctx, "", value, "", ""); !errors.Is(err, ErrInvalidOAuthGrant) {
t.Fatalf("refresh: %v", err)
}
if _, err := store.ConsumeAuthorizationCode(ctx, value); !errors.Is(err, ErrInvalidOAuthGrant) {
t.Fatalf("code: %v", err)
}
if _, ok, err := links.VerifyLoginLink(value); ok || err != nil {
t.Fatalf("login link: %v, %v", ok, err)
}
}
for _, prefix := range []string{"foi_", "foa_", "for_", "foc_"} {
value := prefix + strings.Repeat("A", 43)
if prefix != "foa_" {
if _, err := store.VerifyAccessToken(ctx, value, ""); !errors.Is(err, ErrInvalidOAuthToken) {
t.Fatal(err)
}
}
if prefix != "for_" {
if _, err := store.RotateRefreshToken(ctx, "", value, "", ""); !errors.Is(err, ErrInvalidOAuthGrant) {
t.Fatal(err)
}
}
if prefix != "foc_" {
if _, err := store.ConsumeAuthorizationCode(ctx, value); !errors.Is(err, ErrInvalidOAuthGrant) {
t.Fatal(err)
}
}
if _, ok, err := links.VerifyLoginLink(value); ok || err != nil {
t.Fatalf("login link: %v, %v", ok, err)
}
}
}
23 changes: 11 additions & 12 deletions internal/auth/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import (

"github.com/labstack/fanout/internal/db/generated"
appid "github.com/labstack/fanout/internal/id"
"github.com/labstack/fanout/internal/secret"
)

const (
codeTTL = 5 * time.Minute
loginLinkTTL = 15 * time.Minute
loginLinkTokenBytes = 16
maxAttempts = 3
purposeEmailCode = "email_code"
purposeLoginLink = "login_link"
codeTTL = 5 * time.Minute
loginLinkTTL = 15 * time.Minute
maxAttempts = 3
purposeEmailCode = "email_code"
purposeLoginLink = "login_link"
)

// GenerateCode returns a random 6-digit code.
Expand All @@ -34,13 +34,9 @@ func GenerateCode() (string, error) {
return fmt.Sprintf("%06d", n.Int64()), nil
}

// GenerateLoginLinkToken returns a credential with 128 bits of entropy.
// GenerateLoginLinkToken returns a credential with 256 bits of entropy.
func GenerateLoginLinkToken() (string, error) {
buf := make([]byte, loginLinkTokenBytes)
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("auth: generate login link token: %w", err)
}
return hex.EncodeToString(buf), nil
return secret.NewSecret()
}

// HashCode produces an HMAC-SHA256 hex digest of the code.
Expand Down Expand Up @@ -188,6 +184,9 @@ func (s *CodeStore) Verify(email, code string) (bool, error) {
// email it was issued for. Login links are purpose-bound and cannot be used as
// ordinary email verification codes.
func (s *CodeStore) VerifyLoginLink(token string) (string, bool, error) {
if !secret.ValidSecret(token, "") {
return "", false, nil
}
ctx := context.Background()
row, err := s.q.GetUnusedLoginLink(ctx, HashCode(token, s.secret))
if errors.Is(err, sql.ErrNoRows) {
Expand Down
8 changes: 5 additions & 3 deletions internal/auth/code_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"time"

appstore "github.com/labstack/fanout/internal/store"

"github.com/labstack/fanout/internal/secret"
)

func newTestCodeStore(t *testing.T) *CodeStore {
Expand All @@ -30,13 +32,13 @@ func TestGenerateCode_SixDigits(t *testing.T) {
}
}

func TestGenerateLoginLinkTokenHas128BitsOfEntropy(t *testing.T) {
func TestGenerateLoginLinkTokenHas256BitsOfEntropy(t *testing.T) {
token, err := GenerateLoginLinkToken()
if err != nil {
t.Fatalf("GenerateLoginLinkToken: %v", err)
}
if len(token) != 2*loginLinkTokenBytes {
t.Fatalf("token length = %d, want %d hex characters", len(token), 2*loginLinkTokenBytes)
if !secret.ValidSecret(token, "") {
t.Fatal("login token must encode 32 bytes as unpadded base64url")
}
}

Expand Down
30 changes: 17 additions & 13 deletions internal/auth/oauth_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ package auth

import (
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"

appid "github.com/labstack/fanout/internal/id"

"github.com/labstack/fanout/internal/secret"
)

const (
Expand Down Expand Up @@ -270,7 +270,8 @@ func (s *OAuthStore) CreateAuthorizationCode(ctx context.Context, code OAuthAuth
return "", ErrInvalidOAuthGrant
}
code.Scope = canonicalScope
raw, err := randomOAuthValue("foc_")
value, err := secret.NewSecret()
raw := "foc_" + value
if err != nil {
return "", err
}
Expand All @@ -290,6 +291,9 @@ func (s *OAuthStore) CreateAuthorizationCode(ctx context.Context, code OAuthAuth
}

func (s *OAuthStore) ConsumeAuthorizationCode(ctx context.Context, raw string) (OAuthAuthorizationCode, error) {
if !secret.ValidSecret(raw, "foc_") {
return OAuthAuthorizationCode{}, ErrInvalidOAuthGrant
}
conn, err := s.db.Conn(ctx)
if err != nil {
return OAuthAuthorizationCode{}, fmt.Errorf("oauth: open code transaction: %w", err)
Expand Down Expand Up @@ -353,6 +357,9 @@ func (s *OAuthStore) IssueTokenPair(ctx context.Context, clientID, userID, scope
}

func (s *OAuthStore) RotateRefreshToken(ctx context.Context, clientID, raw, resource, requestedScope string) (OAuthTokenPair, error) {
if !secret.ValidSecret(raw, "for_") {
return OAuthTokenPair{}, ErrInvalidOAuthGrant
}
conn, err := s.db.Conn(ctx)
if err != nil {
return OAuthTokenPair{}, fmt.Errorf("oauth: open refresh transaction: %w", err)
Expand Down Expand Up @@ -466,6 +473,9 @@ func (s *OAuthStore) RotateRefreshToken(ctx context.Context, clientID, raw, reso
// database failure is returned as a wrapped infrastructure error so callers
// can fail closed without treating an outage as a bad credential.
func (s *OAuthStore) VerifyAccessToken(ctx context.Context, raw, resource string) (OAuthTokenRecord, error) {
if !secret.ValidSecret(raw, "foa_") {
return OAuthTokenRecord{}, ErrInvalidOAuthToken
}
record, err := readOAuthToken(ctx, s.db, raw)
if errors.Is(err, ErrInvalidOAuthGrant) {
return OAuthTokenRecord{}, ErrInvalidOAuthToken
Expand Down Expand Up @@ -544,11 +554,13 @@ type oauthDB interface {
}

func (s *OAuthStore) insertTokenPair(ctx context.Context, db oauthDB, familyID, clientID, userID, scope, resource string) (OAuthTokenPair, error) {
access, err := randomOAuthValue("foa_")
accessValue, err := secret.NewSecret()
access := "foa_" + accessValue
if err != nil {
return OAuthTokenPair{}, err
}
refresh, err := randomOAuthValue("for_")
refreshValue, err := secret.NewSecret()
refresh := "for_" + refreshValue
if err != nil {
return OAuthTokenPair{}, err
}
Expand Down Expand Up @@ -595,14 +607,6 @@ func readOAuthToken(ctx context.Context, db oauthDB, raw string) (OAuthTokenReco
return record, nil
}

func randomOAuthValue(prefix string) (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("oauth: generate random value: %w", err)
}
return prefix + base64.RawURLEncoding.EncodeToString(b), nil
}

func oauthHash(value string) string {
sum := sha256.Sum256([]byte(value))
return hex.EncodeToString(sum[:])
Expand Down
4 changes: 2 additions & 2 deletions internal/auth/oauth_store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -555,9 +555,9 @@ func TestOAuthStoreCleanupKeepsLiveFamiliesAndActiveClients(t *testing.T) {
}

func TestOAuthTokenPairStringRedactsSecrets(t *testing.T) {
pair := OAuthTokenPair{AccessToken: "foa_secret", RefreshToken: "for_secret", ExpiresIn: 900, Scope: MCPScopeTelemetryRead}
pair := OAuthTokenPair{AccessToken: "foa_" + strings.Repeat("A", 43), RefreshToken: "for_" + strings.Repeat("B", 43), ExpiresIn: 900, Scope: MCPScopeTelemetryRead}
got := fmt.Sprintf("%v", pair)
if strings.Contains(got, "foa_secret") || strings.Contains(got, "for_secret") {
if strings.Contains(got, pair.AccessToken) || strings.Contains(got, pair.RefreshToken) {
t.Fatalf("String() leaked token material: %s", got)
}
if !strings.Contains(got, "REDACTED") {
Expand Down
22 changes: 4 additions & 18 deletions internal/auth/setup.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package auth

import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"sync"
"time"

"github.com/labstack/fanout/internal/secret"
)

const SetupTTL = time.Hour
Expand Down Expand Up @@ -47,7 +46,7 @@ func NewSetup() *Setup {
}

func (s *Setup) Rotate() (string, time.Time, error) {
token, err := generateSetupToken()
token, err := secret.NewSecret()
if err != nil {
return "", time.Time{}, err
}
Expand All @@ -74,7 +73,7 @@ func (s *Setup) Verify(token string) SetupStatus {
if time.Now().UTC().After(expires) {
return SetupStatusExpired
}
if subtle.ConstantTimeCompare([]byte(token), []byte(current)) != 1 {
if !secret.ValidSecret(token, "") || subtle.ConstantTimeCompare([]byte(token), []byte(current)) != 1 {
return SetupStatusWrong
}
return SetupStatusOK
Expand All @@ -86,16 +85,3 @@ func (s *Setup) Clear() {
s.expires = time.Time{}
s.mu.Unlock()
}

// setupTokenBytes is the entropy floor for a credential that creates an
// administrator. The token is delivered inside the setup URL rather than typed,
// so length costs nothing in usability.
const setupTokenBytes = 16

func generateSetupToken() (string, error) {
buf := make([]byte, setupTokenBytes)
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("generate setup token: %w", err)
}
return base64.RawURLEncoding.EncodeToString(buf), nil
}
18 changes: 14 additions & 4 deletions internal/auth/setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package auth
import (
"encoding/base64"
"regexp"
"strings"
"sync"
"testing"
"time"
)

// The setup credential is delivered inside a URL, so it is URL-safe and
// unpunctuated rather than grouped for typing.
var tokenShape = regexp.MustCompile(`^[A-Za-z0-9_-]{22,}$`)
var tokenShape = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)

func TestSetupVerifyAcceptsFreshToken(t *testing.T) {
s := NewSetup()
Expand Down Expand Up @@ -113,7 +114,7 @@ func TestSetupConcurrentAccess(t *testing.T) {
wg.Wait()
}

func TestSetupTokenCarriesAtLeast128BitsOfEntropy(t *testing.T) {
func TestSetupTokenCarries256BitsOfEntropy(t *testing.T) {
s := NewSetup()
token, _, err := s.Rotate()
if err != nil {
Expand All @@ -123,7 +124,16 @@ func TestSetupTokenCarriesAtLeast128BitsOfEntropy(t *testing.T) {
if err != nil {
t.Fatalf("setup token %q is not raw base64url: %v", token, err)
}
if len(decoded) < 16 {
t.Fatalf("setup token carries %d bits, want at least 128: a credential that creates an administrator needs a conservative entropy floor", len(decoded)*8)
if len(decoded) != 32 {
t.Fatalf("setup token carries %d bits, want 256", len(decoded)*8)
}
}

func TestSetupRejectsMatchingMalformedToken(t *testing.T) {
for _, token := range []string{strings.Repeat("a", 22), strings.Repeat("!", 43)} {
setup := &Setup{token: token, expires: time.Now().Add(time.Minute)}
if status := setup.Verify(token); status != SetupStatusWrong {
t.Fatalf("malformed setup token returned %v", status)
}
}
}
4 changes: 4 additions & 0 deletions internal/ingest/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"

"github.com/labstack/fanout/internal/secret"
"github.com/labstack/fanout/internal/settings"
)

Expand Down Expand Up @@ -65,6 +66,9 @@ func (a *ingestAuthorizer) authorize(ctx context.Context) error {
// authorizeToken owns the transport-neutral credential policy. gRPC and HTTP
// extract tokens from their respective headers, then share this verification.
func (a *ingestAuthorizer) authorizeToken(ctx context.Context, token string) error {
if !secret.ValidSecret(token, "foi_") {
return errInvalidIngestToken
}
if a.settingsStore == nil {
// Defensive: production always wires a store (cmd/fanout/main.go). Reaching
// this path means a mis-wired init; fail closed and log so it surfaces.
Expand Down
Loading
Loading