Implement Phase 1: core framework, operational tooling, and runbook
Core packages: crypto (Argon2id/AES-256-GCM), config (TOML/viper), db (SQLite/migrations), barrier (encrypted storage), seal (state machine with rate-limited unseal), auth (MCIAS integration with token cache), policy (priority-based ACL engine), engine (interface + registry). Server: HTTPS with TLS 1.2+, REST API, auth/admin middleware, htmx web UI (init, unseal, login, dashboard pages). CLI: cobra/viper subcommands (server, init, status, snapshot) with env var override support (METACRYPT_ prefix). Operational tooling: Dockerfile (multi-stage, non-root), docker-compose, hardened systemd units (service + daily backup timer), install script, backup script with retention pruning, production config examples. Runbook covering installation, configuration, daily operations, backup/restore, monitoring, troubleshooting, and security procedures. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
125
internal/auth/auth.go
Normal file
125
internal/auth/auth.go
Normal file
@@ -0,0 +1,125 @@
|
||||
// Package auth provides MCIAS authentication integration with token caching.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
mcias "git.wntrmute.dev/kyle/mcias/clients/go"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("auth: invalid credentials")
|
||||
ErrInvalidToken = errors.New("auth: invalid token")
|
||||
)
|
||||
|
||||
const tokenCacheTTL = 30 * time.Second
|
||||
|
||||
// TokenInfo holds validated token information.
|
||||
type TokenInfo struct {
|
||||
Username string
|
||||
Roles []string
|
||||
IsAdmin bool
|
||||
}
|
||||
|
||||
// cachedClaims holds a cached token validation result.
|
||||
type cachedClaims struct {
|
||||
info *TokenInfo
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
// Authenticator provides MCIAS-backed authentication.
|
||||
type Authenticator struct {
|
||||
client *mcias.Client
|
||||
|
||||
mu sync.RWMutex
|
||||
cache map[string]*cachedClaims // keyed by SHA-256(token)
|
||||
}
|
||||
|
||||
// NewAuthenticator creates a new authenticator with the given MCIAS client.
|
||||
func NewAuthenticator(client *mcias.Client) *Authenticator {
|
||||
return &Authenticator{
|
||||
client: client,
|
||||
cache: make(map[string]*cachedClaims),
|
||||
}
|
||||
}
|
||||
|
||||
// Login authenticates a user via MCIAS and returns the token.
|
||||
func (a *Authenticator) Login(username, password, totpCode string) (token string, expiresAt string, err error) {
|
||||
tok, exp, err := a.client.Login(username, password, totpCode)
|
||||
if err != nil {
|
||||
var authErr *mcias.MciasAuthError
|
||||
if errors.As(err, &authErr) {
|
||||
return "", "", ErrInvalidCredentials
|
||||
}
|
||||
return "", "", err
|
||||
}
|
||||
return tok, exp, nil
|
||||
}
|
||||
|
||||
// ValidateToken validates a bearer token, using a short-lived cache.
|
||||
func (a *Authenticator) ValidateToken(token string) (*TokenInfo, error) {
|
||||
key := tokenHash(token)
|
||||
|
||||
// Check cache.
|
||||
a.mu.RLock()
|
||||
cached, ok := a.cache[key]
|
||||
a.mu.RUnlock()
|
||||
if ok && time.Now().Before(cached.expiresAt) {
|
||||
return cached.info, nil
|
||||
}
|
||||
|
||||
// Validate with MCIAS.
|
||||
claims, err := a.client.ValidateToken(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !claims.Valid {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
info := &TokenInfo{
|
||||
Username: claims.Sub,
|
||||
Roles: claims.Roles,
|
||||
IsAdmin: hasAdminRole(claims.Roles),
|
||||
}
|
||||
|
||||
// Cache the result.
|
||||
a.mu.Lock()
|
||||
a.cache[key] = &cachedClaims{
|
||||
info: info,
|
||||
expiresAt: time.Now().Add(tokenCacheTTL),
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// Logout invalidates a token via MCIAS. The client must have the token set.
|
||||
func (a *Authenticator) Logout(client *mcias.Client) error {
|
||||
return client.Logout()
|
||||
}
|
||||
|
||||
// ClearCache removes all cached token validations.
|
||||
func (a *Authenticator) ClearCache() {
|
||||
a.mu.Lock()
|
||||
a.cache = make(map[string]*cachedClaims)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func tokenHash(token string) string {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func hasAdminRole(roles []string) bool {
|
||||
for _, r := range roles {
|
||||
if r == "admin" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
52
internal/auth/auth_test.go
Normal file
52
internal/auth/auth_test.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTokenHash(t *testing.T) {
|
||||
h1 := tokenHash("token-abc")
|
||||
h2 := tokenHash("token-abc")
|
||||
h3 := tokenHash("token-def")
|
||||
|
||||
if h1 != h2 {
|
||||
t.Error("same input should produce same hash")
|
||||
}
|
||||
if h1 == h3 {
|
||||
t.Error("different inputs should produce different hashes")
|
||||
}
|
||||
if len(h1) != 64 { // SHA-256 hex
|
||||
t.Errorf("hash length: got %d, want 64", len(h1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasAdminRole(t *testing.T) {
|
||||
if !hasAdminRole([]string{"user", "admin"}) {
|
||||
t.Error("should detect admin role")
|
||||
}
|
||||
if hasAdminRole([]string{"user", "operator"}) {
|
||||
t.Error("should not detect admin role when absent")
|
||||
}
|
||||
if hasAdminRole(nil) {
|
||||
t.Error("nil roles should not be admin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAuthenticator(t *testing.T) {
|
||||
a := NewAuthenticator(nil)
|
||||
if a == nil {
|
||||
t.Fatal("NewAuthenticator returned nil")
|
||||
}
|
||||
if a.cache == nil {
|
||||
t.Error("cache should be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearCache(t *testing.T) {
|
||||
a := NewAuthenticator(nil)
|
||||
a.cache["test"] = &cachedClaims{info: &TokenInfo{Username: "test"}}
|
||||
a.ClearCache()
|
||||
if len(a.cache) != 0 {
|
||||
t.Error("cache should be empty after clear")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user