mirror of
https://github.com/bitechdev/ResolveSpec.git
synced 2026-04-11 02:13:53 +00:00
feat(security): implement keystore for user authentication keys
* Add ConfigKeyStore for in-memory key management * Introduce DatabaseKeyStore for PostgreSQL-backed key storage * Create KeyStoreAuthenticator for API key validation * Define SQL procedures for key management in PostgreSQL * Document keystore functionality and usage in KEYSTORE.md
This commit is contained in:
153
pkg/security/KEYSTORE.md
Normal file
153
pkg/security/KEYSTORE.md
Normal file
@@ -0,0 +1,153 @@
|
|||||||
|
# Keystore
|
||||||
|
|
||||||
|
Per-user named auth keys with pluggable storage. Each user can hold multiple keys of different types — JWT secrets, header API keys, OAuth2 client credentials, or generic API keys. Keys are identified by a human-readable name ("CI deploy", "mobile app") and can carry scopes and arbitrary metadata.
|
||||||
|
|
||||||
|
## Key types
|
||||||
|
|
||||||
|
| Constant | Value | Use case |
|
||||||
|
|---|---|---|
|
||||||
|
| `KeyTypeJWTSecret` | `jwt_secret` | Per-user JWT signing secret |
|
||||||
|
| `KeyTypeHeaderAPI` | `header_api` | Static API key sent in a request header |
|
||||||
|
| `KeyTypeOAuth2` | `oauth2` | OAuth2 client credentials |
|
||||||
|
| `KeyTypeGenericAPI` | `api` | General-purpose application key |
|
||||||
|
|
||||||
|
## Storage backends
|
||||||
|
|
||||||
|
### ConfigKeyStore
|
||||||
|
|
||||||
|
In-memory store seeded from a static list. Suitable for a small, fixed set of service-account keys loaded from a config file. Keys created at runtime via `CreateKey` are held in memory and lost on restart.
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Pre-load keys from config (KeyHash = SHA-256 hex of the raw key)
|
||||||
|
store := security.NewConfigKeyStore([]security.UserKey{
|
||||||
|
{
|
||||||
|
UserID: 1,
|
||||||
|
KeyType: security.KeyTypeGenericAPI,
|
||||||
|
KeyHash: "e3b0c44298fc1c149afb...", // sha256(rawKey)
|
||||||
|
Name: "CI deploy",
|
||||||
|
Scopes: []string{"deploy"},
|
||||||
|
IsActive: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### DatabaseKeyStore
|
||||||
|
|
||||||
|
Backed by PostgreSQL stored procedures. Supports optional caching (default 2-minute TTL). Apply `keystore_schema.sql` before use.
|
||||||
|
|
||||||
|
```go
|
||||||
|
db, _ := sql.Open("postgres", dsn)
|
||||||
|
|
||||||
|
store := security.NewDatabaseKeyStore(db)
|
||||||
|
|
||||||
|
// With options
|
||||||
|
store = security.NewDatabaseKeyStore(db, security.DatabaseKeyStoreOptions{
|
||||||
|
CacheTTL: 5 * time.Minute,
|
||||||
|
SQLNames: &security.KeyStoreSQLNames{
|
||||||
|
ValidateKey: "myapp_keystore_validate", // override one procedure name
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Managing keys
|
||||||
|
|
||||||
|
```go
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// Create — raw key returned once; store it securely
|
||||||
|
resp, err := store.CreateKey(ctx, security.CreateKeyRequest{
|
||||||
|
UserID: 42,
|
||||||
|
KeyType: security.KeyTypeGenericAPI,
|
||||||
|
Name: "mobile app",
|
||||||
|
Scopes: []string{"read", "write"},
|
||||||
|
})
|
||||||
|
fmt.Println(resp.RawKey) // only shown here; hashed internally
|
||||||
|
|
||||||
|
// List
|
||||||
|
keys, err := store.GetUserKeys(ctx, 42, "") // "" = all types
|
||||||
|
keys, err = store.GetUserKeys(ctx, 42, security.KeyTypeGenericAPI)
|
||||||
|
|
||||||
|
// Revoke
|
||||||
|
err = store.DeleteKey(ctx, 42, resp.Key.ID)
|
||||||
|
|
||||||
|
// Validate (used by authenticators internally)
|
||||||
|
key, err := store.ValidateKey(ctx, rawKey, "")
|
||||||
|
```
|
||||||
|
|
||||||
|
## HTTP authentication
|
||||||
|
|
||||||
|
`KeyStoreAuthenticator` wraps any `KeyStore` and implements the `Authenticator` interface. It is drop-in compatible with `DatabaseAuthenticator` and works in `CompositeSecurityProvider`.
|
||||||
|
|
||||||
|
Keys are extracted from the request in this order:
|
||||||
|
|
||||||
|
1. `Authorization: Bearer <key>`
|
||||||
|
2. `Authorization: ApiKey <key>`
|
||||||
|
3. `X-API-Key: <key>`
|
||||||
|
|
||||||
|
```go
|
||||||
|
auth := security.NewKeyStoreAuthenticator(store, "") // "" = accept any key type
|
||||||
|
// Restrict to a specific type:
|
||||||
|
auth = security.NewKeyStoreAuthenticator(store, security.KeyTypeGenericAPI)
|
||||||
|
```
|
||||||
|
|
||||||
|
Plug it into a handler:
|
||||||
|
|
||||||
|
```go
|
||||||
|
handler := resolvespec.NewHandler(db, registry,
|
||||||
|
resolvespec.WithAuthenticator(auth),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
`Login` and `Logout` return an error — key lifecycle is managed through `KeyStore` directly.
|
||||||
|
|
||||||
|
On successful validation the request context receives a `UserContext` where:
|
||||||
|
|
||||||
|
- `UserID` — from the key
|
||||||
|
- `Roles` — the key's `Scopes`
|
||||||
|
- `Claims["key_type"]` — key type string
|
||||||
|
- `Claims["key_name"]` — key name
|
||||||
|
|
||||||
|
## Database setup
|
||||||
|
|
||||||
|
Apply `keystore_schema.sql` to your PostgreSQL database. It requires the `users` table from the main `database_schema.sql`.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
\i pkg/security/keystore_schema.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates:
|
||||||
|
|
||||||
|
- `user_keys` table with indexes on `user_id`, `key_hash`, and `key_type`
|
||||||
|
- `resolvespec_keystore_get_user_keys(p_user_id, p_key_type)`
|
||||||
|
- `resolvespec_keystore_create_key(p_request jsonb)`
|
||||||
|
- `resolvespec_keystore_delete_key(p_user_id, p_key_id)`
|
||||||
|
- `resolvespec_keystore_validate_key(p_key_hash, p_key_type)`
|
||||||
|
|
||||||
|
### Custom procedure names
|
||||||
|
|
||||||
|
```go
|
||||||
|
store := security.NewDatabaseKeyStore(db, security.DatabaseKeyStoreOptions{
|
||||||
|
SQLNames: &security.KeyStoreSQLNames{
|
||||||
|
GetUserKeys: "myschema_get_keys",
|
||||||
|
CreateKey: "myschema_create_key",
|
||||||
|
DeleteKey: "myschema_delete_key",
|
||||||
|
ValidateKey: "myschema_validate_key",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Validate names at startup
|
||||||
|
names := &security.KeyStoreSQLNames{
|
||||||
|
GetUserKeys: "myschema_get_keys",
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
if err := security.ValidateKeyStoreSQLNames(names); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security notes
|
||||||
|
|
||||||
|
- Raw keys are never stored. Only the SHA-256 hex digest is persisted.
|
||||||
|
- The raw key is generated with `crypto/rand` (32 bytes, base64url-encoded) and returned exactly once in `CreateKeyResponse.RawKey`.
|
||||||
|
- Hash comparisons in `ConfigKeyStore` use `crypto/subtle.ConstantTimeCompare` to prevent timing side-channels.
|
||||||
|
- `DeleteKey` performs a soft delete (`is_active = false`). The `DatabaseKeyStore` invalidates the cache entry immediately, but due to the cache TTL a revoked key may authenticate for up to `CacheTTL` (default 2 minutes) in a distributed environment. Set `CacheTTL: 0` to disable caching if immediate revocation is required.
|
||||||
81
pkg/security/keystore.go
Normal file
81
pkg/security/keystore.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// hashSHA256Hex returns the lowercase hex SHA-256 digest of the given string.
|
||||||
|
// Used by all keystore implementations to hash raw keys before storage or lookup.
|
||||||
|
func hashSHA256Hex(raw string) string {
|
||||||
|
sum := sha256.Sum256([]byte(raw))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyType identifies the category of an auth key.
|
||||||
|
type KeyType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// KeyTypeJWTSecret is a per-user JWT signing secret for token generation.
|
||||||
|
KeyTypeJWTSecret KeyType = "jwt_secret"
|
||||||
|
// KeyTypeHeaderAPI is a static API key sent via a request header.
|
||||||
|
KeyTypeHeaderAPI KeyType = "header_api"
|
||||||
|
// KeyTypeOAuth2 holds OAuth2 client credentials (client_id / client_secret).
|
||||||
|
KeyTypeOAuth2 KeyType = "oauth2"
|
||||||
|
// KeyTypeGenericAPI is a generic application API key.
|
||||||
|
KeyTypeGenericAPI KeyType = "api"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UserKey represents a single named auth key belonging to a user.
|
||||||
|
// KeyHash stores the SHA-256 hex digest of the raw key; the raw key is never persisted.
|
||||||
|
type UserKey struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
UserID int `json:"user_id"`
|
||||||
|
KeyType KeyType `json:"key_type"`
|
||||||
|
KeyHash string `json:"key_hash"` // SHA-256 hex; never the raw key
|
||||||
|
Name string `json:"name"`
|
||||||
|
Scopes []string `json:"scopes,omitempty"`
|
||||||
|
Meta map[string]any `json:"meta,omitempty"`
|
||||||
|
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||||
|
IsActive bool `json:"is_active"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateKeyRequest specifies the parameters for a new key.
|
||||||
|
type CreateKeyRequest struct {
|
||||||
|
UserID int
|
||||||
|
KeyType KeyType
|
||||||
|
Name string
|
||||||
|
Scopes []string
|
||||||
|
Meta map[string]any
|
||||||
|
ExpiresAt *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateKeyResponse is returned exactly once when a key is created.
|
||||||
|
// The caller is responsible for persisting RawKey; it is not stored anywhere.
|
||||||
|
type CreateKeyResponse struct {
|
||||||
|
Key UserKey
|
||||||
|
RawKey string // crypto/rand 32 bytes, base64url-encoded
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyStore manages per-user auth keys with pluggable storage backends.
|
||||||
|
// Implementations: ConfigKeyStore (static list) and DatabaseKeyStore (stored procedures).
|
||||||
|
type KeyStore interface {
|
||||||
|
// CreateKey generates a new key, stores its hash, and returns the raw key once.
|
||||||
|
CreateKey(ctx context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)
|
||||||
|
|
||||||
|
// GetUserKeys returns all active, non-expired keys for a user.
|
||||||
|
// Pass an empty KeyType to return all types.
|
||||||
|
GetUserKeys(ctx context.Context, userID int, keyType KeyType) ([]UserKey, error)
|
||||||
|
|
||||||
|
// DeleteKey soft-deletes a key by ID after verifying ownership.
|
||||||
|
DeleteKey(ctx context.Context, userID int, keyID int64) error
|
||||||
|
|
||||||
|
// ValidateKey checks a raw key, returns the matching UserKey on success.
|
||||||
|
// The implementation hashes the raw key before any lookup.
|
||||||
|
// Pass an empty KeyType to accept any type.
|
||||||
|
ValidateKey(ctx context.Context, rawKey string, keyType KeyType) (*UserKey, error)
|
||||||
|
}
|
||||||
97
pkg/security/keystore_authenticator.go
Normal file
97
pkg/security/keystore_authenticator.go
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KeyStoreAuthenticator implements the Authenticator interface using a KeyStore.
|
||||||
|
// It is suitable for long-lived application credentials (API keys, JWT secrets, etc.)
|
||||||
|
// rather than interactive sessions. Login and Logout are not supported — key lifecycle
|
||||||
|
// is managed directly through the KeyStore.
|
||||||
|
//
|
||||||
|
// Key extraction order:
|
||||||
|
// 1. Authorization: Bearer <key>
|
||||||
|
// 2. Authorization: ApiKey <key>
|
||||||
|
// 3. X-API-Key header
|
||||||
|
type KeyStoreAuthenticator struct {
|
||||||
|
keyStore KeyStore
|
||||||
|
keyType KeyType // empty = accept any type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewKeyStoreAuthenticator creates a KeyStoreAuthenticator.
|
||||||
|
// Pass an empty keyType to accept keys of any type.
|
||||||
|
func NewKeyStoreAuthenticator(ks KeyStore, keyType KeyType) *KeyStoreAuthenticator {
|
||||||
|
return &KeyStoreAuthenticator{keyStore: ks, keyType: keyType}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login is not supported for keystore authentication.
|
||||||
|
func (a *KeyStoreAuthenticator) Login(_ context.Context, _ LoginRequest) (*LoginResponse, error) {
|
||||||
|
return nil, fmt.Errorf("keystore authenticator does not support login")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logout is not supported for keystore authentication.
|
||||||
|
func (a *KeyStoreAuthenticator) Logout(_ context.Context, _ LogoutRequest) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authenticate extracts an API key from the request and validates it against the KeyStore.
|
||||||
|
// Returns a UserContext built from the matching UserKey on success.
|
||||||
|
func (a *KeyStoreAuthenticator) Authenticate(r *http.Request) (*UserContext, error) {
|
||||||
|
rawKey := extractAPIKey(r)
|
||||||
|
if rawKey == "" {
|
||||||
|
return nil, fmt.Errorf("API key required (Authorization: Bearer/ApiKey <key> or X-API-Key header)")
|
||||||
|
}
|
||||||
|
|
||||||
|
userKey, err := a.keyStore.ValidateKey(r.Context(), rawKey, a.keyType)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid API key: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return userKeyToUserContext(userKey), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractAPIKey extracts a raw key from the request using the following precedence:
|
||||||
|
// 1. Authorization: Bearer <key>
|
||||||
|
// 2. Authorization: ApiKey <key>
|
||||||
|
// 3. X-API-Key header
|
||||||
|
func extractAPIKey(r *http.Request) string {
|
||||||
|
if auth := r.Header.Get("Authorization"); auth != "" {
|
||||||
|
if after, ok := strings.CutPrefix(auth, "Bearer "); ok {
|
||||||
|
return strings.TrimSpace(after)
|
||||||
|
}
|
||||||
|
if after, ok := strings.CutPrefix(auth, "ApiKey "); ok {
|
||||||
|
return strings.TrimSpace(after)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(r.Header.Get("X-API-Key"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// userKeyToUserContext converts a UserKey into a UserContext.
|
||||||
|
// Scopes are mapped to Roles. Key type and name are stored in Claims.
|
||||||
|
func userKeyToUserContext(k *UserKey) *UserContext {
|
||||||
|
claims := map[string]any{
|
||||||
|
"key_type": string(k.KeyType),
|
||||||
|
"key_name": k.Name,
|
||||||
|
}
|
||||||
|
|
||||||
|
meta := k.Meta
|
||||||
|
if meta == nil {
|
||||||
|
meta = map[string]any{}
|
||||||
|
}
|
||||||
|
|
||||||
|
roles := k.Scopes
|
||||||
|
if roles == nil {
|
||||||
|
roles = []string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &UserContext{
|
||||||
|
UserID: k.UserID,
|
||||||
|
SessionID: fmt.Sprintf("key:%d", k.ID),
|
||||||
|
Roles: roles,
|
||||||
|
Claims: claims,
|
||||||
|
Meta: meta,
|
||||||
|
}
|
||||||
|
}
|
||||||
148
pkg/security/keystore_config.go
Normal file
148
pkg/security/keystore_config.go
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ConfigKeyStore is an in-memory keystore backed by a static slice of UserKey values.
|
||||||
|
// It is designed for config-file driven setups (e.g. service accounts defined in YAML)
|
||||||
|
// with a small, bounded number of keys. For large or dynamic key sets use DatabaseKeyStore.
|
||||||
|
//
|
||||||
|
// Pre-existing entries must have KeyHash set to the SHA-256 hex of the intended raw key.
|
||||||
|
// Keys created at runtime via CreateKey are held in memory only and lost on restart.
|
||||||
|
type ConfigKeyStore struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
keys []UserKey
|
||||||
|
next int64 // monotonic ID counter for runtime-created keys (atomic)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewConfigKeyStore creates a ConfigKeyStore seeded with the provided keys.
|
||||||
|
// Pass nil or an empty slice to start with no pre-loaded keys.
|
||||||
|
// Zero-value entries (CreatedAt is zero) are treated as active and assigned the current time.
|
||||||
|
func NewConfigKeyStore(keys []UserKey) *ConfigKeyStore {
|
||||||
|
var maxID int64
|
||||||
|
copied := make([]UserKey, len(keys))
|
||||||
|
copy(copied, keys)
|
||||||
|
for i := range copied {
|
||||||
|
if copied[i].CreatedAt.IsZero() {
|
||||||
|
copied[i].IsActive = true
|
||||||
|
copied[i].CreatedAt = time.Now()
|
||||||
|
}
|
||||||
|
if copied[i].ID > maxID {
|
||||||
|
maxID = copied[i].ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &ConfigKeyStore{keys: copied, next: maxID}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateKey generates a new raw key, stores its SHA-256 hash, and returns the raw key once.
|
||||||
|
func (s *ConfigKeyStore) CreateKey(_ context.Context, req CreateKeyRequest) (*CreateKeyResponse, error) {
|
||||||
|
rawBytes := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(rawBytes); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to generate key material: %w", err)
|
||||||
|
}
|
||||||
|
rawKey := base64.RawURLEncoding.EncodeToString(rawBytes)
|
||||||
|
hash := hashSHA256Hex(rawKey)
|
||||||
|
|
||||||
|
id := atomic.AddInt64(&s.next, 1)
|
||||||
|
key := UserKey{
|
||||||
|
ID: id,
|
||||||
|
UserID: req.UserID,
|
||||||
|
KeyType: req.KeyType,
|
||||||
|
KeyHash: hash,
|
||||||
|
Name: req.Name,
|
||||||
|
Scopes: req.Scopes,
|
||||||
|
Meta: req.Meta,
|
||||||
|
ExpiresAt: req.ExpiresAt,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
IsActive: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
s.keys = append(s.keys, key)
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
return &CreateKeyResponse{Key: key, RawKey: rawKey}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUserKeys returns all active, non-expired keys for the given user.
|
||||||
|
// Pass an empty KeyType to return all types.
|
||||||
|
func (s *ConfigKeyStore) GetUserKeys(_ context.Context, userID int, keyType KeyType) ([]UserKey, error) {
|
||||||
|
now := time.Now()
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
|
||||||
|
var result []UserKey
|
||||||
|
for _, k := range s.keys {
|
||||||
|
if k.UserID != userID || !k.IsActive {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if k.ExpiresAt != nil && k.ExpiresAt.Before(now) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if keyType != "" && k.KeyType != keyType {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, k)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteKey soft-deletes a key by setting IsActive to false after ownership verification.
|
||||||
|
func (s *ConfigKeyStore) DeleteKey(_ context.Context, userID int, keyID int64) error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
for i := range s.keys {
|
||||||
|
if s.keys[i].ID == keyID {
|
||||||
|
if s.keys[i].UserID != userID {
|
||||||
|
return fmt.Errorf("key not found or permission denied")
|
||||||
|
}
|
||||||
|
s.keys[i].IsActive = false
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("key not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateKey hashes the raw key and finds a matching, active, non-expired entry.
|
||||||
|
// Uses constant-time comparison to prevent timing side-channels.
|
||||||
|
// Pass an empty KeyType to accept any type.
|
||||||
|
func (s *ConfigKeyStore) ValidateKey(_ context.Context, rawKey string, keyType KeyType) (*UserKey, error) {
|
||||||
|
hash := hashSHA256Hex(rawKey)
|
||||||
|
hashBytes, _ := hex.DecodeString(hash)
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
// Write lock: ValidateKey updates LastUsedAt on the matched entry.
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
for i := range s.keys {
|
||||||
|
k := &s.keys[i]
|
||||||
|
if !k.IsActive {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if k.ExpiresAt != nil && k.ExpiresAt.Before(now) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if keyType != "" && k.KeyType != keyType {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stored, _ := hex.DecodeString(k.KeyHash)
|
||||||
|
if subtle.ConstantTimeCompare(hashBytes, stored) != 1 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
k.LastUsedAt = &now
|
||||||
|
result := *k
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("invalid or expired key")
|
||||||
|
}
|
||||||
217
pkg/security/keystore_database.go
Normal file
217
pkg/security/keystore_database.go
Normal file
@@ -0,0 +1,217 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/cache"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DatabaseKeyStoreOptions configures DatabaseKeyStore.
|
||||||
|
type DatabaseKeyStoreOptions struct {
|
||||||
|
// Cache is an optional cache instance. If nil, uses the default cache.
|
||||||
|
Cache *cache.Cache
|
||||||
|
// CacheTTL is the duration to cache ValidateKey results.
|
||||||
|
// Default: 2 minutes.
|
||||||
|
CacheTTL time.Duration
|
||||||
|
// SQLNames provides custom procedure names. If nil, uses DefaultKeyStoreSQLNames().
|
||||||
|
SQLNames *KeyStoreSQLNames
|
||||||
|
}
|
||||||
|
|
||||||
|
// DatabaseKeyStore is a KeyStore backed by PostgreSQL stored procedures.
|
||||||
|
// All DB operations go through configurable procedure names; the raw key is
|
||||||
|
// never passed to the database.
|
||||||
|
//
|
||||||
|
// See keystore_schema.sql for the required table and procedure definitions.
|
||||||
|
//
|
||||||
|
// Note: DeleteKey invalidates the cache entry for the deleted key. Due to the
|
||||||
|
// cache TTL, a deleted key may continue to authenticate for up to CacheTTL
|
||||||
|
// (default 2 minutes) if the cache entry cannot be invalidated.
|
||||||
|
type DatabaseKeyStore struct {
|
||||||
|
db *sql.DB
|
||||||
|
sqlNames *KeyStoreSQLNames
|
||||||
|
cache *cache.Cache
|
||||||
|
cacheTTL time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDatabaseKeyStore creates a DatabaseKeyStore with optional configuration.
|
||||||
|
func NewDatabaseKeyStore(db *sql.DB, opts ...DatabaseKeyStoreOptions) *DatabaseKeyStore {
|
||||||
|
o := DatabaseKeyStoreOptions{}
|
||||||
|
if len(opts) > 0 {
|
||||||
|
o = opts[0]
|
||||||
|
}
|
||||||
|
if o.CacheTTL == 0 {
|
||||||
|
o.CacheTTL = 2 * time.Minute
|
||||||
|
}
|
||||||
|
c := o.Cache
|
||||||
|
if c == nil {
|
||||||
|
c = cache.GetDefaultCache()
|
||||||
|
}
|
||||||
|
names := MergeKeyStoreSQLNames(DefaultKeyStoreSQLNames(), o.SQLNames)
|
||||||
|
return &DatabaseKeyStore{
|
||||||
|
db: db,
|
||||||
|
sqlNames: names,
|
||||||
|
cache: c,
|
||||||
|
cacheTTL: o.CacheTTL,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateKey generates a raw key, stores its SHA-256 hash via the create procedure,
|
||||||
|
// and returns the raw key once.
|
||||||
|
func (ks *DatabaseKeyStore) CreateKey(ctx context.Context, req CreateKeyRequest) (*CreateKeyResponse, error) {
|
||||||
|
rawBytes := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(rawBytes); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to generate key material: %w", err)
|
||||||
|
}
|
||||||
|
rawKey := base64.RawURLEncoding.EncodeToString(rawBytes)
|
||||||
|
hash := hashSHA256Hex(rawKey)
|
||||||
|
|
||||||
|
type createRequest struct {
|
||||||
|
UserID int `json:"user_id"`
|
||||||
|
KeyType KeyType `json:"key_type"`
|
||||||
|
KeyHash string `json:"key_hash"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Scopes []string `json:"scopes,omitempty"`
|
||||||
|
Meta map[string]any `json:"meta,omitempty"`
|
||||||
|
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
reqJSON, err := json.Marshal(createRequest{
|
||||||
|
UserID: req.UserID,
|
||||||
|
KeyType: req.KeyType,
|
||||||
|
KeyHash: hash,
|
||||||
|
Name: req.Name,
|
||||||
|
Scopes: req.Scopes,
|
||||||
|
Meta: req.Meta,
|
||||||
|
ExpiresAt: req.ExpiresAt,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to marshal create key request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var success bool
|
||||||
|
var errorMsg sql.NullString
|
||||||
|
var keyJSON sql.NullString
|
||||||
|
|
||||||
|
query := fmt.Sprintf(`SELECT p_success, p_error, p_key::text FROM %s($1::jsonb)`, ks.sqlNames.CreateKey)
|
||||||
|
if err = ks.db.QueryRowContext(ctx, query, string(reqJSON)).Scan(&success, &errorMsg, &keyJSON); err != nil {
|
||||||
|
return nil, fmt.Errorf("create key procedure failed: %w", err)
|
||||||
|
}
|
||||||
|
if !success {
|
||||||
|
return nil, errors.New(nullStringOr(errorMsg, "create key failed"))
|
||||||
|
}
|
||||||
|
|
||||||
|
var key UserKey
|
||||||
|
if err = json.Unmarshal([]byte(keyJSON.String), &key); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse created key: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &CreateKeyResponse{Key: key, RawKey: rawKey}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUserKeys returns all active, non-expired keys for the given user.
|
||||||
|
// Pass an empty KeyType to return all types.
|
||||||
|
func (ks *DatabaseKeyStore) GetUserKeys(ctx context.Context, userID int, keyType KeyType) ([]UserKey, error) {
|
||||||
|
var success bool
|
||||||
|
var errorMsg sql.NullString
|
||||||
|
var keysJSON sql.NullString
|
||||||
|
|
||||||
|
query := fmt.Sprintf(`SELECT p_success, p_error, p_keys::text FROM %s($1, $2)`, ks.sqlNames.GetUserKeys)
|
||||||
|
if err := ks.db.QueryRowContext(ctx, query, userID, string(keyType)).Scan(&success, &errorMsg, &keysJSON); err != nil {
|
||||||
|
return nil, fmt.Errorf("get user keys procedure failed: %w", err)
|
||||||
|
}
|
||||||
|
if !success {
|
||||||
|
return nil, errors.New(nullStringOr(errorMsg, "get user keys failed"))
|
||||||
|
}
|
||||||
|
|
||||||
|
var keys []UserKey
|
||||||
|
if keysJSON.Valid && keysJSON.String != "" && keysJSON.String != "[]" {
|
||||||
|
if err := json.Unmarshal([]byte(keysJSON.String), &keys); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse user keys: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if keys == nil {
|
||||||
|
keys = []UserKey{}
|
||||||
|
}
|
||||||
|
return keys, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteKey soft-deletes a key after verifying ownership and invalidates its cache entry.
|
||||||
|
// The delete procedure returns the key_hash so no separate lookup is needed.
|
||||||
|
// Note: cache invalidation is best-effort; a cached entry may persist for up to CacheTTL.
|
||||||
|
func (ks *DatabaseKeyStore) DeleteKey(ctx context.Context, userID int, keyID int64) error {
|
||||||
|
var success bool
|
||||||
|
var errorMsg sql.NullString
|
||||||
|
var keyHash sql.NullString
|
||||||
|
|
||||||
|
query := fmt.Sprintf(`SELECT p_success, p_error, p_key_hash FROM %s($1, $2)`, ks.sqlNames.DeleteKey)
|
||||||
|
if err := ks.db.QueryRowContext(ctx, query, userID, keyID).Scan(&success, &errorMsg, &keyHash); err != nil {
|
||||||
|
return fmt.Errorf("delete key procedure failed: %w", err)
|
||||||
|
}
|
||||||
|
if !success {
|
||||||
|
return errors.New(nullStringOr(errorMsg, "delete key failed"))
|
||||||
|
}
|
||||||
|
|
||||||
|
if keyHash.Valid && keyHash.String != "" && ks.cache != nil {
|
||||||
|
_ = ks.cache.Delete(ctx, keystoreCacheKey(keyHash.String))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateKey hashes the raw key and calls the validate procedure.
|
||||||
|
// Results are cached for CacheTTL to reduce DB load on hot paths.
|
||||||
|
func (ks *DatabaseKeyStore) ValidateKey(ctx context.Context, rawKey string, keyType KeyType) (*UserKey, error) {
|
||||||
|
hash := hashSHA256Hex(rawKey)
|
||||||
|
cacheKey := keystoreCacheKey(hash)
|
||||||
|
|
||||||
|
if ks.cache != nil {
|
||||||
|
var cached UserKey
|
||||||
|
if err := ks.cache.Get(ctx, cacheKey, &cached); err == nil {
|
||||||
|
if cached.IsActive {
|
||||||
|
return &cached, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("invalid or expired key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var success bool
|
||||||
|
var errorMsg sql.NullString
|
||||||
|
var keyJSON sql.NullString
|
||||||
|
|
||||||
|
query := fmt.Sprintf(`SELECT p_success, p_error, p_key::text FROM %s($1, $2)`, ks.sqlNames.ValidateKey)
|
||||||
|
if err := ks.db.QueryRowContext(ctx, query, hash, string(keyType)).Scan(&success, &errorMsg, &keyJSON); err != nil {
|
||||||
|
return nil, fmt.Errorf("validate key procedure failed: %w", err)
|
||||||
|
}
|
||||||
|
if !success {
|
||||||
|
return nil, errors.New(nullStringOr(errorMsg, "invalid or expired key"))
|
||||||
|
}
|
||||||
|
|
||||||
|
var key UserKey
|
||||||
|
if err := json.Unmarshal([]byte(keyJSON.String), &key); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse validated key: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if ks.cache != nil {
|
||||||
|
_ = ks.cache.Set(ctx, cacheKey, key, ks.cacheTTL)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &key, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func keystoreCacheKey(hash string) string {
|
||||||
|
return "keystore:validate:" + hash
|
||||||
|
}
|
||||||
|
|
||||||
|
// nullStringOr returns s.String if valid, otherwise the fallback.
|
||||||
|
func nullStringOr(s sql.NullString, fallback string) string {
|
||||||
|
if s.Valid && s.String != "" {
|
||||||
|
return s.String
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
187
pkg/security/keystore_schema.sql
Normal file
187
pkg/security/keystore_schema.sql
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
-- Keystore schema for per-user auth keys
|
||||||
|
-- Apply alongside database_schema.sql (requires the users table)
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_keys (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
key_type VARCHAR(50) NOT NULL,
|
||||||
|
key_hash VARCHAR(64) NOT NULL UNIQUE, -- SHA-256 hex digest (64 chars)
|
||||||
|
name VARCHAR(255) NOT NULL DEFAULT '',
|
||||||
|
scopes TEXT, -- JSON array, e.g. '["read","write"]'
|
||||||
|
meta JSONB,
|
||||||
|
expires_at TIMESTAMP,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
last_used_at TIMESTAMP,
|
||||||
|
is_active BOOLEAN DEFAULT true
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_keys_user_id ON user_keys(user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_keys_key_hash ON user_keys(key_hash);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_keys_key_type ON user_keys(key_type);
|
||||||
|
|
||||||
|
-- resolvespec_keystore_get_user_keys
|
||||||
|
-- Returns all active, non-expired keys for a user.
|
||||||
|
-- Pass empty p_key_type to return all key types.
|
||||||
|
CREATE OR REPLACE FUNCTION resolvespec_keystore_get_user_keys(
|
||||||
|
p_user_id INTEGER,
|
||||||
|
p_key_type TEXT DEFAULT ''
|
||||||
|
)
|
||||||
|
RETURNS TABLE(p_success BOOLEAN, p_error TEXT, p_keys JSONB)
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE
|
||||||
|
v_keys JSONB;
|
||||||
|
BEGIN
|
||||||
|
SELECT COALESCE(
|
||||||
|
jsonb_agg(
|
||||||
|
jsonb_build_object(
|
||||||
|
'id', k.id,
|
||||||
|
'user_id', k.user_id,
|
||||||
|
'key_type', k.key_type,
|
||||||
|
'name', k.name,
|
||||||
|
'scopes', CASE WHEN k.scopes IS NOT NULL THEN k.scopes::jsonb ELSE '[]'::jsonb END,
|
||||||
|
'meta', COALESCE(k.meta, '{}'::jsonb),
|
||||||
|
'expires_at', k.expires_at,
|
||||||
|
'created_at', k.created_at,
|
||||||
|
'last_used_at', k.last_used_at,
|
||||||
|
'is_active', k.is_active
|
||||||
|
)
|
||||||
|
),
|
||||||
|
'[]'::jsonb
|
||||||
|
)
|
||||||
|
INTO v_keys
|
||||||
|
FROM user_keys k
|
||||||
|
WHERE k.user_id = p_user_id
|
||||||
|
AND k.is_active = true
|
||||||
|
AND (k.expires_at IS NULL OR k.expires_at > NOW())
|
||||||
|
AND (p_key_type = '' OR k.key_type = p_key_type);
|
||||||
|
|
||||||
|
RETURN QUERY SELECT true, NULL::TEXT, v_keys;
|
||||||
|
EXCEPTION WHEN OTHERS THEN
|
||||||
|
RETURN QUERY SELECT false, SQLERRM, NULL::JSONB;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- resolvespec_keystore_create_key
|
||||||
|
-- Inserts a new key row. key_hash is provided by the caller (Go hashes the raw key).
|
||||||
|
-- Returns the created key record (without key_hash).
|
||||||
|
CREATE OR REPLACE FUNCTION resolvespec_keystore_create_key(
|
||||||
|
p_request JSONB
|
||||||
|
)
|
||||||
|
RETURNS TABLE(p_success BOOLEAN, p_error TEXT, p_key JSONB)
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE
|
||||||
|
v_id BIGINT;
|
||||||
|
v_created_at TIMESTAMP;
|
||||||
|
v_key JSONB;
|
||||||
|
BEGIN
|
||||||
|
INSERT INTO user_keys (user_id, key_type, key_hash, name, scopes, meta, expires_at)
|
||||||
|
VALUES (
|
||||||
|
(p_request->>'user_id')::INTEGER,
|
||||||
|
p_request->>'key_type',
|
||||||
|
p_request->>'key_hash',
|
||||||
|
COALESCE(p_request->>'name', ''),
|
||||||
|
p_request->>'scopes',
|
||||||
|
p_request->'meta',
|
||||||
|
CASE WHEN p_request->>'expires_at' IS NOT NULL
|
||||||
|
THEN (p_request->>'expires_at')::TIMESTAMP
|
||||||
|
ELSE NULL
|
||||||
|
END
|
||||||
|
)
|
||||||
|
RETURNING id, created_at INTO v_id, v_created_at;
|
||||||
|
|
||||||
|
v_key := jsonb_build_object(
|
||||||
|
'id', v_id,
|
||||||
|
'user_id', (p_request->>'user_id')::INTEGER,
|
||||||
|
'key_type', p_request->>'key_type',
|
||||||
|
'name', COALESCE(p_request->>'name', ''),
|
||||||
|
'scopes', CASE WHEN p_request->>'scopes' IS NOT NULL
|
||||||
|
THEN (p_request->>'scopes')::jsonb
|
||||||
|
ELSE '[]'::jsonb END,
|
||||||
|
'meta', COALESCE(p_request->'meta', '{}'::jsonb),
|
||||||
|
'expires_at', p_request->>'expires_at',
|
||||||
|
'created_at', v_created_at,
|
||||||
|
'is_active', true
|
||||||
|
);
|
||||||
|
|
||||||
|
RETURN QUERY SELECT true, NULL::TEXT, v_key;
|
||||||
|
EXCEPTION WHEN OTHERS THEN
|
||||||
|
RETURN QUERY SELECT false, SQLERRM, NULL::JSONB;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- resolvespec_keystore_delete_key
|
||||||
|
-- Soft-deletes a key (is_active = false) after verifying ownership.
|
||||||
|
-- Returns p_key_hash so the caller can invalidate cache entries without a separate query.
|
||||||
|
CREATE OR REPLACE FUNCTION resolvespec_keystore_delete_key(
|
||||||
|
p_user_id INTEGER,
|
||||||
|
p_key_id BIGINT
|
||||||
|
)
|
||||||
|
RETURNS TABLE(p_success BOOLEAN, p_error TEXT, p_key_hash TEXT)
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE
|
||||||
|
v_hash TEXT;
|
||||||
|
BEGIN
|
||||||
|
UPDATE user_keys
|
||||||
|
SET is_active = false
|
||||||
|
WHERE id = p_key_id AND user_id = p_user_id AND is_active = true
|
||||||
|
RETURNING key_hash INTO v_hash;
|
||||||
|
|
||||||
|
IF NOT FOUND THEN
|
||||||
|
RETURN QUERY SELECT false, 'key not found or already deleted'::TEXT, NULL::TEXT;
|
||||||
|
RETURN;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
RETURN QUERY SELECT true, NULL::TEXT, v_hash;
|
||||||
|
EXCEPTION WHEN OTHERS THEN
|
||||||
|
RETURN QUERY SELECT false, SQLERRM, NULL::TEXT;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- resolvespec_keystore_validate_key
|
||||||
|
-- Looks up a key by its SHA-256 hash, checks active status and expiry,
|
||||||
|
-- updates last_used_at, and returns the key record.
|
||||||
|
-- p_key_type can be empty to accept any key type.
|
||||||
|
CREATE OR REPLACE FUNCTION resolvespec_keystore_validate_key(
|
||||||
|
p_key_hash TEXT,
|
||||||
|
p_key_type TEXT DEFAULT ''
|
||||||
|
)
|
||||||
|
RETURNS TABLE(p_success BOOLEAN, p_error TEXT, p_key JSONB)
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE
|
||||||
|
v_key_rec user_keys%ROWTYPE;
|
||||||
|
v_key JSONB;
|
||||||
|
BEGIN
|
||||||
|
SELECT * INTO v_key_rec
|
||||||
|
FROM user_keys
|
||||||
|
WHERE key_hash = p_key_hash
|
||||||
|
AND is_active = true
|
||||||
|
AND (expires_at IS NULL OR expires_at > NOW())
|
||||||
|
AND (p_key_type = '' OR key_type = p_key_type);
|
||||||
|
|
||||||
|
IF NOT FOUND THEN
|
||||||
|
RETURN QUERY SELECT false, 'invalid or expired key'::TEXT, NULL::JSONB;
|
||||||
|
RETURN;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
UPDATE user_keys SET last_used_at = NOW() WHERE id = v_key_rec.id;
|
||||||
|
|
||||||
|
v_key := jsonb_build_object(
|
||||||
|
'id', v_key_rec.id,
|
||||||
|
'user_id', v_key_rec.user_id,
|
||||||
|
'key_type', v_key_rec.key_type,
|
||||||
|
'name', v_key_rec.name,
|
||||||
|
'scopes', CASE WHEN v_key_rec.scopes IS NOT NULL
|
||||||
|
THEN v_key_rec.scopes::jsonb
|
||||||
|
ELSE '[]'::jsonb END,
|
||||||
|
'meta', COALESCE(v_key_rec.meta, '{}'::jsonb),
|
||||||
|
'expires_at', v_key_rec.expires_at,
|
||||||
|
'created_at', v_key_rec.created_at,
|
||||||
|
'last_used_at', NOW(),
|
||||||
|
'is_active', v_key_rec.is_active
|
||||||
|
);
|
||||||
|
|
||||||
|
RETURN QUERY SELECT true, NULL::TEXT, v_key;
|
||||||
|
EXCEPTION WHEN OTHERS THEN
|
||||||
|
RETURN QUERY SELECT false, SQLERRM, NULL::JSONB;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
61
pkg/security/keystore_sql_names.go
Normal file
61
pkg/security/keystore_sql_names.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// KeyStoreSQLNames holds the configurable stored procedure names used by DatabaseKeyStore.
|
||||||
|
// Use DefaultKeyStoreSQLNames() for defaults and MergeKeyStoreSQLNames() for partial overrides.
|
||||||
|
type KeyStoreSQLNames struct {
|
||||||
|
GetUserKeys string // default: "resolvespec_keystore_get_user_keys"
|
||||||
|
CreateKey string // default: "resolvespec_keystore_create_key"
|
||||||
|
DeleteKey string // default: "resolvespec_keystore_delete_key"
|
||||||
|
ValidateKey string // default: "resolvespec_keystore_validate_key"
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultKeyStoreSQLNames returns a KeyStoreSQLNames with all default resolvespec_keystore_* values.
|
||||||
|
func DefaultKeyStoreSQLNames() *KeyStoreSQLNames {
|
||||||
|
return &KeyStoreSQLNames{
|
||||||
|
GetUserKeys: "resolvespec_keystore_get_user_keys",
|
||||||
|
CreateKey: "resolvespec_keystore_create_key",
|
||||||
|
DeleteKey: "resolvespec_keystore_delete_key",
|
||||||
|
ValidateKey: "resolvespec_keystore_validate_key",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MergeKeyStoreSQLNames returns a copy of base with any non-empty fields from override applied.
|
||||||
|
// If override is nil, a copy of base is returned.
|
||||||
|
func MergeKeyStoreSQLNames(base, override *KeyStoreSQLNames) *KeyStoreSQLNames {
|
||||||
|
if override == nil {
|
||||||
|
copied := *base
|
||||||
|
return &copied
|
||||||
|
}
|
||||||
|
merged := *base
|
||||||
|
if override.GetUserKeys != "" {
|
||||||
|
merged.GetUserKeys = override.GetUserKeys
|
||||||
|
}
|
||||||
|
if override.CreateKey != "" {
|
||||||
|
merged.CreateKey = override.CreateKey
|
||||||
|
}
|
||||||
|
if override.DeleteKey != "" {
|
||||||
|
merged.DeleteKey = override.DeleteKey
|
||||||
|
}
|
||||||
|
if override.ValidateKey != "" {
|
||||||
|
merged.ValidateKey = override.ValidateKey
|
||||||
|
}
|
||||||
|
return &merged
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateKeyStoreSQLNames checks that all non-empty procedure names are valid SQL identifiers.
|
||||||
|
func ValidateKeyStoreSQLNames(names *KeyStoreSQLNames) error {
|
||||||
|
fields := map[string]string{
|
||||||
|
"GetUserKeys": names.GetUserKeys,
|
||||||
|
"CreateKey": names.CreateKey,
|
||||||
|
"DeleteKey": names.DeleteKey,
|
||||||
|
"ValidateKey": names.ValidateKey,
|
||||||
|
}
|
||||||
|
for field, val := range fields {
|
||||||
|
if val != "" && !validSQLIdentifier.MatchString(val) {
|
||||||
|
return fmt.Errorf("KeyStoreSQLNames.%s contains invalid characters: %q", field, val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user