personalcloudlogs4datatug

package
v0.67.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package personalcloudlogs4datatug defines personal, direct-read Cloud Logging authorization. Provider SDKs, encrypted storage and distributed leases belong to the host. This package never persists log entries or query criteria.

Index

Constants

View Source
const (
	Active           = "active"
	Revoking         = "revocation_pending"
	Retired          = "retired"
	MaxEntries       = 200
	MaxResponseBytes = 2 << 20
	MaxPages         = 20
	QueryTimeout     = 30 * time.Second
	MaxWindow        = 24 * time.Hour
)

Variables

View Source
var (
	ErrUnsupported  = errors.New("unsupported_query")
	ErrInvalid      = errors.New("invalid_request")
	ErrUnauthorized = errors.New("unauthorized")
	ErrNotFound     = errors.New("not_found")
	ErrConflict     = errors.New("account_unavailable")
	ErrExpired      = errors.New("reconnect_required")
	ErrDenied       = errors.New("permission_denied")
	ErrThrottled    = errors.New("throttled")
	ErrUnavailable  = errors.New("unavailable")
)

Functions

func ValidateView

func ValidateView(project, view string) error

Types

type ActivationLifecycle

ActivationLifecycle is the server-only pause/resume and bounded reconciliation seam. It is separate from Registry so ordinary registry fakes and adapters do not need lifecycle controls.

type ActivationReconciliation

type ActivationReconciliation struct {
	Status               ActivationStatus `json:"status"`
	ActiveGrants         int              `json:"activeGrants"`
	RevokingGrants       int              `json:"revokingGrants"`
	PendingRemaining     bool             `json:"pendingRemaining"`
	CompletionsRemaining bool             `json:"completionsRemaining"`
	DurableReconciled    bool             `json:"durableReconciled"`
}

ActivationReconciliation reports durable registry state only. Provider revocation is not attested by this result.

type ActivationStatus

type ActivationStatus struct {
	Initialized bool   `json:"initialized"`
	Paused      bool   `json:"paused"`
	Epoch       uint64 `json:"epoch"`
}

ActivationStatus describes the private per-user OAuth activation fence. Epoch zero is always uninitialized and paused, including legacy rows.

type Authorization

type Authorization struct{ State, Nonce, Challenge, RedirectURI string }

type AuthorizationStart

type AuthorizationStart struct {
	AuthorizationURL string `json:"authorizationUrl"`
	FinishKey        string `json:"finishKey"`
}

AuthorizationStart contains no Google credential; FinishKey is the independent browser proof kept only in sessionStorage until OAuth completion or failure.

type Completion

type Completion struct {
	ReceiptHash, FinishKeyHash string
	Grant                      Grant
	ExpiresAt                  time.Time
	ActivationEpoch            uint64
}

Completion is a short-lived server-only sealed grant, not yet authorized for reads. ReceiptHash and FinishKeyHash must never appear in registry lists.

type Config

type Config struct {
	OAuthProject, RedirectURI string
	Registry                  Registry
	OAuth                     OAuth
	Vault                     Vault
	Operations                Operations
	Reader                    Reader
}

type Connection

type Connection struct {
	ID         string `json:"id"`
	GrantID    string `json:"grantId"`
	UID        string `json:"-"`
	Generation string `json:"-"`
	Project    string `json:"projectId"`
	View       string `json:"logViewId"`
	Active     bool   `json:"active"`
}

type Entry

type Entry struct {
	Service       string         `json:"service,omitempty"`
	CorrelationID string         `json:"correlationId,omitempty"`
	OrderID       string         `json:"orderId,omitempty"`
	TraceID       string         `json:"traceId,omitempty"`
	ParseStatus   string         `json:"parseStatus,omitempty"`
	Fields        map[string]any `json:"fields,omitempty"`
	Timestamp     *time.Time     `json:"timestamp,omitempty"`
	Severity      string         `json:"severity"`
	Source        string         `json:"source"`
	Message       string         `json:"message"`
	Raw           any            `json:"raw,omitempty"`
	SourceRef     string         `json:"sourceRef,omitempty"`
}

Entry mirrors ordinary log presentation. Raw evidence is response-only.

type Exchange

type Exchange struct{ Code, Verifier, Nonce, RedirectURI string }

type GoogleIdentity

type GoogleIdentity struct{ Subject, Email, RefreshToken string }

GoogleIdentity is returned only after issuer, audience, expiry AND nonce validation. Email is display-only. Required scopes must have been granted.

type Grant

type Grant struct {
	RevocationConfirmed                                      *bool
	PreviousRevocationUnconfirmed                            bool
	ID, UID, OAuthProject, Subject, Email, Generation, State string
	Ciphertext                                               []byte
	CreatedAt, DisconnectAt                                  time.Time
}

Grant is server-only. Ciphertext must be encrypted under a managed key with UID, ID and Generation authenticated as associated data. Never serialize into API responses. Server-only encrypted persistence may serialize this record.

func (Grant) Info

func (g Grant) Info() GrantInfo

Info returns only browser-safe grant metadata, including durable revocation warnings. Tokens, owner UID, Google subject and generation are never exposed.

type GrantInfo

type GrantInfo struct {
	RevocationConfirmed           *bool  `json:"revocationConfirmed,omitempty"`
	PreviousRevocationUnconfirmed bool   `json:"previousRevocationUnconfirmed,omitempty"`
	ID                            string `json:"id"`
	Email                         string `json:"email"`
	State                         string `json:"state"`
}

type Identity

type Identity struct {
	UID     string
	Browser bool
}

Identity is constructed ONLY by the host after Firebase/active DataTug grant verification. Browser is true only for a verified Firebase browser session.

type Listing

type Listing struct {
	Grants      []GrantInfo  `json:"grants"`
	Connections []Connection `json:"connections"`
}

type OAuth

type OAuth interface {
	AuthorizationURL(Authorization) (string, error)
	Exchange(context.Context, Exchange) (GoogleIdentity, error)
}

type Operations

type Operations interface {
	Acquire(context.Context, Grant, *Connection) (context.Context, func(), error)
	Cleanup(context.Context, Grant) (revocationConfirmed bool, err error)
}

Operations is the host's distributed generation fence. Acquire must atomically reject inactive grants/views and register a bounded cancellable lease before any decrypt, refresh, probe or provider query. Its release is idempotent. Cleanup blocks new leases, cancels/drains every refresh/query/revoke job, attempts provider revocation under a finite retry deadline and destroys ALL stored/cached credentials. It returns nil only after this barrier completes; provider-unconfirmed is an explicit terminal outcome, never an early unlock. Persist the cleanup outcome by generation before returning; retries after a failed FinishCleanup must return that same outcome even after token destruction. Never release the global subject reservation while an old job can run.

type Pending

type Pending struct {
	StateHash, UID, FinishKeyHash, Verifier, Nonce string
	ExpiresAt                                      time.Time
	ActivationEpoch                                uint64
}

type Query

type Query struct {
	From          time.Time `json:"from"`
	To            time.Time `json:"to"`
	Severity      string    `json:"severity,omitempty"`
	CorrelationID string    `json:"correlationId,omitempty"`
	OrderID       string    `json:"orderId,omitempty"`
	Service       string    `json:"service,omitempty"`
	Limit         int       `json:"limit,omitempty"`
}

func ValidateQuery

func ValidateQuery(q Query) (Query, error)

type Reader

type Reader interface {
	Probe(context.Context, Grant, Connection) error
	Query(context.Context, Grant, Connection, Query) (Result, error)
}

Reader uses only the grant's delegated user token and connection's fixed View; never ADC. Enforce MaxPages/MaxResponseBytes/QueryTimeout while scanning (even empty pages with continuation tokens). String equality is case-insensitive. No cache, persistence, telemetry payloads or automatic AI processing.

type Registry

type Registry interface {
	SavePending(context.Context, Pending) error
	// ConsumePending atomically checks expiry and removes state once. UID and
	// browser binding come only from the authenticated start request.
	ConsumePending(context.Context, string, time.Time) (Pending, error)
	SaveCompletion(context.Context, Completion) error
	// ActivateCompletion is ONE transaction: validate UID, receipt/finish-key hash,
	// OAuth project, active state and expiry; reserve the global subject; insert
	// the active grant; then consume the completion. An abort, conflict or wrong
	// caller MUST leave the completion intact for retry or expiration cleanup.
	// A still-unexpired completion may retry after the previous owner explicitly
	// disconnects and finishes cleanup; original UID and browser binding remain
	// mandatory. It cannot take over an active or revoking reservation.
	// A committed activation with a lost response remains discoverable via List.
	// A previously consumed receipt returns ErrUnauthorized and cannot re-claim.
	ActivateCompletion(context.Context, string, string, string, string, time.Time) (Grant, error)
	// PurgeExpired destroys expired pending states and sealed completions in a
	// bounded batch. The durable host recovery worker invokes this repeatedly.
	PurgeExpired(context.Context, time.Time, int) error
	GetGrant(context.Context, string, string) (Grant, error)
	List(context.Context, string) (Listing, error)
	GetConnection(context.Context, string, string) (Connection, error)
	CreateConnection(context.Context, Connection) error
	RemoveConnection(context.Context, string, string) error
	BeginDisconnect(context.Context, string, string, time.Time) (Grant, error)
	FinishCleanup(context.Context, string, string, bool) error
	// PendingCleanup returns at most limit revoking records after a durable
	// round-robin cursor, ordered oldest-first within the returned page. A
	// stranded oldest grant must not starve later grants across sweeps.
	PendingCleanup(context.Context, int) ([]Grant, error)
}

Registry operations are serializable and server-only. ActivateCompletion atomically reserves (OAuthProject, Subject) globally, including revoking grants, and must return ErrConflict without disclosing another UID. No timeout takeover exists. All owner checks return ErrNotFound for absent OR foreign records. Every write checks current generation; CreateConnection also checks the grant is active. BeginDisconnect atomically disables the grant and all children before returning. FinishCleanup releases subject ownership only after the host cleanup barrier; it destroys Ciphertext and persists the confirmed/unconfirmed revocation outcome in a credential-free terminal audit record. Preserve this outcome by subject after releasing its active reservation; a later activation must carry the last terminal outcome into PreviousRevocationUnconfirmed on the new grant. No method accepts log payloads, query filters, business IDs or query results.

type Result

type Result struct {
	Entries      []Entry `json:"entries"`
	Capped       bool    `json:"capped"`
	MorePossible bool    `json:"morePossible"`
}

type Service

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

func New

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

func (*Service) Begin

func (s *Service) Begin(ctx context.Context, id Identity) (AuthorizationStart, error)

Begin requests separate explicit consent for openid email logging.read with offline access. OAuth must use exactly this configured redirect and S256 PKCE.

func (*Service) Cleanup

func (s *Service) Cleanup(ctx context.Context, uid, grantID string) (bool, error)

Cleanup is invoked by the host's bounded retry worker, never by the browser. A failed cleanup preserves the global reservation. Only the Operations barrier can permit credential-free retirement and a subsequent fresh OAuth claim.

func (*Service) CleanupPending

func (s *Service) CleanupPending(ctx context.Context, limit int) error

CleanupPending recovers interrupted disconnects. The host schedules this bounded sweep at startup and periodically, owns its lifecycle, and supplies a deadline.

func (*Service) Complete

func (s *Service) Complete(ctx context.Context, state, code string) (string, error)

Complete consumes server-owned OAuth state and seals a short-lived completion. It does NOT claim a grant. The browser must finish with verified Firebase UID and the independent secret retained in its sessionStorage before redirect. This works across app/API sites without depending on third-party cookies.

func (*Service) Create

func (s *Service) Create(ctx context.Context, id Identity, grantID, project, view string) (Connection, error)

func (*Service) Disconnect

func (s *Service) Disconnect(ctx context.Context, id Identity, grantID string, confirm bool) error

func (*Service) Finish

func (s *Service) Finish(ctx context.Context, id Identity, receipt, finishKey string) (GrantInfo, error)

Finish atomically activates a sealed completion and claims its Google subject with the original Firebase UID and browser proof. Transaction failure never revokes Google tokens because another owner may currently use that subject.

func (*Service) List

func (s *Service) List(ctx context.Context, id Identity) (Listing, error)

func (*Service) Query

func (s *Service) Query(ctx context.Context, id Identity, connectionID string, q Query) (Result, error)

func (*Service) Remove

func (s *Service) Remove(ctx context.Context, id Identity, connectionID string) error

type Vault

type Vault interface {
	Seal(context.Context, Grant, string) ([]byte, error)
}

Jump to

Keyboard shortcuts

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