keyenv

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 10 Imported by: 0

README

KeyEnv Go SDK

Official Go SDK for KeyEnv - Secrets management made simple.

Go Reference Go Report Card

Installation

go get github.com/keyenv/go-sdk

Quick Start

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/keyenv/go-sdk"
)

func main() {
    client, err := keyenv.New(keyenv.Config{
        Token: os.Getenv("KEYENV_TOKEN"),
    })
    if err != nil {
        panic(err)
    }

    // Load secrets into environment
    if _, err := client.LoadEnv(context.Background(), "your-project-id", "production"); err != nil {
        panic(err)
    }

    fmt.Println(os.Getenv("DATABASE_URL"))
}

Configuration

client, err := keyenv.New(keyenv.Config{
    Token:    "your-service-token",      // Required
    BaseURL:  "https://api.keyenv.dev",  // Optional, default shown
    Timeout:  30 * time.Second,          // Optional, default 30s
    CacheTTL: 5 * time.Minute,           // Optional, 0 disables caching
})

Loading Secrets

Load into Environment

The simplest way to use secrets in your application:

count, err := client.LoadEnv(ctx, "project-id", "production")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Loaded %d secrets\n", count)

// Now use them
fmt.Println(os.Getenv("DATABASE_URL"))
Export as Map

Get secrets as a map:

secrets, err := client.ExportSecretsAsMap(ctx, "project-id", "production")
if err != nil {
    log.Fatal(err)
}
fmt.Println(secrets["DATABASE_URL"])
Export with Metadata

Get secrets with full metadata:

secrets, err := client.ExportSecrets(ctx, "project-id", "production")
if err != nil {
    log.Fatal(err)
}
for _, secret := range secrets {
    fmt.Printf("%s=%s\n", secret.Key, secret.Value)
}

Managing Secrets

Get a Single Secret
secret, err := client.GetSecret(ctx, "project-id", "production", "DATABASE_URL")
if err != nil {
    log.Fatal(err)
}
fmt.Println(secret.Value)
Set a Secret

Creates or updates a secret:

err := client.SetSecret(ctx, "project-id", "production", "API_KEY", "sk_live_...")
if err != nil {
    log.Fatal(err)
}

// With description
description := "Production API key"
err = client.SetSecretWithDescription(ctx, "project-id", "production", "API_KEY", "sk_live_...", &description)
Delete a Secret
err := client.DeleteSecret(ctx, "project-id", "production", "OLD_KEY")

Bulk Operations

Bulk Import
result, err := client.BulkImport(ctx, "project-id", "development", []keyenv.SecretInput{
    {Key: "DATABASE_URL", Value: "postgres://localhost/mydb"},
    {Key: "REDIS_URL", Value: "redis://localhost:6379"},
}, keyenv.BulkImportOptions{Overwrite: true})

fmt.Printf("Created: %d, Updated: %d\n", result.Created, result.Updated)
Generate .env File
content, err := client.GenerateEnvFile(ctx, "project-id", "production")
if err != nil {
    log.Fatal(err)
}
os.WriteFile(".env", []byte(content), 0644)

Projects & Environments

List Projects
projects, err := client.ListProjects(ctx)
for _, project := range projects {
    fmt.Printf("%s (%s)\n", project.Name, project.ID)
}
Get Project Details
project, err := client.GetProject(ctx, "project-id")
fmt.Printf("Project: %s\n", project.Name)
for _, env := range project.Environments {
    fmt.Printf("  - %s\n", env.Name)
}

Error Handling

secret, err := client.GetSecret(ctx, "project-id", "production", "MISSING_KEY")
if err != nil {
    var keyenvErr *keyenv.Error
    if errors.As(err, &keyenvErr) {
        switch {
        case keyenvErr.IsUnauthorized():
            log.Fatal("Invalid or expired token")
        case keyenvErr.IsForbidden():
            log.Fatal("Access denied")
        case keyenvErr.IsNotFound():
            log.Fatal("Secret not found")
        default:
            log.Fatalf("Error %d: %s", keyenvErr.Status, keyenvErr.Message)
        }
    }
}

Caching

Enable caching for better performance in serverless environments:

client, _ := keyenv.New(keyenv.Config{
    Token:    os.Getenv("KEYENV_TOKEN"),
    CacheTTL: 5 * time.Minute,
})

// Cached for 5 minutes
secrets, _ := client.ExportSecrets(ctx, "project-id", "production")

// Clear cache manually
client.ClearCache("project-id", "production")

// Or clear all cache
client.ClearAllCache()

API Reference

Constructor Options
Option Type Required Default Description
Token string Yes - Service token
BaseURL string No https://api.keyenv.dev API base URL
Timeout time.Duration No 30s Request timeout
CacheTTL time.Duration No 0 Cache TTL (0 = disabled)
Methods
Method Description
GetCurrentUser(ctx) Get current user/token info
ListProjects(ctx) List all accessible projects
GetProject(ctx, id) Get project with environments
ListEnvironments(ctx, projectId) List environments
ListSecrets(ctx, projectId, env) List secret keys (no values)
ExportSecrets(ctx, projectId, env) Export secrets with values
ExportSecretsAsMap(ctx, projectId, env) Export as map
GetSecret(ctx, projectId, env, key) Get single secret
SetSecret(ctx, projectId, env, key, value) Create or update secret
SetSecretWithDescription(ctx, ...) Create/update with description
DeleteSecret(ctx, projectId, env, key) Delete secret
BulkImport(ctx, projectId, env, secrets, opts) Bulk import secrets
LoadEnv(ctx, projectId, env) Load secrets into os.Environ
GenerateEnvFile(ctx, projectId, env) Generate .env file content
GetSecretHistory(ctx, projectId, env, key) Get secret version history
ListPermissions(ctx, projectId, env) List permissions
SetPermission(ctx, projectId, env, userId, role) Set user permission
DeletePermission(ctx, projectId, env, userId) Delete permission
BulkSetPermissions(ctx, projectId, env, perms) Bulk set permissions
GetMyPermissions(ctx, projectId) Get current user's permissions
GetProjectDefaults(ctx, projectId) Get default permissions
SetProjectDefaults(ctx, projectId, defaults) Set default permissions
ClearCache(projectId, env) Clear cached secrets
ClearAllCache() Clear all cached data

Examples

HTTP Server
package main

import (
    "context"
    "log"
    "net/http"
    "os"

    "github.com/keyenv/go-sdk"
)

func main() {
    client, _ := keyenv.New(keyenv.Config{
        Token: os.Getenv("KEYENV_TOKEN"),
    })

    // Load secrets before starting server
    client.LoadEnv(context.Background(), os.Getenv("KEYENV_PROJECT"), "production")

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("OK"))
    })

    log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), nil))
}
Lambda Function
package main

import (
    "context"
    "os"
    "time"

    "github.com/aws/aws-lambda-go/lambda"
    "github.com/keyenv/go-sdk"
)

var client *keyenv.Client

func init() {
    client, _ = keyenv.New(keyenv.Config{
        Token:    os.Getenv("KEYENV_TOKEN"),
        CacheTTL: 5 * time.Minute, // Cache across warm invocations
    })
    client.LoadEnv(context.Background(), os.Getenv("KEYENV_PROJECT"), "production")
}

func handler(ctx context.Context) (string, error) {
    return os.Getenv("API_KEY"), nil
}

func main() {
    lambda.Start(handler)
}

License

MIT License - see LICENSE for details.

Documentation

Overview

Package keyenv provides a Go SDK for the KeyEnv secrets management service.

Package keyenv provides a Go SDK for the KeyEnv secrets management service.

Index

Constants

View Source
const (
	// DefaultBaseURL is the default API endpoint.
	DefaultBaseURL = "https://api.keyenv.dev"

	// DefaultTimeout is the default HTTP request timeout.
	DefaultTimeout = 30 * time.Second

	// Version is the SDK version.
	Version = "1.0.0"
)

Variables

View Source
var (
	ErrUnauthorized = &Error{Status: 401, Message: "Unauthorized"}
	ErrForbidden    = &Error{Status: 403, Message: "Forbidden"}
	ErrNotFound     = &Error{Status: 404, Message: "Not found"}
	ErrConflict     = &Error{Status: 409, Message: "Conflict"}
	ErrRateLimited  = &Error{Status: 429, Message: "Rate limited"}
)

Common error variables for sentinel error checking.

Functions

This section is empty.

Types

type BulkImportOptions

type BulkImportOptions struct {
	// Overwrite controls whether existing secrets should be updated.
	Overwrite bool `json:"overwrite"`
}

BulkImportOptions holds options for bulk import operations.

type BulkImportResult

type BulkImportResult struct {
	Created int `json:"created"`
	Updated int `json:"updated"`
	Skipped int `json:"skipped"`
}

BulkImportResult contains the results of a bulk import operation.

type Client

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

Client is the KeyEnv API client.

func New

func New(config Config) (*Client, error)

New creates a new KeyEnv client with the given configuration.

func (*Client) BulkImport

func (c *Client) BulkImport(ctx context.Context, projectID, environment string, secrets []SecretInput, options BulkImportOptions) (*BulkImportResult, error)

BulkImport imports multiple secrets at once.

func (*Client) BulkSetPermissions

func (c *Client) BulkSetPermissions(ctx context.Context, projectID, environment string, permissions []PermissionInput) error

BulkSetPermissions sets multiple permissions at once.

func (*Client) ClearAllCache

func (c *Client) ClearAllCache()

ClearAllCache clears all cached data.

func (*Client) ClearCache

func (c *Client) ClearCache(projectID, environment string)

ClearCache clears the cache for a specific project/environment combination.

func (*Client) CreateEnvironment

func (c *Client) CreateEnvironment(ctx context.Context, projectID, name string, inheritsFrom *string) (*Environment, error)

CreateEnvironment creates a new environment in a project.

func (*Client) CreateProject

func (c *Client) CreateProject(ctx context.Context, teamID, name string) (*Project, error)

CreateProject creates a new project.

func (*Client) DeleteEnvironment

func (c *Client) DeleteEnvironment(ctx context.Context, projectID, environment string) error

DeleteEnvironment deletes an environment from a project.

func (*Client) DeletePermission

func (c *Client) DeletePermission(ctx context.Context, projectID, environment, userID string) error

DeletePermission removes a user's permission for an environment.

func (*Client) DeleteProject

func (c *Client) DeleteProject(ctx context.Context, projectID string) error

DeleteProject deletes a project.

func (*Client) DeleteSecret

func (c *Client) DeleteSecret(ctx context.Context, projectID, environment, key string) error

DeleteSecret deletes a secret by key.

func (*Client) ExportSecrets

func (c *Client) ExportSecrets(ctx context.Context, projectID, environment string) ([]SecretWithValueAndInheritance, error)

ExportSecrets returns all secrets with their values for an environment.

func (*Client) ExportSecretsAsMap

func (c *Client) ExportSecretsAsMap(ctx context.Context, projectID, environment string) (map[string]string, error)

ExportSecretsAsMap returns secrets as a key-value map.

func (*Client) GenerateEnvFile

func (c *Client) GenerateEnvFile(ctx context.Context, projectID, environment string) (string, error)

GenerateEnvFile generates a .env file content string.

func (*Client) GetCurrentUser

func (c *Client) GetCurrentUser(ctx context.Context) (*CurrentUserResponse, error)

GetCurrentUser returns information about the current authenticated user or service token.

func (*Client) GetMyPermissions

func (c *Client) GetMyPermissions(ctx context.Context, projectID string) (*MyPermissionsResponse, error)

GetMyPermissions returns the current user's permissions for a project.

func (*Client) GetProject

func (c *Client) GetProject(ctx context.Context, projectID string) (*Project, error)

GetProject returns a project by ID including its environments.

func (*Client) GetProjectDefaults

func (c *Client) GetProjectDefaults(ctx context.Context, projectID string) ([]DefaultPermission, error)

GetProjectDefaults returns the default permissions for a project.

func (*Client) GetSecret

func (c *Client) GetSecret(ctx context.Context, projectID, environment, key string) (*SecretWithValue, error)

GetSecret returns a single secret by key.

func (*Client) GetSecretHistory

func (c *Client) GetSecretHistory(ctx context.Context, projectID, environment, key string) ([]SecretHistory, error)

GetSecretHistory returns the version history of a secret.

func (*Client) ListEnvironments

func (c *Client) ListEnvironments(ctx context.Context, projectID string) ([]Environment, error)

ListEnvironments returns all environments in a project.

func (*Client) ListPermissions

func (c *Client) ListPermissions(ctx context.Context, projectID, environment string) ([]Permission, error)

ListPermissions returns permissions for an environment.

func (*Client) ListProjects

func (c *Client) ListProjects(ctx context.Context) ([]Project, error)

ListProjects returns all projects accessible to the current user or service token.

func (*Client) ListSecrets

func (c *Client) ListSecrets(ctx context.Context, projectID, environment string) ([]SecretWithInheritance, error)

ListSecrets returns secret keys (without values) for an environment.

func (*Client) LoadEnv

func (c *Client) LoadEnv(ctx context.Context, projectID, environment string) (int, error)

LoadEnv loads secrets into environment variables. Returns the number of secrets loaded.

func (*Client) SetPermission

func (c *Client) SetPermission(ctx context.Context, projectID, environment, userID, role string) error

SetPermission sets a user's permission for an environment.

func (*Client) SetProjectDefaults

func (c *Client) SetProjectDefaults(ctx context.Context, projectID string, defaults []DefaultPermission) error

SetProjectDefaults sets the default permissions for a project.

func (*Client) SetSecret

func (c *Client) SetSecret(ctx context.Context, projectID, environment, key, value string) error

SetSecret creates or updates a secret.

func (*Client) SetSecretWithDescription

func (c *Client) SetSecretWithDescription(ctx context.Context, projectID, environment, key, value string, description *string) error

SetSecretWithDescription creates or updates a secret with a description.

func (*Client) ValidateToken

func (c *Client) ValidateToken(ctx context.Context) (*CurrentUserResponse, error)

ValidateToken validates the token and returns user info.

type Config

type Config struct {
	// Token is the service token for authentication (required).
	Token string

	// BaseURL is the API base URL (optional, defaults to https://api.keyenv.dev).
	BaseURL string

	// Timeout is the HTTP request timeout (optional, defaults to 30s).
	Timeout time.Duration

	// CacheTTL is the cache time-to-live duration (optional, 0 means disabled).
	CacheTTL time.Duration
}

Config holds the configuration options for the KeyEnv client.

type CurrentUserResponse

type CurrentUserResponse struct {
	// Common fields
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"created_at"`

	// Auth type: "service_token" or "user"
	AuthType string `json:"auth_type,omitempty"`

	// Service token fields (when auth_type is "service_token")
	TeamID     string   `json:"team_id,omitempty"`
	ProjectIDs []string `json:"project_ids,omitempty"`
	Scopes     []string `json:"scopes,omitempty"`

	// User fields (when auth_type is "user" or not a service token)
	Email     string `json:"email,omitempty"`
	Name      string `json:"name,omitempty"`
	ClerkID   string `json:"clerk_id,omitempty"`
	AvatarURL string `json:"avatar_url,omitempty"`

	// Legacy fields for backward compatibility
	Type         string        `json:"type,omitempty"` // Deprecated: use AuthType
	User         *User         `json:"user,omitempty"`
	ServiceToken *ServiceToken `json:"service_token,omitempty"`
}

CurrentUserResponse contains information about the current authenticated user or token. For service tokens, it returns a flat structure with token info. For users, it returns the user profile with team memberships.

func (*CurrentUserResponse) IsServiceToken

func (r *CurrentUserResponse) IsServiceToken() bool

IsServiceToken returns true if this response represents a service token.

type DefaultPermission

type DefaultPermission struct {
	EnvironmentName string `json:"environment_name"`
	DefaultRole     string `json:"default_role"`
}

DefaultPermission represents default permission settings for an environment.

type Environment

type Environment struct {
	ID             string    `json:"id"`
	Name           string    `json:"name"`
	Description    string    `json:"description,omitempty"`
	ProjectID      string    `json:"project_id"`
	InheritsFromID *string   `json:"inherits_from_id,omitempty"`
	Order          int       `json:"order"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
}

Environment represents a KeyEnv environment within a project.

type Error

type Error struct {
	// Status is the HTTP status code.
	Status int `json:"status"`

	// Message is the error message.
	Message string `json:"message"`

	// Code is an optional error code for programmatic handling.
	Code string `json:"code,omitempty"`
}

Error represents an error returned by the KeyEnv API.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) IsConflict

func (e *Error) IsConflict() bool

IsConflict returns true if the error is a 409 Conflict error.

func (*Error) IsForbidden

func (e *Error) IsForbidden() bool

IsForbidden returns true if the error is a 403 Forbidden error.

func (*Error) IsNotFound

func (e *Error) IsNotFound() bool

IsNotFound returns true if the error is a 404 Not Found error.

func (*Error) IsRateLimited

func (e *Error) IsRateLimited() bool

IsRateLimited returns true if the error is a 429 Too Many Requests error.

func (*Error) IsServerError

func (e *Error) IsServerError() bool

IsServerError returns true if the error is a 5xx server error.

func (*Error) IsUnauthorized

func (e *Error) IsUnauthorized() bool

IsUnauthorized returns true if the error is a 401 Unauthorized error.

type MyPermissionsResponse

type MyPermissionsResponse struct {
	Permissions []Permission `json:"permissions"`
	IsTeamAdmin bool         `json:"is_team_admin"`
}

MyPermissionsResponse contains the current user's permissions.

type Permission

type Permission struct {
	ID              string    `json:"id"`
	UserID          string    `json:"user_id"`
	UserEmail       string    `json:"user_email"`
	EnvironmentID   string    `json:"environment_id"`
	EnvironmentName string    `json:"environment_name,omitempty"`
	Role            string    `json:"role"`
	CanWrite        bool      `json:"can_write"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

Permission represents a user's permission for an environment.

type PermissionInput

type PermissionInput struct {
	UserID string `json:"user_id"`
	Role   string `json:"role"`
}

PermissionInput represents input for setting a permission.

type Project

type Project struct {
	ID           string        `json:"id"`
	Name         string        `json:"name"`
	Description  string        `json:"description,omitempty"`
	TeamID       string        `json:"team_id"`
	CreatedAt    time.Time     `json:"created_at"`
	UpdatedAt    time.Time     `json:"updated_at"`
	Environments []Environment `json:"environments,omitempty"`
}

Project represents a KeyEnv project.

type Secret

type Secret struct {
	ID            string    `json:"id"`
	Key           string    `json:"key"`
	Description   *string   `json:"description,omitempty"`
	EnvironmentID string    `json:"environment_id"`
	SecretType    string    `json:"secret_type,omitempty"`
	Version       int       `json:"version"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

Secret represents a secret's metadata without the value.

type SecretHistory

type SecretHistory struct {
	ID         string    `json:"id"`
	SecretID   string    `json:"secret_id"`
	Key        string    `json:"key"`
	Version    int       `json:"version"`
	ChangedBy  *string   `json:"changed_by,omitempty"`
	ChangeType string    `json:"change_type"`
	CreatedAt  time.Time `json:"created_at"`
}

SecretHistory represents a historical version of a secret.

type SecretInput

type SecretInput struct {
	Key         string  `json:"key"`
	Value       string  `json:"value"`
	Description *string `json:"description,omitempty"`
}

SecretInput represents input for creating or importing a secret.

type SecretWithInheritance

type SecretWithInheritance struct {
	Secret
	InheritedFrom *string `json:"inherited_from,omitempty"`
}

SecretWithInheritance represents a secret with inheritance information.

type SecretWithValue

type SecretWithValue struct {
	Secret
	Value string `json:"value"`
}

SecretWithValue represents a secret including its decrypted value.

type SecretWithValueAndInheritance

type SecretWithValueAndInheritance struct {
	Secret
	Value         string  `json:"value"`
	InheritedFrom *string `json:"inherited_from,omitempty"`
}

SecretWithValueAndInheritance represents a secret with value and inheritance info.

type ServiceToken

type ServiceToken struct {
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	ProjectID   string     `json:"project_id"`
	ProjectName string     `json:"project_name,omitempty"`
	Permissions []string   `json:"permissions"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
}

ServiceToken represents information about a service token.

type Team

type Team struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Team represents a KeyEnv team.

type User

type User struct {
	ID        string    `json:"id"`
	Email     string    `json:"email"`
	FirstName string    `json:"first_name"`
	LastName  string    `json:"last_name"`
	AvatarURL string    `json:"avatar_url,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

User represents a KeyEnv user.

Jump to

Keyboard shortcuts

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