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
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ go 1.25.0

require (
github.com/coder/websocket v1.8.15
github.com/coreos/go-oidc/v3 v3.21.0
github.com/go-jose/go-jose/v4 v4.1.4
github.com/iniwex5/quectel-qmi-go v0.6.0
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/warthog618/sms v0.3.0
go.bug.st/serial v1.6.4
golang.org/x/crypto v0.52.0
golang.org/x/oauth2 v0.36.0
golang.org/x/sys v0.47.0
golang.org/x/term v0.43.0
golang.org/x/text v0.41.0
Expand All @@ -29,7 +32,6 @@ require (
github.com/stretchr/testify v1.10.0 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/time v0.15.0 // indirect
modernc.org/libc v1.66.3 // indirect
Expand Down
8 changes: 6 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=
github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
Expand Down Expand Up @@ -53,8 +57,8 @@ golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/y
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
55 changes: 35 additions & 20 deletions internal/auth/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,17 @@ type Credentials struct {
}

type AuthenticatedSession struct {
Principal Principal
ExpiresAt time.Time
tokenHash []byte
csrfHash []byte
Principal Principal
ExpiresAt time.Time
LoginMethod string
tokenHash []byte
csrfHash []byte
}

// TokenHash returns a copy of the session digest for atomic authorization checks.
// The browser's raw session credential is never exposed by an authenticated view.
func (s AuthenticatedSession) TokenHash() []byte {
return append([]byte(nil), s.tokenHash...)
}

func New(database *store.Store, options Options) (*Service, error) {
Expand Down Expand Up @@ -154,6 +161,7 @@ func (s *Service) ResetAdminCredentials(ctx context.Context, username string, pa
return nil
}

// Login verifies the local password and persists fresh session and CSRF credentials before returning them.
func (s *Service) Login(ctx context.Context, username string, password string) (Credentials, error) {
admin, err := s.store.AdminByUsername(ctx, strings.TrimSpace(username))
if errors.Is(err, store.ErrNotFound) {
Expand All @@ -170,6 +178,20 @@ func (s *Service) Login(ctx context.Context, username string, password string) (
if err := s.store.DeleteExpiredSessions(ctx, time.Now()); err != nil {
return Credentials{}, err
}
credentials, err := s.PrepareCredentials(Principal{ID: admin.ID, Username: admin.Username})
if err != nil {
return Credentials{}, err
}
if err := s.store.CreateSession(ctx, admin.ID, hashToken(credentials.SessionToken), hashToken(credentials.CSRFToken), credentials.ExpiresAt); err != nil {
return Credentials{}, err
}
return credentials, nil
}

// PrepareCredentials generates independent local Session and CSRF material
// without persisting it. The caller must atomically commit SSO authorization
// before delivering these raw credentials to the browser.
func (s *Service) PrepareCredentials(principal Principal) (Credentials, error) {
sessionToken, err := randomToken()
if err != nil {
return Credentials{}, err
Expand All @@ -179,26 +201,15 @@ func (s *Service) Login(ctx context.Context, username string, password string) (
return Credentials{}, err
}
expiresAt := time.Now().UTC().Add(s.sessionTTL)
if err := s.store.CreateSession(
ctx,
admin.ID,
hashToken(sessionToken),
hashToken(csrfToken),
expiresAt,
); err != nil {
return Credentials{}, err
}
return Credentials{
SessionToken: sessionToken,
CSRFToken: csrfToken,
ExpiresAt: expiresAt,
Principal: Principal{
ID: admin.ID,
Username: admin.Username,
},
Principal: principal,
}, nil
}

// Authenticate resolves a live session and exposes its principal, expiry, and original login method.
func (s *Service) Authenticate(ctx context.Context, sessionToken string) (AuthenticatedSession, error) {
if sessionToken == "" {
return AuthenticatedSession{}, ErrUnauthorized
Expand All @@ -220,9 +231,10 @@ func (s *Service) Authenticate(ctx context.Context, sessionToken string) (Authen
ID: session.Admin.ID,
Username: session.Admin.Username,
},
ExpiresAt: session.ExpiresAt,
tokenHash: tokenHash,
csrfHash: session.CSRFHash,
ExpiresAt: session.ExpiresAt,
LoginMethod: session.LoginMethod,
tokenHash: tokenHash,
csrfHash: session.CSRFHash,
}, nil
}

Expand Down Expand Up @@ -497,3 +509,6 @@ func hashToken(token string) []byte {
digest := sha256.Sum256([]byte(token))
return digest[:]
}

// TokenHash derives the digest used by the store for session and CSRF material.
func TokenHash(token string) []byte { return hashToken(token) }
58 changes: 58 additions & 0 deletions internal/auth/sso_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package auth

import (
"bytes"
"context"
"errors"
"testing"

"vocat/internal/store"
)

// TestPreparedCredentialsRequireAtomicCommit verifies credential generation is independent and grants no persisted session.
func TestPreparedCredentialsRequireAtomicCommit(t *testing.T) {
service := newTestService(t)
principal := Principal{ID: 1, Username: "admin"}
first, err := service.PrepareCredentials(principal)
if err != nil {
t.Fatal(err)
}
second, err := service.PrepareCredentials(principal)
if err != nil {
t.Fatal(err)
}
if first.SessionToken == first.CSRFToken || first.SessionToken == second.SessionToken || first.CSRFToken == second.CSRFToken {
t.Fatal("local credentials must be independent random values")
}
if _, err := service.Authenticate(context.Background(), first.SessionToken); !errors.Is(err, ErrUnauthorized) {
t.Fatalf("uncommitted credentials authenticated: %v", err)
}
if _, err := service.store.SessionByTokenHash(context.Background(), TokenHash(first.SessionToken)); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("credential preparation persisted a session: %v", err)
}
}

// TestAuthenticatedSessionDigestAccessorPreservesSessionAndCSRF checks digest copies cannot mutate session or CSRF state.
func TestAuthenticatedSessionDigestAccessorPreservesSessionAndCSRF(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
credentials, err := service.Login(ctx, "admin", "correct-password")
if err != nil {
t.Fatal(err)
}
session, err := service.Authenticate(ctx, credentials.SessionToken)
if err != nil || session.LoginMethod != "password" {
t.Fatalf("password session authentication failed: %v", err)
}
if !bytes.Equal(session.TokenHash(), TokenHash(credentials.SessionToken)) {
t.Fatal("session digest accessor mismatch")
}
copy := session.TokenHash()
copy[0] ^= 0xff
if bytes.Equal(copy, session.TokenHash()) {
t.Fatal("digest accessor exposed mutable session state")
}
if _, err := service.ValidateCSRF(ctx, credentials.SessionToken, credentials.CSRFToken); err != nil {
t.Fatalf("digest accessor altered CSRF: %v", err)
}
}
Loading
Loading