ci: expand shared package validation and test coverage
- Add lint, formatting, vet, and publish workflow checks - Run Go database tests with PostgreSQL and add Java tests - Make consumer sync opt-in; update docs and Go dependency
This commit is contained in:
1 parent
937f51b4fb
commit
0ff94f9b10
107 files changed
+10124
-410
No files matched your search
@@ -68,7 +68,9 @@ type Client struct {
|
||||
// restrictions can be enforced. Empty means "don't identify" - the
|
||||
// caller is treated as unrestricted; see AuthServer's project-scoping
|
||||
// feature and WithProjectKey.
|
||||
projectKey string
|
||||
projectKey string
|
||||
validationMu sync.Mutex
|
||||
validationCache map[[32]byte]validationCacheEntry
|
||||
}
|
||||
|
||||
// ProjectKeyHeader is the header Client attaches to every request identifying
|
||||
@@ -112,9 +114,10 @@ func WithProjectKey(key string) Option {
|
||||
// is always left as-is, overriding the inference.
|
||||
func New(baseURL string, opts ...Option) *Client {
|
||||
c := &Client{
|
||||
baseURL: normalizeBaseURL(baseURL),
|
||||
httpClient: &http.Client{Timeout: 5 * time.Second},
|
||||
cookieName: DefaultCookieName,
|
||||
baseURL: normalizeBaseURL(baseURL),
|
||||
httpClient: &http.Client{Timeout: 5 * time.Second},
|
||||
cookieName: DefaultCookieName,
|
||||
validationCache: make(map[[32]byte]validationCacheEntry),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
@@ -138,6 +141,7 @@ func (c *Client) SetBaseURL(baseURL string) {
|
||||
c.baseURLMu.Lock()
|
||||
c.baseURL = normalized
|
||||
c.baseURLMu.Unlock()
|
||||
c.clearValidationCache()
|
||||
}
|
||||
|
||||
func (c *Client) getBaseURL() string {
|
||||
@@ -155,6 +159,33 @@ func (c *Client) setProjectKeyHeader(req *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// ForwardedForHeader carries the end user's address to AuthServer on the
|
||||
// credential calls (see WithClientIP). AuthServer reads it only when the
|
||||
// calling service's own address is listed in its TRUSTED_PROXIES, so sending
|
||||
// it changes nothing for a deployment that has not opted in.
|
||||
const ForwardedForHeader = "X-Forwarded-For"
|
||||
|
||||
type clientIPKey struct{}
|
||||
|
||||
// WithClientIP returns a context that makes Login, Register, TOTPVerify,
|
||||
// TOTPDisable and the password-reset calls send ip as X-Forwarded-For, so
|
||||
// AuthServer's per-address limits see the end user instead of this service.
|
||||
// Pass an address the caller has already verified (for example
|
||||
// auth.Service's trusted-proxy-aware client address), never a raw request
|
||||
// header. Anything that is not an IP address is ignored.
|
||||
func WithClientIP(ctx context.Context, ip string) context.Context {
|
||||
return context.WithValue(ctx, clientIPKey{}, strings.TrimSpace(ip))
|
||||
}
|
||||
|
||||
// setClientIPHeader attaches ForwardedForHeader when ctx carries a valid
|
||||
// address from WithClientIP; a no-op otherwise.
|
||||
func setClientIPHeader(ctx context.Context, req *http.Request) {
|
||||
ip, _ := ctx.Value(clientIPKey{}).(string)
|
||||
if parsed := net.ParseIP(ip); parsed != nil {
|
||||
req.Header.Set(ForwardedForHeader, parsed.String())
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeBaseURL(baseURL string) string {
|
||||
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
if trimmed == "" {
|
||||
@@ -211,6 +242,9 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
|
||||
if token == "" {
|
||||
return nil, ErrInvalidSession
|
||||
}
|
||||
if user, cachedErr, ok := c.cachedValidation(token); ok {
|
||||
return user, cachedErr
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api/session/validate", nil)
|
||||
if err != nil {
|
||||
@@ -233,15 +267,22 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
c.cacheValidation(token, nil, false)
|
||||
return nil, ErrInvalidSession
|
||||
}
|
||||
return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK || !payload.Valid {
|
||||
if resp.StatusCode == http.StatusUnauthorized || (resp.StatusCode == http.StatusOK && !payload.Valid) {
|
||||
c.cacheValidation(token, nil, false)
|
||||
return nil, ErrInvalidSession
|
||||
}
|
||||
return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, nil
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("authclient: AuthServer returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
user := &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}
|
||||
c.cacheValidation(token, user, true)
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// contextKey is unexported so only this package can set/read the resolved
|
||||
@@ -451,6 +492,7 @@ func (c *Client) call(ctx context.Context, method, path, token string, body, out
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
c.setProjectKeyHeader(req)
|
||||
setClientIPHeader(ctx, req)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -535,6 +577,7 @@ func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.invalidateValidation(token)
|
||||
return resp.Cookies(), nil
|
||||
}
|
||||
|
||||
@@ -623,6 +666,9 @@ func (c *Client) CreateManagedUser(ctx context.Context, token string, input Mana
|
||||
// UpdateManagedUser calls PUT /api/admin/users/{id}.
|
||||
func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error {
|
||||
_, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil)
|
||||
if err == nil {
|
||||
c.invalidateValidation(token)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -110,3 +110,43 @@ func TestSetBaseURLIgnoresBlank(t *testing.T) {
|
||||
t.Fatalf("SetBaseURL(blank) changed baseURL to %q, want unchanged", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithClientIPSendsXForwardedForOnCredentialCalls(t *testing.T) {
|
||||
var seen []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
seen = append(seen, r.Header.Get(ForwardedForHeader))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"user":{"id":1,"username":"a"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client := New(server.URL)
|
||||
|
||||
ctx := WithClientIP(context.Background(), " 203.0.113.9 ")
|
||||
if _, err := client.Login(ctx, "a", "password123", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.Register(WithClientIP(context.Background(), "2001:db8::1"), "a", "a@b.com", "password123"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := client.TOTPVerify(ctx, "tok", "123456"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// No address, and values that are not IP addresses, send no header.
|
||||
if _, err := client.Login(context.Background(), "a", "password123", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{"", "not-an-ip", "203.0.113.9\r\nX-Evil: 1"} {
|
||||
if _, err := client.Login(WithClientIP(context.Background(), bad), "a", "password123", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
want := []string{"203.0.113.9", "2001:db8::1", "203.0.113.9", "", "", "", ""}
|
||||
if len(seen) != len(want) {
|
||||
t.Fatalf("server saw %d requests, want %d", len(seen), len(want))
|
||||
}
|
||||
for i := range want {
|
||||
if seen[i] != want[i] {
|
||||
t.Errorf("request %d X-Forwarded-For = %q, want %q", i, seen[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package authclient
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
validationCacheTTL = 2 * time.Second
|
||||
maxValidationCacheSize = 10000
|
||||
)
|
||||
|
||||
type validationCacheEntry struct {
|
||||
user User
|
||||
valid bool
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
func (c *Client) cachedValidation(token string) (*User, error, bool) {
|
||||
key := sha256.Sum256([]byte(token))
|
||||
now := time.Now()
|
||||
c.validationMu.Lock()
|
||||
defer c.validationMu.Unlock()
|
||||
entry, ok := c.validationCache[key]
|
||||
if !ok {
|
||||
return nil, nil, false
|
||||
}
|
||||
if !now.Before(entry.expires) {
|
||||
delete(c.validationCache, key)
|
||||
return nil, nil, false
|
||||
}
|
||||
if !entry.valid {
|
||||
return nil, ErrInvalidSession, true
|
||||
}
|
||||
user := entry.user
|
||||
return &user, nil, true
|
||||
}
|
||||
|
||||
func (c *Client) cacheValidation(token string, user *User, valid bool) {
|
||||
key := sha256.Sum256([]byte(token))
|
||||
now := time.Now()
|
||||
c.validationMu.Lock()
|
||||
defer c.validationMu.Unlock()
|
||||
if c.validationCache == nil {
|
||||
c.validationCache = make(map[[32]byte]validationCacheEntry)
|
||||
}
|
||||
if len(c.validationCache) >= maxValidationCacheSize {
|
||||
for existing, entry := range c.validationCache {
|
||||
if !now.Before(entry.expires) {
|
||||
delete(c.validationCache, existing)
|
||||
}
|
||||
}
|
||||
if len(c.validationCache) >= maxValidationCacheSize {
|
||||
for existing := range c.validationCache {
|
||||
delete(c.validationCache, existing)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
entry := validationCacheEntry{valid: valid, expires: now.Add(validationCacheTTL)}
|
||||
if user != nil {
|
||||
entry.user = *user
|
||||
}
|
||||
c.validationCache[key] = entry
|
||||
}
|
||||
|
||||
func (c *Client) invalidateValidation(token string) {
|
||||
key := sha256.Sum256([]byte(token))
|
||||
c.validationMu.Lock()
|
||||
delete(c.validationCache, key)
|
||||
c.validationMu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Client) clearValidationCache() {
|
||||
c.validationMu.Lock()
|
||||
c.validationCache = make(map[[32]byte]validationCacheEntry)
|
||||
c.validationMu.Unlock()
|
||||
}
|
||||
Reference in new issue
Block a user