vaultguard

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 15 Imported by: 0

README

VaultGuard

Build Status Lint Status Go Report Card Docs License

Security-gated credential access for Go applications. Combines Posture (security posture assessment) with OmniVault (secret management) to provide environment-aware secure credential handling.

Features

  • 🔍 Automatic Environment Detection - Detects local workstations, AWS EKS, GCP GKE, Azure AKS, Lambda, Cloud Run, and more
  • 🛡️ Security Policy Enforcement - Define security requirements that must be met before credentials are accessed
  • Provider Auto-Selection - Automatically uses the right secret provider for each environment
  • 🌐 Cross-Platform - Works on macOS, Windows, Linux, and all major cloud platforms

Quick Start

package main

import (
    "context"
    "log"

    "github.com/agentplexus/vaultguard"
)

func main() {
    ctx := context.Background()

    // Create a secure vault with default settings
    sv, err := vaultguard.Quick()
    if err != nil {
        log.Fatalf("Security check failed: %v", err)
    }
    defer sv.Close()

    // Get credentials
    apiKey, err := sv.GetValue(ctx, "API_KEY")
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Environment: %s, Provider: %s", sv.Environment(), sv.Provider())
}

Environment Support

Environment Detection Security Checks Default Provider
Local (macOS/Windows/Linux) Automatic Posture (TPM, encryption, Secure Boot) Keyring
AWS EKS IRSA env vars IRSA validation, role ARN checks AWS Secrets Manager
AWS Lambda Lambda env vars IAM validation AWS Secrets Manager
GCP GKE Workload Identity Service account validation GCP Secret Manager
GCP Cloud Run K_SERVICE env IAM validation GCP Secret Manager
Azure AKS Workload Identity Client/tenant validation Azure Key Vault
Kubernetes Service account mount Namespace, SA validation K8s Secrets
Container Docker/cgroup detection Basic checks Environment vars

Security Policies

Default Policy
sv, _ := vaultguard.Quick() // Uses DefaultPolicy()
Development Policy (Permissive)
sv, _ := vaultguard.QuickDev() // Relaxed for development
Strict Policy
sv, _ := vaultguard.QuickStrict() // High security requirements
Custom Policy
sv, err := vaultguard.New(&vaultguard.Config{
    Policy: &vaultguard.Policy{
        Local: &vaultguard.LocalPolicy{
            MinSecurityScore:  75,
            RequireEncryption: true,
            RequireTPM:        true,
        },
        Cloud: &vaultguard.CloudPolicy{
            RequireIAM: true,
            AWS: &vaultguard.AWSPolicy{
                RequireIRSA: true,
                AllowedRoleARNs: []string{
                    "arn:aws:iam::123456789:role/my-app-*",
                },
            },
        },
        Kubernetes: &vaultguard.KubernetesPolicy{
            DeniedNamespaces: []string{"default", "kube-system"},
        },
    },
})

File-Based Configuration

Policies can be loaded from JSON configuration files, supporting both user preferences and enterprise-wide enforcement.

Configuration Hierarchy

Policies are loaded in order of precedence (highest first):

  1. AGENTPLEXUS_POLICY_FILE environment variable
  2. User config: ~/.agentplexus/policy.json
  3. System config: /etc/agentplexus/policy.json (Linux/macOS) or %ProgramData%\agentplexus\policy.json (Windows)
// Load policy from configuration files
policy, err := vaultguard.LoadPolicy()
if err != nil {
    log.Fatal(err)
}

sv, err := vaultguard.New(&vaultguard.Config{
    Policy: policy,
})
User Configuration Example

~/.agentplexus/policy.json:

{
  "version": 1,
  "local": {
    "min_security_score": 60,
    "require_encryption": true
  },
  "provider_map": {
    "local": "keyring"
  }
}
Enterprise Configuration Example

System administrators can deploy organization-wide policies with locked fields that users cannot override.

/etc/agentplexus/policy.json:

{
  "version": 1,
  "local": {
    "min_security_score": 50,
    "require_encryption": true
  },
  "cloud": {
    "require_iam": true,
    "aws": {
      "require_irsa": true,
      "allowed_account_ids": ["123456789012"]
    }
  },
  "allow_insecure": false,
  "locked": [
    "local.require_encryption",
    "cloud.require_iam",
    "allow_insecure"
  ]
}

When both system and user configs exist, they are merged with system settings taking precedence on locked fields.

Convenience Functions

// Pre-flight security check
result, err := vaultguard.CheckSecurity(nil)
fmt.Printf("Security score: %d\n", result.Score)

// Require security (for init functions)
if err := vaultguard.RequireSecurity(nil); err != nil {
    log.Fatal(err)
}

// Quick credential access
apiKey, err := vaultguard.GetEnv(ctx, "API_KEY", nil)

// Load multiple credentials
creds, err := vaultguard.LoadCredentials(ctx, nil,
    "GOOGLE_API_KEY",
    "ANTHROPIC_API_KEY",
    "OPENAI_API_KEY",
)

// Load required credentials (error if any missing)
creds, err := vaultguard.LoadRequiredCredentials(ctx, nil,
    "GOOGLE_API_KEY",
    "SERPER_API_KEY",
)

How It Works

┌─────────────────────────────────────────────────────────────────────┐
│                           VaultGuard                                │
│                                                                     │
│  1. Environment Detection                                           │
│     DetectEnvironment() → local | eks | gke | aks | lambda | ...    │
│                                                                     │
│  2. Security Checks (based on environment)                          │
│     ┌─────────────────────┐   ┌────────────────────────────────┐    │
│     │ Local (Posture)     │   │ Cloud                          │    │
│     │ • Secure Enclave    │   │ • IRSA/Workload Identity       │    │
│     │ • Disk Encryption   │   │ • Role/Account validation      │    │
│     │ • Secure Boot       │   │ • Namespace restrictions       │    │
│     └─────────────────────┘   └────────────────────────────────┘    │
│                                                                     │
│  3. Provider Auto-Selection                                         │
│     local → keyring | eks → aws-sm | gke → gcp-sm | ...             │
│                                                                     │
│  4. Credential Access (via OmniVault)                               │
│     sv.GetValue(ctx, "API_KEY") → secret value                      │
└─────────────────────────────────────────────────────────────────────┘

Integration with stats-agent-team

package main

import (
    "context"
    "log"

    "github.com/agentplexus/vaultguard"
)

func main() {
    ctx := context.Background()

    // Security-gated credential loading
    sv, err := vaultguard.New(&vaultguard.Config{
        Policy: &vaultguard.Policy{
            Local: &vaultguard.LocalPolicy{
                MinSecurityScore:  50,
                RequireEncryption: true,
            },
            Cloud: &vaultguard.CloudPolicy{
                RequireIAM: true,
            },
        },
    })
    if err != nil {
        log.Fatalf("Security requirements not met: %v", err)
    }
    defer sv.Close()

    // Load agent credentials
    creds, err := sv.LoadRequiredCredentials(ctx, nil,
        "LLM_PROVIDER",
        "GOOGLE_API_KEY",
        "SERPER_API_KEY",
    )
    if err != nil {
        log.Fatal(err)
    }

    // Start agents with credentials...
    log.Printf("Starting agents with provider: %s", creds["LLM_PROVIDER"])
}

Installation

go get github.com/agentplexus/vaultguard

Documentation

Full documentation is available at agentplexus.github.io/vaultguard including:

Dependencies

License

MIT License

Documentation

Overview

Package vaultguard provides security-gated credential access by combining Posture (security posture assessment) with OmniVault (secret management). It supports both local workstation deployments and cloud environments like AWS EKS, GCP GKE, and Azure AKS.

Index

Constants

View Source
const (
	// ConfigDirName is the directory name for agentplexus configuration.
	ConfigDirName = ".agentplexus"

	// PolicyFileName is the name of the policy configuration file.
	PolicyFileName = "policy.json"

	// EnvPolicyFile is the environment variable for explicit policy file path.
	EnvPolicyFile = "AGENTPLEXUS_POLICY_FILE"
)

Variables

View Source
var (
	// ErrSecurityCheckFailed indicates the security policy was not met.
	ErrSecurityCheckFailed = errors.New("security check failed")

	// ErrEnvironmentNotSupported indicates the environment is not supported.
	ErrEnvironmentNotSupported = errors.New("environment not supported")

	// ErrProviderNotAvailable indicates the secret provider is not available.
	ErrProviderNotAvailable = errors.New("provider not available")

	// ErrPolicyViolation indicates a policy requirement was violated.
	ErrPolicyViolation = errors.New("policy violation")

	// ErrNotInitialized indicates the SecureVault was not properly initialized.
	ErrNotInitialized = errors.New("secure vault not initialized")

	// ErrSecretNotFound indicates the requested secret was not found.
	ErrSecretNotFound = errors.New("secret not found")

	// ErrAccessDenied indicates access to the secret was denied.
	ErrAccessDenied = errors.New("access denied")
)

Standard errors for omnisafe operations.

Functions

func EnsureConfigDir added in v0.2.0

func EnsureConfigDir() (string, error)

EnsureConfigDir creates the user config directory if it doesn't exist.

func GetConfigPaths added in v0.2.0

func GetConfigPaths() map[string]string

GetConfigPaths returns the paths that will be checked for configuration.

func GetEnv

func GetEnv(ctx context.Context, name string, policy *Policy) (string, error)

GetEnv is a convenience function that retrieves an environment variable through the secure vault. It performs security checks before access.

Example:

apiKey, err := omnisafe.GetEnv(ctx, "API_KEY", nil)

func GetLocalSecuritySummary

func GetLocalSecuritySummary() (*inspector.SecuritySummary, error)

GetLocalSecuritySummary returns a quick security summary for local environments.

func IsLocalSecuritySupported

func IsLocalSecuritySupported() bool

IsLocalSecuritySupported returns true if local security checks are available. This checks if Posture functionality is available on the current platform.

func LoadCredentials

func LoadCredentials(ctx context.Context, policy *Policy, names ...string) (map[string]string, error)

LoadCredentials loads multiple credentials at once and returns them as a map. Missing credentials are returned as empty strings (no error).

Example:

creds, err := omnisafe.LoadCredentials(ctx, nil,
    "GOOGLE_API_KEY",
    "ANTHROPIC_API_KEY",
    "OPENAI_API_KEY",
)

func LoadRequiredCredentials

func LoadRequiredCredentials(ctx context.Context, policy *Policy, names ...string) (map[string]string, error)

LoadRequiredCredentials loads credentials and returns an error if any are missing.

Example:

creds, err := omnisafe.LoadRequiredCredentials(ctx, nil,
    "GOOGLE_API_KEY",
    "SERPER_API_KEY",
)

func MustGetEnv

func MustGetEnv(ctx context.Context, name string, policy *Policy) string

MustGetEnv is like GetEnv but panics on error.

func RequireSecurity

func RequireSecurity(policy *Policy) error

RequireSecurity checks security and returns an error if it fails. This is a convenience wrapper around CheckSecurity for use in init functions.

Example:

func init() {
    if err := omnisafe.RequireSecurity(nil); err != nil {
        log.Fatal(err)
    }
}

func SavePolicy added in v0.2.0

func SavePolicy(policy *Policy) error

SavePolicy saves a policy to the user config directory.

Types

type AWSDetails

type AWSDetails struct {
	RoleARN      string `json:"role_arn,omitempty"`
	Region       string `json:"region,omitempty"`
	AccountID    string `json:"account_id,omitempty"`
	TokenFile    string `json:"token_file,omitempty"`
	FunctionName string `json:"function_name,omitempty"`
	ExecutionEnv string `json:"execution_env,omitempty"`
}

AWSDetails contains AWS-specific environment details.

type AWSPolicy

type AWSPolicy struct {
	// RequireIRSA requires IRSA (IAM Roles for Service Accounts).
	RequireIRSA bool `json:"require_irsa,omitempty"`

	// AllowedRoleARNs is a whitelist of allowed IAM role ARNs.
	// Supports wildcards: "arn:aws:iam::123456789:role/my-app-*"
	AllowedRoleARNs []string `json:"allowed_role_arns,omitempty"`

	// AllowedAccountIDs is a whitelist of allowed AWS account IDs.
	AllowedAccountIDs []string `json:"allowed_account_ids,omitempty"`

	// AllowedRegions restricts to specific AWS regions.
	AllowedRegions []string `json:"allowed_regions,omitempty"`

	// RequireIMDSv2 requires IMDSv2 for EC2 metadata.
	RequireIMDSv2 bool `json:"require_imdsv2,omitempty"`
}

AWSPolicy defines AWS-specific security requirements.

type AzureDetails

type AzureDetails struct {
	ClientID      string `json:"client_id,omitempty"`
	TenantID      string `json:"tenant_id,omitempty"`
	TokenFile     string `json:"token_file,omitempty"`
	Subscription  string `json:"subscription,omitempty"`
	ResourceGroup string `json:"resource_group,omitempty"`
}

AzureDetails contains Azure-specific environment details.

type AzurePolicy

type AzurePolicy struct {
	// RequireWorkloadIdentity requires AKS Workload Identity.
	RequireWorkloadIdentity bool `json:"require_workload_identity,omitempty"`

	// AllowedClientIDs is a whitelist of allowed Azure AD client IDs.
	AllowedClientIDs []string `json:"allowed_client_ids,omitempty"`

	// AllowedTenantIDs is a whitelist of allowed Azure AD tenant IDs.
	AllowedTenantIDs []string `json:"allowed_tenant_ids,omitempty"`

	// AllowedSubscriptions restricts to specific Azure subscriptions.
	AllowedSubscriptions []string `json:"allowed_subscriptions,omitempty"`

	// AllowedRegions restricts to specific Azure regions.
	AllowedRegions []string `json:"allowed_regions,omitempty"`
}

AzurePolicy defines Azure-specific security requirements.

type CloudPolicy

type CloudPolicy struct {
	// RequireIAM requires cloud IAM (IRSA, Workload Identity) to be configured.
	RequireIAM bool `json:"require_iam,omitempty"`

	// AWS-specific requirements.
	AWS *AWSPolicy `json:"aws,omitempty"`

	// GCP-specific requirements.
	GCP *GCPPolicy `json:"gcp,omitempty"`

	// Azure-specific requirements.
	Azure *AzurePolicy `json:"azure,omitempty"`
}

CloudPolicy defines security requirements for cloud environments.

type CloudSecurityDetails

type CloudSecurityDetails struct {
	// CloudProvider (aws, gcp, azure).
	CloudProvider string `json:"cloud_provider"`

	// Region where the workload is running.
	Region string `json:"region,omitempty"`

	// IAM identity details.
	IAM *IAMDetails `json:"iam,omitempty"`

	// Kubernetes details (if applicable).
	Kubernetes *KubernetesDetails `json:"kubernetes,omitempty"`
}

CloudSecurityDetails contains cloud environment security information.

type Config

type Config struct {
	// Policy defines security requirements. If nil, DefaultPolicy() is used.
	Policy *Policy

	// Logger for structured logging. If nil, logging is disabled.
	Logger *slog.Logger

	// ForceEnvironment overrides automatic environment detection.
	// Use for testing or when detection fails.
	ForceEnvironment Environment

	// CustomVault allows injecting a custom vault.Vault implementation.
	// If set, this takes precedence over provider auto-selection.
	CustomVault vault.Vault

	// ProviderConfig is passed to the auto-selected provider.
	ProviderConfig any
}

Config configures a SecureVault.

type Environment

type Environment string

Environment represents the deployment context.

const (
	// EnvUnknown is an undetected environment.
	EnvUnknown Environment = "unknown"

	// EnvLocal is a developer workstation (macOS, Windows, Linux desktop).
	EnvLocal Environment = "local"

	// EnvContainer is a generic container without cloud IAM.
	EnvContainer Environment = "container"

	// EnvKubernetes is Kubernetes without cloud-specific IAM.
	EnvKubernetes Environment = "kubernetes"

	// EnvEKS is AWS EKS with IRSA (IAM Roles for Service Accounts).
	EnvEKS Environment = "eks"

	// EnvGKE is GCP GKE with Workload Identity.
	EnvGKE Environment = "gke"

	// EnvAKS is Azure AKS with Workload Identity.
	EnvAKS Environment = "aks"

	// EnvLambda is AWS Lambda.
	EnvLambda Environment = "lambda"

	// EnvCloudRun is GCP Cloud Run.
	EnvCloudRun Environment = "cloudrun"

	// EnvAzureFunc is Azure Functions.
	EnvAzureFunc Environment = "azurefunc"
)

func DetectEnvironment

func DetectEnvironment() Environment

DetectEnvironment automatically detects the current deployment environment. It checks for cloud-specific environment variables and Kubernetes markers to determine where the code is running.

func (Environment) IsAWS

func (e Environment) IsAWS() bool

IsAWS returns true if this is an AWS environment.

func (Environment) IsAzure

func (e Environment) IsAzure() bool

IsAzure returns true if this is an Azure environment.

func (Environment) IsCloud

func (e Environment) IsCloud() bool

IsCloud returns true if this is a cloud environment.

func (Environment) IsGCP

func (e Environment) IsGCP() bool

IsGCP returns true if this is a GCP environment.

func (Environment) IsKubernetes

func (e Environment) IsKubernetes() bool

IsKubernetes returns true if this is a Kubernetes environment.

func (Environment) IsLocal

func (e Environment) IsLocal() bool

IsLocal returns true if this is a local workstation environment.

func (Environment) String

func (e Environment) String() string

String returns the string representation of the environment.

type EnvironmentDetails

type EnvironmentDetails struct {
	Environment Environment        `json:"environment"`
	Platform    string             `json:"platform"`
	Arch        string             `json:"arch"`
	AWS         *AWSDetails        `json:"aws,omitempty"`
	GCP         *GCPDetails        `json:"gcp,omitempty"`
	Azure       *AzureDetails      `json:"azure,omitempty"`
	Kubernetes  *KubernetesDetails `json:"kubernetes,omitempty"`
}

EnvironmentDetails contains detailed environment information.

func GetEnvironmentDetails

func GetEnvironmentDetails() *EnvironmentDetails

GetEnvironmentDetails returns detailed information about the current environment.

type FilePolicy added in v0.2.0

type FilePolicy struct {
	// Version of the policy file format.
	Version int `json:"version"`

	// Extends the base Policy.
	Policy

	// Locked lists field paths that cannot be overridden by user config.
	// Used by enterprise/system configs to enforce settings.
	// Example: ["local.require_encryption", "local.min_security_score"]
	Locked []string `json:"locked,omitempty"`
}

FilePolicy extends Policy with file-based configuration features.

func LoadPolicyFromFile added in v0.2.0

func LoadPolicyFromFile(path string) (*FilePolicy, error)

LoadPolicyFromFile loads a policy from a specific file path.

type GCPDetails

type GCPDetails struct {
	ProjectID           string `json:"project_id,omitempty"`
	Region              string `json:"region,omitempty"`
	ServiceAccountEmail string `json:"service_account_email,omitempty"`
	ClusterName         string `json:"cluster_name,omitempty"`
	ServiceName         string `json:"service_name,omitempty"`
}

GCPDetails contains GCP-specific environment details.

type GCPPolicy

type GCPPolicy struct {
	// RequireWorkloadIdentity requires GKE Workload Identity.
	RequireWorkloadIdentity bool `json:"require_workload_identity,omitempty"`

	// AllowedServiceAccounts is a whitelist of allowed GCP service accounts.
	AllowedServiceAccounts []string `json:"allowed_service_accounts,omitempty"`

	// AllowedProjects is a whitelist of allowed GCP project IDs.
	AllowedProjects []string `json:"allowed_projects,omitempty"`

	// AllowedRegions restricts to specific GCP regions.
	AllowedRegions []string `json:"allowed_regions,omitempty"`
}

GCPPolicy defines GCP-specific security requirements.

type IAMDetails

type IAMDetails struct {
	// Configured indicates if cloud IAM is configured.
	Configured bool `json:"configured"`

	// RoleARN for AWS IRSA.
	RoleARN string `json:"role_arn,omitempty"`

	// ServiceAccountEmail for GCP Workload Identity.
	ServiceAccountEmail string `json:"service_account_email,omitempty"`

	// ClientID for Azure Workload Identity.
	ClientID string `json:"client_id,omitempty"`

	// TokenPath is the path to the projected token.
	TokenPath string `json:"token_path,omitempty"`
}

IAMDetails contains cloud IAM information.

type KubernetesDetails

type KubernetesDetails struct {
	// InCluster indicates if running inside a Kubernetes cluster.
	InCluster bool `json:"in_cluster"`

	// Namespace is the current namespace.
	Namespace string `json:"namespace,omitempty"`

	// ServiceAccount is the service account name.
	ServiceAccount string `json:"service_account,omitempty"`

	// PodName is the current pod name.
	PodName string `json:"pod_name,omitempty"`
}

KubernetesDetails contains Kubernetes environment information.

type KubernetesPolicy

type KubernetesPolicy struct {
	// RequireServiceAccount requires a specific service account.
	RequireServiceAccount bool `json:"require_service_account,omitempty"`

	// AllowedServiceAccounts is a whitelist of allowed service accounts.
	AllowedServiceAccounts []string `json:"allowed_service_accounts,omitempty"`

	// AllowedNamespaces restricts to specific namespaces.
	AllowedNamespaces []string `json:"allowed_namespaces,omitempty"`

	// DeniedNamespaces is a blacklist of namespaces.
	DeniedNamespaces []string `json:"denied_namespaces,omitempty"`

	// RequireNonRoot requires the pod to run as non-root.
	RequireNonRoot bool `json:"require_non_root,omitempty"`

	// RequireReadOnlyRoot requires a read-only root filesystem.
	RequireReadOnlyRoot bool `json:"require_read_only_root,omitempty"`
}

KubernetesPolicy defines Kubernetes-specific security requirements.

type LocalPolicy

type LocalPolicy struct {
	// MinSecurityScore is the minimum Posture security score (0-100).
	// Default: 0 (no minimum).
	MinSecurityScore int `json:"min_security_score,omitempty"`

	// RequireEncryption requires disk encryption (FileVault/BitLocker/LUKS).
	RequireEncryption bool `json:"require_encryption,omitempty"`

	// RequireTPM requires TPM or Secure Enclave.
	RequireTPM bool `json:"require_tpm,omitempty"`

	// RequireSecureBoot requires Secure Boot to be enabled.
	RequireSecureBoot bool `json:"require_secure_boot,omitempty"`

	// RequireBiometrics requires biometric authentication to be configured.
	RequireBiometrics bool `json:"require_biometrics,omitempty"`

	// AllowedPlatforms restricts to specific platforms (darwin, windows, linux).
	// Empty means all platforms are allowed.
	AllowedPlatforms []string `json:"allowed_platforms,omitempty"`
}

LocalPolicy defines security requirements for local workstations.

type LocalSecurityDetails

type LocalSecurityDetails struct {
	// Platform (darwin, windows, linux).
	Platform string `json:"platform"`

	// TPMPresent indicates if TPM/Secure Enclave is available.
	TPMPresent bool `json:"tpm_present"`

	// TPMEnabled indicates if TPM/Secure Enclave is enabled.
	TPMEnabled bool `json:"tpm_enabled"`

	// TPMType is the type of security chip (tpm, secure_enclave).
	TPMType string `json:"tpm_type,omitempty"`

	// DiskEncrypted indicates if disk encryption is enabled.
	DiskEncrypted bool `json:"disk_encrypted"`

	// EncryptionType (filevault, bitlocker, luks).
	EncryptionType string `json:"encryption_type,omitempty"`

	// SecureBootEnabled indicates if Secure Boot is enabled.
	SecureBootEnabled bool `json:"secure_boot_enabled"`

	// BiometricsAvailable indicates if biometric auth is available.
	BiometricsAvailable bool `json:"biometrics_available"`

	// BiometricsConfigured indicates if biometrics are set up.
	BiometricsConfigured bool `json:"biometrics_configured"`
}

LocalSecurityDetails contains workstation security information.

type Policy

type Policy struct {
	// Local contains security requirements for local workstations.
	// Used when Environment.IsLocal() returns true.
	Local *LocalPolicy `json:"local,omitempty"`

	// Cloud contains security requirements for cloud environments.
	// Used when Environment.IsCloud() returns true.
	Cloud *CloudPolicy `json:"cloud,omitempty"`

	// Kubernetes contains additional requirements for Kubernetes environments.
	// Used when Environment.IsKubernetes() returns true.
	Kubernetes *KubernetesPolicy `json:"kubernetes,omitempty"`

	// ProviderMap maps environments to preferred secret providers.
	// If not specified, providers are auto-selected based on environment.
	ProviderMap map[Environment]Provider `json:"provider_map,omitempty"`

	// FallbackProvider is used when the preferred provider is unavailable.
	FallbackProvider Provider `json:"fallback_provider,omitempty"`

	// AllowInsecure allows credential access even if security checks fail.
	// This should only be used for development/testing.
	AllowInsecure bool `json:"allow_insecure,omitempty"`

	// InsecureReason documents why AllowInsecure is set (for auditing).
	InsecureReason string `json:"insecure_reason,omitempty"`
}

Policy defines security requirements for credential access. Different policies can be applied based on the detected environment.

func DefaultPolicy

func DefaultPolicy() *Policy

DefaultPolicy returns a sensible default policy for production use.

func DevelopmentPolicy

func DevelopmentPolicy() *Policy

DevelopmentPolicy returns a permissive policy for development.

func LoadPolicy added in v0.2.0

func LoadPolicy() (*Policy, error)

LoadPolicy loads the policy from the configuration hierarchy. Precedence (highest to lowest):

  1. AGENTPLEXUS_POLICY_FILE environment variable
  2. User config (~/.agentplexus/policy.yaml)
  3. System config (/etc/agentplexus/policy.yaml)
  4. nil (no policy = permissive mode)

func StrictPolicy

func StrictPolicy() *Policy

StrictPolicy returns a strict policy for high-security environments.

type PolicyError

type PolicyError struct {
	// Err is the underlying error.
	Err error

	// Policy is the name of the policy that was violated.
	Policy string

	// Requirement describes what was required.
	Requirement string

	// Details provides additional context.
	Details string
}

PolicyError represents a policy violation with details.

func NewPolicyError

func NewPolicyError(policy, requirement, details string) *PolicyError

NewPolicyError creates a new PolicyError.

func (*PolicyError) Error

func (e *PolicyError) Error() string

Error implements the error interface.

func (*PolicyError) Unwrap

func (e *PolicyError) Unwrap() error

Unwrap returns the underlying error.

type Provider

type Provider string

Provider represents a secret provider type.

const (
	// ProviderEnv reads from environment variables.
	ProviderEnv Provider = "env"

	// ProviderFile reads from files.
	ProviderFile Provider = "file"

	// ProviderKeyring uses OS keyring (macOS Keychain, Windows Credential Manager).
	ProviderKeyring Provider = "keyring"

	// ProviderAWSSecretsManager uses AWS Secrets Manager.
	ProviderAWSSecretsManager Provider = "aws-sm"

	// ProviderAWSParameterStore uses AWS Systems Manager Parameter Store.
	ProviderAWSParameterStore Provider = "aws-ssm"

	// ProviderGCPSecretManager uses GCP Secret Manager.
	ProviderGCPSecretManager Provider = "gcp-sm"

	// ProviderAzureKeyVault uses Azure Key Vault.
	ProviderAzureKeyVault Provider = "azure-kv"

	// ProviderK8sSecret uses Kubernetes Secrets.
	ProviderK8sSecret Provider = "k8s"

	// ProviderVault uses HashiCorp Vault.
	ProviderVault Provider = "vault"
)

func (Provider) String

func (p Provider) String() string

String returns the string representation of the provider.

type ProviderError

type ProviderError struct {
	// Err is the underlying error.
	Err error

	// Provider is the provider that encountered the error.
	Provider Provider

	// Operation is the operation that failed.
	Operation string

	// Path is the secret path (if applicable).
	Path string

	// Cause is the underlying cause.
	Cause error
}

ProviderError represents a provider-related error.

func NewProviderError

func NewProviderError(provider Provider, operation, path string, cause error) *ProviderError

NewProviderError creates a new ProviderError.

func (*ProviderError) Error

func (e *ProviderError) Error() string

Error implements the error interface.

func (*ProviderError) Unwrap

func (e *ProviderError) Unwrap() error

Unwrap returns the underlying error.

type SecureVault

type SecureVault struct {
	// contains filtered or unexported fields
}

SecureVault provides security-gated access to secrets. It combines Posture security checks with OmniVault secret management.

func MustQuick

func MustQuick() *SecureVault

MustQuick is like Quick but panics on error.

func MustQuickDev

func MustQuickDev() *SecureVault

MustQuickDev is like QuickDev but panics on error.

func New

func New(cfg *Config) (*SecureVault, error)

New creates a new SecureVault with the given configuration. It automatically detects the environment, performs security checks, and initializes the appropriate secret provider.

func Quick

func Quick() (*SecureVault, error)

Quick creates a SecureVault with sensible defaults for the detected environment. This is the simplest way to get started with OmniSafe.

Example:

sv, err := omnisafe.Quick()
if err != nil {
    log.Fatal(err)
}
defer sv.Close()

apiKey, err := sv.GetValue(ctx, "API_KEY")

func QuickDev

func QuickDev() (*SecureVault, error)

QuickDev creates a SecureVault with permissive settings for development. Security checks are relaxed and the environment provider is used.

WARNING: Do not use in production!

func QuickStrict

func QuickStrict() (*SecureVault, error)

QuickStrict creates a SecureVault with strict security requirements. Use this for high-security environments.

func (*SecureVault) Close

func (sv *SecureVault) Close() error

Close releases resources.

func (*SecureVault) Delete

func (sv *SecureVault) Delete(ctx context.Context, path string) error

Delete removes a secret.

func (*SecureVault) Environment

func (sv *SecureVault) Environment() Environment

Environment returns the detected environment.

func (*SecureVault) Exists

func (sv *SecureVault) Exists(ctx context.Context, path string) (bool, error)

Exists checks if a secret exists.

func (*SecureVault) Get

func (sv *SecureVault) Get(ctx context.Context, path string) (*vault.Secret, error)

Get retrieves a secret by path.

func (*SecureVault) GetField

func (sv *SecureVault) GetField(ctx context.Context, path, field string) (string, error)

GetField retrieves a specific field from a multi-field secret.

func (*SecureVault) GetValue

func (sv *SecureVault) GetValue(ctx context.Context, path string) (string, error)

GetValue retrieves the primary value of a secret.

func (*SecureVault) IsSecure

func (sv *SecureVault) IsSecure() bool

IsSecure returns true if security checks passed.

func (*SecureVault) List

func (sv *SecureVault) List(ctx context.Context, prefix string) ([]string, error)

List returns secrets matching a prefix.

func (*SecureVault) Provider

func (sv *SecureVault) Provider() Provider

Provider returns the active provider.

func (*SecureVault) SecurityResult

func (sv *SecureVault) SecurityResult() *SecurityResult

SecurityResult returns the security check results.

func (*SecureVault) Set

func (sv *SecureVault) Set(ctx context.Context, path string, secret *vault.Secret) error

Set stores a secret.

func (*SecureVault) SetValue

func (sv *SecureVault) SetValue(ctx context.Context, path, value string) error

SetValue stores a simple string secret.

type SecurityDetails

type SecurityDetails struct {
	// Local security details (populated for local environments).
	Local *LocalSecurityDetails `json:"local,omitempty"`

	// Cloud security details (populated for cloud environments).
	Cloud *CloudSecurityDetails `json:"cloud,omitempty"`
}

SecurityDetails contains environment-specific security information.

type SecurityError

type SecurityError struct {
	// Err is the underlying error.
	Err error

	// Check is the name of the security check that failed.
	Check string

	// Required is what was required.
	Required string

	// Actual is what was found.
	Actual string

	// Environment where the check was performed.
	Environment Environment

	// Recommendations for fixing the issue.
	Recommendations []string
}

SecurityError represents a security check failure with details.

func NewSecurityError

func NewSecurityError(check, required, actual string, env Environment, recommendations ...string) *SecurityError

NewSecurityError creates a new SecurityError.

func (*SecurityError) Error

func (e *SecurityError) Error() string

Error implements the error interface.

func (*SecurityError) Unwrap

func (e *SecurityError) Unwrap() error

Unwrap returns the underlying error.

type SecurityLevel

type SecurityLevel string

SecurityLevel represents the overall security assessment.

const (
	// SecurityCritical means critical security issues detected.
	SecurityCritical SecurityLevel = "critical"

	// SecurityLow means security posture is low.
	SecurityLow SecurityLevel = "low"

	// SecurityMedium means security posture is acceptable.
	SecurityMedium SecurityLevel = "medium"

	// SecurityHigh means security posture is good.
	SecurityHigh SecurityLevel = "high"

	// SecurityExcellent means all security features are enabled.
	SecurityExcellent SecurityLevel = "excellent"
)

type SecurityResult

type SecurityResult struct {
	// Environment detected.
	Environment Environment `json:"environment"`

	// Level is the overall security level.
	Level SecurityLevel `json:"level"`

	// Score is the numeric security score (0-100).
	Score int `json:"score"`

	// Passed indicates if the security policy passed.
	Passed bool `json:"passed"`

	// Message provides a human-readable summary.
	Message string `json:"message"`

	// Details contains environment-specific security details.
	Details SecurityDetails `json:"details"`

	// Recommendations for improving security.
	Recommendations []string `json:"recommendations,omitempty"`

	// Timestamp of the assessment.
	Timestamp time.Time `json:"timestamp"`
}

SecurityResult contains the security assessment results.

func CheckCloudSecurity

func CheckCloudSecurity(env Environment, policy *CloudPolicy) (*SecurityResult, error)

CheckCloudSecurity performs security checks for cloud environments.

func CheckKubernetesSecurity

func CheckKubernetesSecurity(env Environment, policy *KubernetesPolicy) (*SecurityResult, error)

CheckKubernetesSecurity performs Kubernetes-specific security checks.

func CheckLocalSecurity

func CheckLocalSecurity(policy *LocalPolicy) (*SecurityResult, error)

CheckLocalSecurity performs security checks for local workstation environments using Posture.

func CheckSecurity

func CheckSecurity(policy *Policy) (*SecurityResult, error)

CheckSecurity performs security checks without creating a vault. Useful for pre-flight checks before starting an application.

Example:

result, err := omnisafe.CheckSecurity(nil)
if err != nil {
    log.Fatalf("Security check failed: %v", err)
}
fmt.Printf("Security score: %d\n", result.Score)

Directories

Path Synopsis
examples
agent-credentials command
Example: Using OmniSafe for agent credentials
Example: Using OmniSafe for agent credentials
stats-agent-team command
Example: Integrating OmniSafe with stats-agent-team
Example: Integrating OmniSafe with stats-agent-team

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL