api

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const AuthModeTokenFile = AuthModeTokenStore

AuthModeTokenFile is the deprecated compatibility name for AuthModeTokenStore. The value and behavior are intentionally identical.

View Source
const (
	LocalSessionReadyEventV1Alpha1 = localsession.EventVersion
)

Session event schema versions for the host protocol on stdout.

Variables

This section is empty.

Functions

func GenerateSecret

func GenerateSecret() string

GenerateSecret creates a random secret string.

func HasScope

func HasScope(record *TokenRecord, required TokenScope, group string) bool

HasScope checks if a token record has the required scope for a given group.

func HasScopeForAction

func HasScopeForAction(record *TokenRecord, required TokenScope, group string, action string) bool

HasScopeForAction checks scope group and, when present, the action allowlist.

func IsExpired

func IsExpired(record *TokenRecord) bool

IsExpired checks if a token has expired.

func ListenAndServe

func ListenAndServe(ctx context.Context, service *app.Service, vault string, port int, logf func(string, ...any), options ...ServerOptions) error

func ServeSupervisedSession added in v0.3.0

func ServeSupervisedSession(ctx context.Context, options ServeSupervisedSessionOptions) error

ServeSupervisedSession runs the readonly loopback reader surface for one bootstrap frame. Only the reader route group is exposed; the legacy API, temp tokens and audit writes stay out of this mode entirely. EOF on stdin stops new requests and drains for at most five seconds before shutdown.

func VerifySecret

func VerifySecret(record *TokenRecord, secret string) bool

VerifySecret checks if a plaintext secret matches the stored hash.

func WriteSessionError added in v0.3.0

func WriteSessionError(writer io.Writer, code, message string) error

WriteSessionError emits one redacted error event for host consumption.

Types

type AuditEntry

type AuditEntry struct {
	Timestamp string `json:"ts"`
	TokenID   string `json:"token_id"`
	Method    string `json:"method"`
	Path      string `json:"path"`
	Scope     string `json:"scope,omitempty"`
	Group     string `json:"group,omitempty"`
	Status    int    `json:"status"`
}

AuditEntry represents a single audit log entry.

type AuditLogger

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

AuditLogger writes audit entries to a JSONL file.

func NewAuditLogger

func NewAuditLogger(path string) (*AuditLogger, error)

NewAuditLogger creates a new audit logger writing to the given path.

func (*AuditLogger) Close

func (l *AuditLogger) Close() error

Close closes the audit log file.

func (*AuditLogger) Log

func (l *AuditLogger) Log(entry AuditEntry) error

Log writes an audit entry to the log file.

type AuthMode

type AuthMode int

AuthMode defines the authentication mode for the API server.

const (
	AuthModeUnset      AuthMode = iota // zero value: no auth (tests)
	AuthModeTemp                       // default: temp token in memory
	AuthModeTokenStore                 // --token-store: hashed long-lived token registry
	AuthModeNone                       // --no-auth: no auth, loopback only
)

type CachePolicy

type CachePolicy struct {
	MaxAge int    // seconds
	Scope  string // "public" or "private"
}

CachePolicy defines caching parameters for a route.

type DispatcherOptions

type DispatcherOptions struct {
	AllowWrite      bool
	Manifest        ManifestProvider
	Readiness       app.ConnectionReadinessOptions
	OperationAccess app.OperationAccess
}

type FileTokenStore

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

FileTokenStore stores tokens in a JSON file.

func NewFileTokenStore

func NewFileTokenStore(path string) (*FileTokenStore, error)

NewFileTokenStore creates or opens a file-based token store.

func (*FileTokenStore) Create

func (f *FileTokenStore) Create(record *TokenRecord) error

Create stores a new token record to the file.

func (*FileTokenStore) Delete

func (f *FileTokenStore) Delete(id string) error

Delete removes a token by ID from the file.

func (*FileTokenStore) Get

func (f *FileTokenStore) Get(id string) (*TokenRecord, error)

Get retrieves a token by ID from the file.

func (*FileTokenStore) List

func (f *FileTokenStore) List() ([]*TokenRecord, error)

List returns all token records from the file.

func (*FileTokenStore) Update

func (f *FileTokenStore) Update(record *TokenRecord) error

Update modifies an existing token record in the file.

func (*FileTokenStore) Verify

func (f *FileTokenStore) Verify(secret string) (*TokenRecord, error)

Verify checks a secret against all stored tokens in the file.

type HTTPRPCRequest

type HTTPRPCRequest struct {
	ID     string         `json:"id,omitempty"`
	Method string         `json:"method"`
	Params map[string]any `json:"params,omitempty"`
}

type ManifestProvider added in v0.3.0

type ManifestProvider func() (domain.Projection, error)

type MemoryTokenStore

type MemoryTokenStore struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

MemoryTokenStore stores tokens in process memory.

func NewMemoryTokenStore

func NewMemoryTokenStore() *MemoryTokenStore

NewMemoryTokenStore creates a new in-memory token store.

func (*MemoryTokenStore) Create

func (m *MemoryTokenStore) Create(record *TokenRecord) error

Create stores a new token record.

func (*MemoryTokenStore) Delete

func (m *MemoryTokenStore) Delete(id string) error

Delete removes a token by ID.

func (*MemoryTokenStore) Get

func (m *MemoryTokenStore) Get(id string) (*TokenRecord, error)

Get retrieves a token by ID.

func (*MemoryTokenStore) List

func (m *MemoryTokenStore) List() ([]*TokenRecord, error)

List returns all token records.

func (*MemoryTokenStore) Update

func (m *MemoryTokenStore) Update(record *TokenRecord) error

Update modifies an existing token record.

func (*MemoryTokenStore) Verify

func (m *MemoryTokenStore) Verify(secret string) (*TokenRecord, error)

Verify checks a secret against all stored tokens.

type RPCDispatcher

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

func NewRPCDispatcher

func NewRPCDispatcher(service *app.Service, vault string) *RPCDispatcher

func NewRPCDispatcherWithOptions

func NewRPCDispatcherWithOptions(service *app.Service, vault string, options DispatcherOptions) *RPCDispatcher

func (*RPCDispatcher) Call

type RPCRequest

type RPCRequest struct {
	Method string         `json:"method"`
	Params map[string]any `json:"params,omitempty"`
}

type ReaderSession added in v0.3.0

type ReaderSession struct {
	SessionID string
	BindingID string
	Nonce     string
	Scopes    []string
	ExpiresAt time.Time
	CreatedAt time.Time
}

ReaderSession is one authorized human reading session.

func (*ReaderSession) Expired added in v0.3.0

func (s *ReaderSession) Expired() bool

Expired reports whether the session passed its deadline.

func (*ReaderSession) HasScope added in v0.3.0

func (s *ReaderSession) HasScope(scope string) bool

HasScope reports whether the session grants a reader scope.

type ReaderSessionStore added in v0.3.0

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

ReaderSessionStore keeps bearer digests in process memory. Secrets are hashed at rest and never persisted.

func NewReaderSessionStore added in v0.3.0

func NewReaderSessionStore() (*ReaderSessionStore, error)

NewReaderSessionStore creates an empty in-memory registry with a random cursor signing secret.

func (*ReaderSessionStore) AuthorizeRecovery added in v0.3.1

func (s *ReaderSessionStore) AuthorizeRecovery(sessionID string, frame []byte) error

AuthorizeRecovery receives an explicitly approved private host frame. It must never be called with HTTP/renderer-supplied authority or old digests. The current bearer alone does not permit installation of recovery grants.

func (*ReaderSessionStore) Create added in v0.3.0

func (s *ReaderSessionStore) Create(session ReaderSession, bearer string) error

Create registers a session for a fresh bearer secret.

func (*ReaderSessionStore) CursorSecret added in v0.3.0

func (s *ReaderSessionStore) CursorSecret() []byte

CursorSecret returns the cursor signing key for this server process.

func (*ReaderSessionStore) LookupRecovery added in v0.3.1

func (s *ReaderSessionStore) LookupRecovery(ctx context.Context, bearer, operationID string) (operation.View, error)

LookupRecovery revalidates the actual current bearer, not a cached session snapshot. Lock order is registry -> owner recovery; neither owner nor its snapshot reader calls back into this registry. Revoke waits for an admitted lookup, and no new lookup can pass after Revoke returns.

func (*ReaderSessionStore) PrepareRecovery added in v0.3.1

func (s *ReaderSessionStore) PrepareRecovery(sessionID, root string) (localsession.RecoveryLookupContext, error)

PrepareRecovery is a TRUSTED HOST integration point, not an HTTP action. The root comes from the independently approved vault selection, not a query or renderer path. A session gets only one owner filesystem observation.

func (*ReaderSessionStore) Revoke added in v0.3.0

func (s *ReaderSessionStore) Revoke(sessionID string)

Revoke removes a session by ID.

func (*ReaderSessionStore) Verify added in v0.3.0

func (s *ReaderSessionStore) Verify(bearer string) (*ReaderSession, error)

Verify resolves a bearer to its live session.

type RouteInfo

type RouteInfo struct {
	Group    string
	Method   string
	Action   string
	Readonly bool
}

RouteInfo describes a route's group and method for scope checking.

type ScopeTarget

type ScopeTarget struct {
	Groups  []string `json:"groups,omitempty"`
	Actions []string `json:"actions,omitempty"`
}

ScopeTarget defines which groups and actions a scope covers.

type ServeSupervisedSessionOptions added in v0.3.0

type ServeSupervisedSessionOptions struct {
	Service       *app.Service
	Frame         SessionBootstrapFrame
	Stdin         io.Reader // liveness channel; closed stdin stops the server
	Stdout        io.Writer // redacted host protocol
	Stderr        io.Writer // human diagnostics; never secrets
	Manifest      ManifestProvider
	RecoveryStdin bool // explicit private host handshake; never enabled by bootstrap fields
}

ServeSupervisedSessionOptions configures the supervised reader server.

type Server

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

func NewServer

func NewServer(service *app.Service, vault string) *Server

func NewServerWithOptions

func NewServerWithOptions(service *app.Service, vault string, options ServerOptions) *Server

func (*Server) Handler

func (s *Server) Handler() http.Handler

type ServerOptions

type ServerOptions struct {
	AllowWrite bool
	AuthMode   AuthMode
	TokenStore string
	// TokenFile is the deprecated compatibility field for TokenStore.
	TokenFile    string
	ExposeGroups []string
	HideGroups   []string
	Logger       *zap.Logger
	Manifest     ManifestProvider
	// ReaderSessions enables the human reading surface. Nil keeps reader
	// routes off (reader_disabled) without touching legacy auth.
	ReaderSessions *ReaderSessionStore
}

type SessionBootstrapFrame added in v0.3.0

type SessionBootstrapFrame = localsession.Bootstrap

SessionBootstrapFrame is the versioned private stdin first frame (pinax.local_session.bootstrap.v1alpha1). Secret fields never reach logs.

func ReadSessionBootstrap added in v0.3.0

func ReadSessionBootstrap(reader io.Reader) (SessionBootstrapFrame, error)

ReadSessionBootstrap reads and validates the private first frame. The host keeps stdin open for liveness after the frame, so exactly one newline-terminated frame is consumed — never until EOF. The frame is capped at 16 KiB; unknown fields, unknown schema versions, unknown scopes, mutation requests and malformed secrets are rejected.

func ReadSessionBootstrapWithDeadline added in v0.3.0

func ReadSessionBootstrapWithDeadline(ctx context.Context, reader io.Reader) (SessionBootstrapFrame, error)

ReadSessionBootstrapWithDeadline applies the 10s first-frame deadline.

type SessionEvent added in v0.3.0

type SessionEvent = localsession.Event

SessionEvent is one redacted stdout protocol message.

type TokenRecord

type TokenRecord struct {
	ID          string                     `json:"id"`
	SecretHash  string                     `json:"secret_hash"`
	Salt        string                     `json:"salt"`
	Scope       map[TokenScope]ScopeTarget `json:"scope"`
	Label       string                     `json:"label,omitempty"`
	CreatedAt   string                     `json:"created_at"`
	ExpiresAt   string                     `json:"expires_at,omitempty"`
	LastUsedAt  string                     `json:"last_used_at,omitempty"`
	RotatedFrom string                     `json:"rotated_from,omitempty"`
	CreatedBy   string                     `json:"created_by"`
}

TokenRecord represents a stored API token.

func GenerateTokenRecord

func GenerateTokenRecord(label string, scope map[TokenScope]ScopeTarget, expiresAt string, createdBy string) (*TokenRecord, string)

GenerateTokenRecord creates a new token record and returns it along with the plaintext secret.

type TokenScope

type TokenScope string

TokenScope defines the permission scope of a token.

const (
	ScopeRead  TokenScope = "read"  // All GET routes
	ScopeWrite TokenScope = "write" // All mutation routes
	ScopeAdmin TokenScope = "admin" // Token management itself
)

type TokenStore

type TokenStore interface {
	Verify(secret string) (*TokenRecord, error)
	Create(record *TokenRecord) error
	Get(id string) (*TokenRecord, error)
	List() ([]*TokenRecord, error)
	Delete(id string) error
	Update(record *TokenRecord) error
}

TokenStore is the interface for token persistence and verification.

Jump to

Keyboard shortcuts

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