Documentation
¶
Index ¶
- Constants
- func Fetch[T any](ctx context.Context, cache *JetStreamKV, key string, ...) (T, error)
- func NatsOptionsFromConfig(name string, cfg NATSClientConfig) []nats.Option
- type BucketOptions
- type JSLock
- type JetStreamKV
- func (c *JetStreamKV) AcquireLock(key string, ttl time.Duration) (*JSLock, error)
- func (c *JetStreamKV) Create(key string, value []byte) (uint64, error)
- func (c *JetStreamKV) Delete(key string) error
- func (c *JetStreamKV) Get(key string) (nats.KeyValueEntry, error)
- func (c *JetStreamKV) Set(key string, value []byte) (uint64, error)
- func (c *JetStreamKV) Update(key string, value []byte, revision uint64) (uint64, error)
- type KVEvent
- type KVSubscriber
- type KVSubscriberOptions
- type Lock
- type NATSClient
- type NATSClientConfig
- type PasswordLockoutState
- type UserLockState
Constants ¶
const ( WORKSPACE_PROVISION_JOBS_BUCKET = "workspace-provision-jobs" // LOCKED_USERS_BUCKET holds per-user account lock state, keyed by // username. See UserLockState (userlock.go) for the value type stored in // it and the producer/consumer contract between api-server and ssh-proxy. LOCKED_USERS_BUCKET = "locked-users" // PASSWORD_LOCKOUT_BUCKET holds per-username password brute-force // tracking state, keyed by username. See PasswordLockoutState // (passwordlockout.go) for the value type stored in it. Unlike // LOCKED_USERS_BUCKET, identity is the sole producer and consumer: it // reads and writes this bucket directly inside AuthUserPassword, so the // lockout applies consistently no matter which caller (ssh-proxy, // api-server, or any other gRPC client) invoked it. PASSWORD_LOCKOUT_BUCKET = "password-lockouts" // PASSWORD_RESET_TOKEN_BUCKET holds single-use password-reset tokens, // keyed by hex(sha256(token)), value = username. Identity is the sole // producer and consumer. TTL bounds how long an issued reset link stays // valid; ConfirmPasswordReset deletes a token immediately on successful // use, but the bucket-wide TTL also cleans up abandoned tokens. PASSWORD_RESET_TOKEN_BUCKET = "password-reset-tokens" // PASSWORD_RESET_COOLDOWN_BUCKET holds a per-username marker created by // RequestPasswordReset to throttle repeat requests. Keyed by username, // empty value. A separate bucket from PASSWORD_RESET_TOKEN_BUCKET // because JetStream KV TTL is bucket-wide and the two need very // different lifetimes (short cooldown vs. longer token validity). PASSWORD_RESET_COOLDOWN_BUCKET = "password-reset-cooldown" )
Variables ¶
This section is empty.
Functions ¶
func Fetch ¶
func Fetch[T any](ctx context.Context, cache *JetStreamKV, key string, fetch func(context.Context) (T, error), ) (T, error)
Fetch retrieves a value from cache by key. On miss, calls fetch(), caches result with TTL, and returns it.
func NatsOptionsFromConfig ¶
func NatsOptionsFromConfig(name string, cfg NATSClientConfig) []nats.Option
Types ¶
type BucketOptions ¶
type BucketOptions struct {
Bucket string `yaml:"bucket" json:"bucket"`
BucketTTL time.Duration `yaml:"bucketTTL" json:"bucketTTL"`
History uint8 `yaml:"history" json:"history"`
Storage nats.StorageType `yaml:"storage" json:"storage"`
Replicas int `yaml:"replicas" json:"replicas"`
}
BucketOptions holds options for the JetStream cache bucket.
type JSLock ¶
type JSLock struct {
// contains filtered or unexported fields
}
JSLock is a guard returned by AcquireLock. Call Release() when done.
func (*JSLock) Release ¶
Release attempts to release the lock by deleting its key, guarded by a CAS revision check. It only releases if we still own the lock; otherwise it is a no-op.
The key is deleted rather than CAS-updated to an empty/zeroed envelope: AcquireLock's takeover check only reclaims an existing key once its ExpireAt has passed (cur.ExpireAt > 0 && now >= cur.ExpireAt), and a zeroed envelope has ExpireAt == 0, which never satisfies that condition. Leaving such an envelope behind would make the key permanently unacquirable — every future AcquireLock on it would fail immediately with nats.ErrKeyExists, even with no other holder in sight.
type JetStreamKV ¶
type JetStreamKV struct {
// contains filtered or unexported fields
}
JetStreamKV is a cache client backed by NATS JetStream KV store.
func (*JetStreamKV) AcquireLock ¶
AcquireLock attempts to acquire a lock at key with TTL. Returns nats.ErrKeyExists if the lock is already held and not expired. On success returns a guard; call guard.Release() to release. Implemented using KV Create() and CAS Update() when taking over expired locks.
func (*JetStreamKV) Create ¶
func (c *JetStreamKV) Create(key string, value []byte) (uint64, error)
Create stores raw bytes at key only if missing. Returns nats.ErrKeyExists if already present.
func (*JetStreamKV) Delete ¶
func (c *JetStreamKV) Delete(key string) error
Delete removes a key. Returns nats.ErrKeyNotFound if missing.
func (*JetStreamKV) Get ¶
func (c *JetStreamKV) Get(key string) (nats.KeyValueEntry, error)
Get retrieves raw bytes at key.
type KVEvent ¶
type KVEvent struct {
Bucket string
Key string
Op string
Value []byte
Seq uint64
Time time.Time
Msg *nats.Msg
}
KVEvent represents a single key-value event.
type KVSubscriber ¶
type KVSubscriber struct {
// contains filtered or unexported fields
}
KVSubscriber is a NATS JetStream KV bucket subscriber.
func (*KVSubscriber) StartPull ¶
func (s *KVSubscriber) StartPull(ctx context.Context, handler func(context.Context, *KVEvent) error) error
StartPull runs the pull loop until ctx is canceled. handler must be idempotent; Ack happens only if handler returns nil.
func (*KVSubscriber) Stop ¶
func (s *KVSubscriber) Stop() error
Stop unsubscribes from the KV bucket.
type KVSubscriberOptions ¶
type KVSubscriberOptions struct {
DeliverAll bool // true to replay all from start; false to get new only
AckWait time.Duration
MaxAckPending int
FetchBatchSize int
FetchMaxWait time.Duration
}
KVSubscriberOptions holds options for the KVSubscriber.
type NATSClient ¶
type NATSClient struct {
// contains filtered or unexported fields
}
func NewNATSClient ¶
func NewNATSClient(cfg NATSClientConfig) (*NATSClient, error)
func (*NATSClient) Close ¶
func (c *NATSClient) Close()
func (*NATSClient) NewKV ¶
func (c *NATSClient) NewKV(bucketOpts BucketOptions) (*JetStreamKV, error)
func (*NATSClient) NewKVSubscriber ¶
func (c *NATSClient) NewKVSubscriber(bucket, durable string, o KVSubscriberOptions) (*KVSubscriber, error)
NewKVSubscriber connects to NATS using your config and prepares a subscriber. Close() will drain/close the connection (since this constructor owns it).
func (*NATSClient) ServerVersion ¶ added in v0.49.0
func (c *NATSClient) ServerVersion() string
ServerVersion returns the version of the NATS server this client is currently connected to, as advertised in the server's INFO protocol (e.g. "2.10.7"). It returns "" when the client is not connected.
type NATSClientConfig ¶
type NATSClientConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
URL string `yaml:"url" json:"url"`
Username string `yaml:"username" json:"username"`
Password string `yaml:"password" json:"password"`
Token string `yaml:"token" json:"token"`
MaxReconnects int `yaml:"maxReconnects" json:"maxReconnects"`
ReconnectWait time.Duration `yaml:"reconnectWait" json:"reconnectWait"`
}
NATSClientConfig holds NATS connection.
type PasswordLockoutState ¶ added in v0.34.3
type PasswordLockoutState struct {
// FailedAttempts is the number of consecutive failed password attempts
// since the last success or lockout expiry.
FailedAttempts int `json:"failedAttempts,omitempty"`
// LockedUntil is the unix time (seconds) the account remains locked
// until. Zero means not currently locked.
LockedUntil int64 `json:"lockedUntil,omitempty"`
}
PasswordLockoutState is the JSON value stored in PASSWORD_LOCKOUT_BUCKET for a username, tracking password-authentication failures.
identity is the sole producer and consumer: AuthUserPassword reads and writes this bucket directly on every call, regardless of which caller (ssh-proxy, api-server, or any other gRPC client) invoked it, so the lockout is enforced consistently no matter which auth surface is used. This is distinct from UserLockState/LOCKED_USERS_BUCKET, which tracks an administrative lock set by api-server and observed by ssh-proxy.
type UserLockState ¶ added in v0.34.3
type UserLockState struct {
// Locked is whether the account is currently locked. Consumers should
// treat any request/connection for this username as denied while true.
Locked bool `json:"locked,omitempty"`
// SessionsInvalidBefore is the unix time (seconds) of the most recent
// lock. Unlike Locked, it survives the account being unlocked again, so
// api-server can keep rejecting a web session that predates the lock
// even after unlock — forcing a fresh login rather than silently
// resuming. ssh-proxy has no equivalent persistent session concept and
// can ignore this field.
SessionsInvalidBefore int64 `json:"sessionsInvalidBefore,omitempty"`
}
UserLockState is the JSON value stored in LOCKED_USERS_BUCKET for a username.
api-server is the sole producer: it writes an entry whenever a user is locked or unlocked (see its setUserLocked), and its own AuthMiddleware reads the bucket directly on every request as a fast-path check.
ssh-proxy is a consumer: it subscribes to bucket changes (see NATSClient.NewKVSubscriber, which delivers a KVEvent per write) and, on any event decoding to UserLockState.Locked == true, closes its live SSH connection(s) for that username. It should ignore Locked == false — unlocking a web account doesn't imply an SSH session should be allowed to resume; the user reconnects normally on their next attempt.