dataaccess

package
v0.136.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

README

Shared data access boundary

dataaccess provides shared DataTug contracts and a bounded read-authorization foundation. DALgo's access package evaluates policies before adapter dispatch. This package is a core proof checkpoint; production opener wiring, CLI integration and completion of the data-access-security plan remain pending.

Consumer contract

The host constructs NewAuthority with an authenticated, host-assigned Subject, a resolved ConnectionRef and an injected Resolver. The subject is fixed for that authority. Execution input must not choose a different subject or supply a local-owner flag as authority.

ConnectionRef binds a Space, a Space-local protection ID and a fingerprint. Every resolution must match that subject, Space and ID, the protection ID, and both connection fingerprints. Fingerprints compare engine, database and engine identity. When engine identity is absent, the address must match; otherwise the address is only a hint. An engine identity can identify cluster lineage rather than a unique physical database.

NewLocalAuthority is the explicit alternative for a host-owned source with no enrolled Space. Its LocalConnectionRef binds a local authority ID, source ID and independently measured fingerprint. Its resulting ConnectionRef has an empty Space and an explicit localAuthorityId; it is never an enrolled decision actor. NewAuthority refuses a mixed Space/local identity. The same trusted resolver, evaluator and lifetime guards apply, but a local resolution cannot carry grants. Host ownership loss, changed local identity or changed baseline must fail resolution. A local ID supplied by a model is not host ownership.

Authority.SecureDB accepts the corresponding DALgo database and returns the narrow Database interface. The host is responsible for verifying that the supplied database matches the resolved connection and keeping its raw handle out of consumer code. The factory does not perform native identity discovery or establish a production opener boundary by itself.

The resolver is a trusted authenticated authority port. It must verify current membership, protection and grant state, enforce the control plane's grant lifecycle and duration limits, and return an error when that authority cannot be established. Client-supplied grants or approval files are not an authority source. ServerTime and ValidUntil must be verified server facts, with ServerTime fresh for that resolve call. A cached reply must not be replayed as new authority. Any future caching adapter must preserve the reply's original age and deadline. This checkpoint resolves before each operation or reader release and rechecks successful results before returning them; it provides no caching adapter.

DecodeAccessRequest and DecodeGrant are the MVP wire admission points. They reject unknown fields, duplicate or case-folded duplicate keys, trailing input, and later-phase fields even when null or empty. Connection-read scopes require an explicit empty requires list. Exact-object read requests require objects.exact; request admission alone does not enable object-grant execution. Unknown required features are refused. Plain JSON unmarshalling is not wire admission.

Supported execution

Surface Current behavior
Exists Checks authority around the typed read.
Get, GetMulti Stages data into fresh containers; publishes only after successful read and authority recheck. Supports non-nil maps, non-nil pointers and fixed-length slices. Nil, scalar, key-only or inaccessible targets are refused before dispatch.
ExecuteQueryToRecordsReader Accepts only DALgo's built-in, unconditional, single-root-collection key-query profile. Default SecureDB accepts only unqualified sources without aliases. The explicit opt-in described below also accepts verified schema/name components and aliases. Both preserve limit, offset and cursor and refuse parent collections, database qualifiers, filters, joins, grouping, having, ordering, projections and source scan directives. Foreign or typed-nil query/from implementations are refused.
RunReadonlyTransaction Returns only a guarded read transaction and bounds its context and lifetime. Retained transaction handles cannot be used after RunReadonlyTransaction returns.

Standing posture all permits the supported reads. Posture none needs an approved, unexpired data.read grant matching the operation. Point reads, transactions and version1 retained-result capture/import/release require connection-wide authority; an exact-object grant cannot substitute for it. Active grants form a union: a shorter grant cannot shorten standing authority or a longer matching grant, and the existence of an object grant cannot narrow standing all. Agent subjects use the agent posture and cannot inherit human grants or execute with grants in this checkpoint. Unsupported grant fields and mandatory fine-grained protection fail closed.

SecureDBWithTableIdentity is an optional trusted-host composition point for one actual opened database. It permits exact-object grants only for the frozen explicit-schema key-query profile, with database empty and schema/name matching byte-for-byte. Each operation compiles ordinary DALgo Root/TableScope read rules from the current posture and active-grant union; DALgo remains the evaluator. It uses DALgo's shared ResourcesForQuery mapping and checks table metadata before opaque kind, with no raw-query fallback. Bare names never acquire a namespace from a grant or a prefix. Different literal dots, quotes and case are different names, and Core never rewrites them.

The optional TableIdentityVerifier supplies facts, never permissions. It must independently corroborate the exact opened handle, authenticated source binding and native execution identity. It must establish immutable source routing and identifier/compiler behavior across the complete database/reader lifetime, or pin an equivalent execution span. Before/after metadata samples alone cannot prove that a mutable pool did not change and change back. Native folding, quote interpretation, temporary-schema aliases, default search paths or unsupported configuration must refuse when byte-exact execution cannot be proved. A flag or catalog echo alone is insufficient. Logical name equality does not prove physical relation lineage across DDL replacement.

Core permission candidacy and the original selected deadline precede any fact lookup. Denied Core authority, unlisted resources and unsupported profiles make no fact or adapter data calls. Additional restrictive DALgo context policies intersect before adapter data dispatch, but their denial may follow the trusted read-only identity-metadata lookup. The fact port receives scalar identity values and no grants or query payload; it must not mutate data or disclose secrets. Source/fact failures before or after I/O discard results and close held readers. Verifiers and resource requirements belong to one secured database and operation; none are installed globally on Authority.

Missing or nil verifiers do not enable the profile, and default SecureDB stays closed to qualified execution. Synthetic verifier fixtures test composition and fences only. No production opener or native naming verifier is certified or wired by this checkpoint.

All nine typed-write methods remain denied before adapter dispatch: Set, SetMulti, Insert, InsertMulti, Update, UpdateRecord, UpdateMulti, Delete and DeleteMulti. Adding a permissive context policy cannot widen the core's database policy.

Deadlines and retained values

The initial local deadline uses the interval from verified ServerTime to ValidUntil, capped at 60 seconds and, when grant authority is needed, the matching grant expiry. An unrelated surviving object grant cannot extend it. The interval starts before resolution I/O, so that latency consumes the budget. Transactions and readers retain their original deadline; a refresh cannot extend it. Query readers retain exact mapped resource requirements and grant/protection digest identity, and reauthorize before and after each page or cursor release. Replacement or downscoped grants cannot renew an existing reader. Fact-port I/O holds no reader ownership lock, so Close, cancellation and expiry can close it while a lookup stalls.

Point-read staging keeps newly fetched values out of caller-owned aliases when an adapter returns a partial error or authority expires or is revoked during I/O. Next and Cursor check authority before releasing records or tokens and discard late results on denial. Expiry or parent cancellation closes readers without waiting for their operation lock, including when an operation is blocked. Consumers must close readers when finished. Already delivered application values, caches and snapshots still need their own integration and release checks.

Result release makes a detached output copy and performs its last local authorization/deadline check immediately before handoff to the output operation. That authorized in-flight copy cannot be recalled by later cancellation or revocation. It stays intact while the writer consumes it and is cleared when Write returns. Writers must not retain or modify the buffer. Output serialization has its own mutex: a blocked writer cannot prevent Close, private retained-byte purge, expiry or native-span cleanup. No ownership mutex spans output I/O.

Unsupported surfaces and claim limits

ReadTableResult is a separate, explicit programmatic table-data profile. Core constructs one qualified all-column query, secures its native read session with DALgo's existing operation policy and context-policy intersection, and retains private serialized cells until a final release check. It admits no caller query, projection, filter, join, function, raw SQL, view, ordering or pagination. The bounded preview reads at most N+1 rows and returns at most N, with protected returnedRows, hasMore and complete metadata. Byte/type/column failures discard the entire preview. NULL, exact integer tokens and tagged base64 BLOBs are kept distinct. Mandatory fine-grained restrictions still refuse the profile.

This requires a trusted TableReadSource and a pinned TableReadSpan that proves the actual source/table/compiler/native limits before rows open. Later Verify calls must be SQL-free immutable-proof and liveness checks; fresh control-plane authority resolution is separate. No old key-profile verifier automatically enables recordset reads. The span is retained until result close/expiry, and the data reader must close successfully before any result publication. Final native cleanup after output cannot retract bytes: the host owns redacted lifecycle-error reporting. Cleanup and purge never hold an ownership lock across native I/O.

The separate version2 TableResultEnvelope binds its exact profile and operation alongside the original subject/source/request/nonce/digest/deadline. Import reconstructs resources from the independently expected operation and rejects v1; v1 import rejects v2. An added or replacement grant cannot rescue a retained result, and a shorter fresh ceiling is installed before any fact lookup can stall. No production opener, SQLite native profile or end-to-end consumer route is enabled merely by this Core API; each needs its own integration proof.

The returned interface exposes no schema metadata, adapter/native capabilities, raw handle or read-write transaction opener. Its object-only point operations, transactions, raw queries, general recordset readers and complex structured queries remain unsupported. Existing version1 result wire behavior is unchanged. Full standing policy/grant composition, native naming proof and production path coverage remain separate work.

Structured operation and result profile

ReadStructuredResult accepts an immutable StructuredRead: the existing serialized TugQL YAML/JSON, strict JSON apicontract.TypedValueOrSet bindings and bounded output rows/bytes. It accepts no caller-provided DALgo implementation, grants, subject, policies or credentials. Core privately parses the operation, uses DALgo's shared ResourcesForQuery for every source, and authorizes the same snapshot before opening a source. Supported projections, filters, joins, known aggregates, grouping/having, order, query limit and offset retain their complete semantics. The independent output bound returns a labelled preview and never changes the query's limit or ordering. Existing RHS-WHERE parameters use condeval.Substitute; unresolved or misplaced parameters refuse before opening. Typed integers and decimals that DALgo's generic numeric comparison cannot represent exactly refuse explicitly. No value is silently rounded into a query.

This single-connection profile requires a distinct trusted StructuredReadSource/StructuredReadSpan. Its SQL-free verifier must establish the actual immutable source, native read-only span, compiler/options and every resource identity, including joined sources. Request identities are requirements, not evidence to echo. A provider must refuse unsupported operations and enforce its own native allocation limits. Implementing the port, a recording fixture or an in-memory result does not certify a native driver. The published table-only SQLite profile does not implement this broader contract.

DALgo context row/field policies remain subordinate constraints. Core sets the explicit principal to its fixed host subject with no inherited roles or groups, so an Agent never acquires an ambient human identity. Explicit-realm policies must use that subject's realm. Core freezes any effective policy rewrite, unions its actual resources with the authored resources, and reauthorizes/reverifies that complete set before native data dispatch. Unknown or unprovable residuals fail closed. Mandatory fine-grained protection remains unsupported.

The returned Result owns the original authority/credential ceiling, private payload, reader, native span, purge and final fresh output gate. The strict version3 StructuredResultEnvelope carries the complete authored operation, original nonce/digest, and authenticated effective operation/resources. Import requires independently expected original intent and original request start time; it never executes the server's effective query. Its resources remain part of fresh retained-value authorization. Payloads use the same exact scalar/NULL/BLOB encoding and bounds as table data. Versions 1, table 2 and structured 3 reject one another.

Recursive subqueries currently refuse before opening because DALgo's nested route needs a separately owned intermediate-result and leaf-execution lifetime. Database-qualified/federated sources require independent authority and pinned spans for every actual source; this API refuses them before opening. Both remain unfinished integration work, as do production source constructors, CLI/MCP routes and native/provider claim gates. The explicit OQ-13 no-control-plane raw compatibility route and OQ-15 confirmed write-target route are distinct paths; neither is a fallback from an unsupported governed structured operation.

The tests prove shared authorization decisions across two recording implementations, including zero adapter calls for denied typed writes, and the deadline and value-release guards. They do not certify a native driver, force a misbehaving adapter to honor cancellation, prove arbitrary database functions side-effect-free, or prevent direct credential use outside this boundary. Native read-only modes, credentials and driver assurance require their own evidence. This foundation alone establishes no CLI, production or agent database guarantee.

Documentation

Overview

Package dataaccess owns shared DataTug access contracts and a bounded, adapter-independent read boundary. DALgo remains the policy evaluator.

Index

Constants

View Source
const ObjectsExact = "objects.exact"

ObjectsExact is the only optional scope feature defined for this checkpoint. A future selector feature must have a different name.

View Source
const StructuredReadProfile = "structured-recordset/1"

StructuredReadProfile is a single-connection structured recordset operation. It is distinct from the closed all-column table preview and from raw SQL.

View Source
const TableReadProfile = "table-recordset/1"

TableReadProfile admits only a Core-constructed, qualified, unconditional all-column recordset preview. It does not enable arbitrary structured queries.

Variables

This section is empty.

Functions

This section is empty.

Types

type AccessRequest

type AccessRequest struct {
	Permissions []Permission `json:"permissions"`
	Scope       GrantScope   `json:"scope"`
	Reason      string       `json:"reason"`
	ExpiresAt   time.Time    `json:"expiresAt"`
	CaseRef     *CaseRef     `json:"caseRef,omitempty"`
	PriorGrant  string       `json:"priorGrant,omitempty"`
}

AccessRequest carries no subject, requester, approval, or identity assertion. The control plane derives those from authenticated host facts.

func DecodeAccessRequest

func DecodeAccessRequest(data []byte) (AccessRequest, error)

DecodeAccessRequest and DecodeGrant are the MVP wire admission points. They reuse the core decoder's duplicate/case-folded key, unknown-field and trailing input checks. Unsupported field presence is refused even when its value is null or an empty collection. Plain json.Unmarshal is not wire admission.

func (AccessRequest) ValidateMVP

func (r AccessRequest) ValidateMVP() error

type AgentRead

type AgentRead string
const (
	AgentInherit AgentRead = "inherit"
	AgentNone    AgentRead = "none"
)

type Authority

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

Authority binds one host-assigned subject and one resolved connection. It does not accept a caller authorization token or a local-owner boolean.

func NewAuthority

func NewAuthority(subject Subject, connection ConnectionRef, resolve Resolver) (*Authority, error)

func NewLocalAuthority added in v0.135.0

func NewLocalAuthority(subject Subject, connection LocalConnectionRef, resolve Resolver) (*Authority, error)

NewLocalAuthority uses the same resolver/evaluator/lease boundary for a source with no enrolled Space. The trusted host resolver supplies its current baseline and source facts and refuses lost local ownership. Local resolutions cannot carry grants; no control-plane decision is fabricated for this route.

func (*Authority) CaptureResult added in v0.131.0

func (a *Authority) CaptureResult(ctx context.Context, request ResultRequest, read func(context.Context) ([]byte, error)) (*Result, error)

CaptureResult is a trusted host composition point. read must use the secured database for this Authority and transfer ownership of the complete serialized JSON payload buffer (Core clears it, including on read/validation failure). The first resolve precedes I/O, and neither I/O nor later release renews it. This transport checkpoint requires connection-wide read authority; object-only results require a separately reviewed resource-bound transport contract.

func (*Authority) ImportResult added in v0.131.0

func (a *Authority) ImportResult(ctx context.Context, request ResultRequest, requestStarted time.Time, envelope ResultEnvelope) (*Result, error)

ImportResult requires an authenticated trusted server envelope and independently expected subject, connection/scope, request digest and fresh nonce. The host pins the actual source identity from that trusted transport before constructing Authority. requestStarted MUST be captured before the HTTP request. The caller must bound ctx by the verified ORIGINAL credential deadline, not its refresh. Object grants never substitute for current connection-wide result authority. Ownership of envelope.Payload transfers to Core; it is cleared on every path and immediately after compaction, before any authority network I/O.

func (*Authority) ImportStructuredResult added in v0.135.0

func (a *Authority) ImportStructuredResult(ctx context.Context, request ResultRequest, started time.Time, expected StructuredRead, envelope StructuredResultEnvelope) (*Result, error)

ImportStructuredResult requires authenticated transport and independently expected original intent, subject, source, nonce and original credential deadline. Started is recorded BEFORE the network request. Payload ownership transfers to Core and is cleared before fresh authority I/O on every path.

func (*Authority) ImportTableResult added in v0.134.0

func (a *Authority) ImportTableResult(ctx context.Context, request ResultRequest, started time.Time, expected TableRead, envelope TableResultEnvelope) (*Result, error)

ImportTableResult requires the same authenticated transport and original credential/context/deadline discipline as ImportResult, plus an independently expected closed operation. The host pins actual server source identity first; the client never fabricates native span facts. Ownership of Payload transfers to Core, and caller bytes are cleared before any fresh authority network I/O.

func (*Authority) ReadStructuredResult added in v0.135.0

func (a *Authority) ReadStructuredResult(ctx context.Context, request ResultRequest, operation StructuredRead, source StructuredReadSource) (*Result, error)

ReadStructuredResult freezes serialized intent before resolving authority, opens only after every resource is a candidate, and retains the same original authority ceiling through native reads, serialization and guarded output. Additional DALgo context policies remain restrictive subordinate constraints.

func (*Authority) ReadTableResult added in v0.134.0

func (a *Authority) ReadTableResult(ctx context.Context, request ResultRequest, operation TableRead, source TableReadSource) (*Result, error)

ReadTableResult constructs and executes its own frozen operation, secures the supplied native session with DALgo, serializes actual cells into private bytes and returns a version2 retained result. Existing v1 capture stays connection- wide. The authenticated host computes ResultRequest from the actual complete command/scope; the client computes its expected digest independently.

func (*Authority) SecureDB

func (a *Authority) SecureDB(db dal.DB) (Database, error)

SecureDB is a trusted composition point: the host supplies the database that corresponds to the resolved ConnectionRef. Only the secured interface leaves it. Production opener wiring and its architecture ratchet are later work.

func (*Authority) SecureDBWithTableIdentity added in v0.133.2

func (a *Authority) SecureDBWithTableIdentity(db dal.DB, verifier TableIdentityVerifier) (Database, error)

SecureDBWithTableIdentity opts one actual opened DB into the bounded explicit- schema key-enumeration profile. The host owns the verifier's execution-span invariants; all permission decisions remain in Core and DALgo. Point keys, transactions and result transport retain their connection-wide requirements. Core permission candidacy and its selected ceiling precede fact lookup. Additional DALgo context policies still intersect before data dispatch; their denial may follow trusted identity-metadata lookup.

type CaseRef

type CaseRef struct {
	Kind string `json:"kind"`
	ID   string `json:"id"`
}

type ConnectionProtection

type ConnectionProtection struct {
	ID                   string             `json:"id"`
	Fingerprint          Fingerprint        `json:"fingerprint"`
	Name                 string             `json:"name"`
	Environment          string             `json:"environment,omitempty"`
	ReadOnly             bool               `json:"readOnly"`
	ReadPosture          ReadPosture        `json:"readPosture"`
	AgentRead            AgentRead          `json:"agentRead"`
	MaxDuration          map[Permission]int `json:"maxDuration,omitempty"` // seconds
	MandatoryFineGrained bool               `json:"mandatoryFineGrained"`
	Revision             int64              `json:"revision"`
}

type ConnectionRef

type ConnectionRef struct {
	Space       string      `json:"space"`
	ID          string      `json:"id"`
	Fingerprint Fingerprint `json:"fingerprint"`
	// LocalAuthorityID is host-owned local authority, mutually exclusive with
	// Space. Its presence never asserts enrollment or control-plane approval.
	LocalAuthorityID string `json:"localAuthorityId,omitempty"`
}

ConnectionRef includes the Space because protection IDs are Space-local.

type Database

type Database interface {
	dal.ReadwriteSession
	dal.ReadTransactionCoordinator
}

Database deliberately exposes no Schema, Adapter, native/optional capability, underlying handle, or read-write transaction opener. Those surfaces require separate integration proof. Typed writes remain callable only to return a DALgo policy denial before dispatch. Recordset queries are refused; the query profile supports only frozen, unconditional single-source key enumeration, with an explicit schema required for exact-object grants. Object-only retained result transport and transactions remain unavailable at this checkpoint. Point reads stage maps, non-nil pointers and fixed-length slices; nil, scalar or inaccessible targets are refused before dispatch. This additive boundary is a Task 4 checkpoint, not whole-task integration.

type Decision

type Decision struct {
	By       Subject   `json:"by"`
	At       time.Time `json:"at"`
	Note     string    `json:"note,omitempty"`
	Self     bool      `json:"self"`
	Narrowed bool      `json:"narrowed"`
}

type Denial

type Denial struct {
	Connection string     `json:"connection"`
	Capability Permission `json:"capability"`
	Code       string     `json:"code"`
}

Denial is safe to show across execution surfaces. It carries no query, credential, policy expression, resolved value, or untrusted upstream error.

func (*Denial) Error

func (e *Denial) Error() string

func (*Denial) Unwrap

func (e *Denial) Unwrap() error

type ExactReadPolicy added in v0.136.0

type ExactReadPolicy struct {
	Version    int           `json:"version"`
	Subject    Subject       `json:"subject"`
	Connection ConnectionRef `json:"connection"`
	Baseline   []ObjectRef   `json:"baseline"`
}

ExactReadPolicy contains only the subject's effective standing table scope. It is an authenticated authority projection, never stored policy or native identity proof. Private policy generations and denied names are not wire data.

func (*ExactReadPolicy) UnmarshalJSON added in v0.136.0

func (p *ExactReadPolicy) UnmarshalJSON(data []byte) error

type ExactReadSnapshot added in v0.136.0

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

ExactReadSnapshot is sealed private host configuration. Ordinary JSON encoding exposes no private facts. Only DecodeExactReadSnapshot creates a valid value. Hosts must collect ALL standing/catalog/mandatory/native facts from one owned generation and exclude old writers before enabling exact mode. This type does not establish that deployment fence or discover policies in unrelated handles.

func DecodeExactReadSnapshot added in v0.136.0

func DecodeExactReadSnapshot(data []byte) (*ExactReadSnapshot, error)

DecodeExactReadSnapshot admits only this bounded table-local deny profile. Unknown policy kinds, permissions, expressions or fields refuse; there is no custom-policy escape hatch. Names must match the trusted native inventory byte-for-byte, including namespace. Folded collisions conservatively refuse.

func (*ExactReadSnapshot) BindContext added in v0.136.0

func (s *ExactReadSnapshot) BindContext(ctx context.Context, subject Subject) (context.Context, error)

BindContext installs the SAME trusted namespace and compiled mandatory rules for actual secured native execution. Hosts must use this snapshot's closed configuration in both projection and execution, not an untracked source.

func (ExactReadSnapshot) Format added in v0.136.0

func (ExactReadSnapshot) Format(state fmt.State, _ rune)

func (ExactReadSnapshot) GoString added in v0.136.0

func (ExactReadSnapshot) GoString() string

func (ExactReadSnapshot) LogValue added in v0.136.0

func (ExactReadSnapshot) LogValue() slog.Value

func (*ExactReadSnapshot) MarshalJSON added in v0.136.0

func (*ExactReadSnapshot) MarshalJSON() ([]byte, error)

MarshalJSON deliberately omits every private fact, including future fields.

func (*ExactReadSnapshot) RequestableObjects added in v0.136.0

func (s *ExactReadSnapshot) RequestableObjects() []ObjectRef

RequestableObjects is intentionally disclosed configuration, separate from effective read metadata. Hosts must not substitute their old catalog port.

func (ExactReadSnapshot) String added in v0.136.0

func (ExactReadSnapshot) String() string

type FieldScope

type FieldScope struct {
	Include []string `json:"include,omitempty"`
	Exclude []string `json:"exclude,omitempty"`
}

type Fingerprint

type Fingerprint struct {
	Engine         string `json:"engine"`
	Database       string `json:"database"`
	EngineIdentity string `json:"engineIdentity,omitempty"`
	Address        string `json:"address,omitempty"`
}

Fingerprint is resolved by the host using the engine's identity facts. Address is a display hint when EngineIdentity is available; without that identity, binding falls back to Address. Identity can name cluster lineage.

type Grant

type Grant struct {
	ID          string       `json:"id"`
	Subject     Subject      `json:"subject"`
	RequestedBy Subject      `json:"requestedBy"`
	Permissions []Permission `json:"permissions"`
	Scope       GrantScope   `json:"scope"`
	Reason      string       `json:"reason"`
	CaseRef     *CaseRef     `json:"caseRef,omitempty"`
	NotBefore   *time.Time   `json:"notBefore,omitempty"`
	ExpiresAt   time.Time    `json:"expiresAt"`
	State       GrantState   `json:"state"`
	Decision    *Decision    `json:"decision,omitempty"`
	PriorGrant  string       `json:"priorGrant,omitempty"`
	Revision    int64        `json:"revision"`
}

func DecodeGrant

func DecodeGrant(data []byte) (Grant, error)

func (Grant) ValidateMVP

func (g Grant) ValidateMVP() error

type GrantScope

type GrantScope struct {
	Connection string          `json:"connection"`
	Schemas    []Selector      `json:"schemas,omitempty"`
	Objects    []ObjectRef     `json:"objects,omitempty"`
	Exclude    []Selector      `json:"exclude,omitempty"`
	Records    *RecordScope    `json:"records,omitempty"`
	Fields     *FieldScope     `json:"fields,omitempty"`
	Request    *RequestBinding `json:"request,omitempty"`
	Requires   []string        `json:"requires"`
}

func (GrantScope) ValidateMVP

func (s GrantScope) ValidateMVP(permissions []Permission) error

ValidateMVP admits connection reads and exact-object read requests. Execution of object grants requires a separately proven profile; admission alone never enables it. SecureDBWithTableIdentity provides one bounded opt-in profile. All not-yet-supported fields and unknown required features fail closed.

type GrantState

type GrantState string
const (
	Requested GrantState = "requested"
	Approved  GrantState = "approved"
	Refused   GrantState = "refused"
	Withdrawn GrantState = "withdrawn"
	Revoked   GrantState = "revoked"
	// Expired is computed from ExpiresAt; it is never a persisted transition.
	Expired GrantState = "expired"
)

type LocalConnectionRef added in v0.135.0

type LocalConnectionRef struct {
	AuthorityID string
	ID          string
	Fingerprint Fingerprint
}

LocalConnectionRef is constructed by the host from its owned source registry and independently resolved native identity. It is never model execution input. AuthorityID is local provenance, not an enrolled Space or an approval actor.

type ObjectRef

type ObjectRef struct {
	Namespace string `json:"namespace"`
	Name      string `json:"name"`
}

ObjectRef contains an already canonical namespace and exact object name. It never contains a wildcard, an identifier expression, or an address.

type Permission

type Permission string
const (
	DataRead   Permission = "data.read"
	DataWrite  Permission = "data.write"
	DataInsert Permission = "data.insert"
	DataUpdate Permission = "data.update"
	DataDelete Permission = "data.delete"
	DataReveal Permission = "data.reveal"
	QueryTugQL Permission = "query.tugql"
	QueryRaw   Permission = "query.raw"
)

type ReadPosture

type ReadPosture string
const (
	ReadAll  ReadPosture = "all"
	ReadNone ReadPosture = "none"
	// ReadExact requires a current ExactReadPolicy and a resource-bound read profile.
	ReadExact ReadPosture = "exact-v1"
)

type RecordScope

type RecordScope struct {
	Language  string          `json:"language"`
	Predicate json.RawMessage `json:"predicate"`
}

type RequestBinding

type RequestBinding struct {
	Fingerprint string `json:"fingerprint"`
}

type Resolution

type Resolution struct {
	Subject    Subject              `json:"subject"`
	Connection ConnectionRef        `json:"connection"`
	Protection ConnectionProtection `json:"protection"`
	Grants     []Grant              `json:"grants"`
	ServerTime time.Time            `json:"serverTime"`
	ValidUntil time.Time            `json:"validUntil"`
	ExactRead  *ExactReadPolicy     `json:"exactRead,omitempty"`
}

Resolution comes only from the injected authenticated authority port. The port verifies current membership and protection state, and refuses failure. ServerTime and ValidUntil are verified server facts, not local clock values. ServerTime must be fresh for this resolve call. A cached response must not be replayed as new authority; a future caching adapter must preserve its original age and deadline rather than rebase either onto the next call's local time.

func ProjectAgentExactRead added in v0.136.0

func ProjectAgentExactRead(ctx context.Context, user Resolution, agent Subject, s *ExactReadSnapshot) (Resolution, error)

ProjectAgentExactRead keeps User authentication/membership admission in the host, then narrows its effective standing baseline under a fixed Agent. Human grants never enter either the candidate set or Agent projection.

func ProjectExactRead added in v0.136.0

func ProjectExactRead(ctx context.Context, r Resolution, s *ExactReadSnapshot) (Resolution, error)

ProjectExactRead produces only positive read authority, never an audit view. Effective ExpiresAt caps must already be computed by the owning resolver. No generation, private deny name or private-policy fingerprint is returned. ctx supplies cancellation/deadline only. Hosts must qualify that the sealed snapshot contains every active mandatory constraint and BindContext governs the same native execution source. Ambient/hidden policy composition is not qualified by this API and must not be enabled merely because decoding passed.

type ResolveRequest

type ResolveRequest struct {
	Subject    Subject       `json:"subject"`
	Connection ConnectionRef `json:"connection"`
}

type Resolver

type Resolver func(context.Context, ResolveRequest) (Resolution, error)

type Result added in v0.131.0

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

Result keeps DataTug-owned values private until a final release check. Values handed to an output operation are detached copies and cannot be recalled. The handoff is authorized under mu; output I/O never holds that ownership lock. An in-flight copy stays intact until Write returns, then is cleared. Writers must obey io.Writer's contract: do not modify or retain the buffer.

func (*Result) Close added in v0.131.0

func (r *Result) Close()

Close discards retained values even if no subsequent release is requested.

func (*Result) WriteEnvelope added in v0.131.0

func (r *Result) WriteEnvelope(ctx context.Context, writer io.Writer) error

func (*Result) WritePayload added in v0.131.0

func (r *Result) WritePayload(ctx context.Context, writer io.Writer) error

type ResultEnvelope added in v0.131.0

type ResultEnvelope struct {
	Payload json.RawMessage `json:"payload"`
	Lease   ResultLease     `json:"lease"`
}

func DecodeResultEnvelope added in v0.131.0

func DecodeResultEnvelope(data []byte) (ResultEnvelope, error)

type ResultLease added in v0.131.0

type ResultLease struct {
	Version        int           `json:"version"`
	Subject        Subject       `json:"subject"`
	Connection     ConnectionRef `json:"connection"`
	GrantSetDigest string        `json:"grantSetDigest"`
	Nonce          string        `json:"nonce"`
	RequestSHA256  string        `json:"requestSHA256"`
	PayloadSHA256  string        `json:"payloadSHA256"`
	ServerTime     time.Time     `json:"serverTime"`
	ExpiresAt      time.Time     `json:"expiresAt"`
}

ResultLease is transport metadata, never a capability. ImportResult accepts it only from the host's authenticated transport, then resolves current facts. ExpiresAt-ServerTime is anchored before the original network request; receiving or refreshing metadata must never restart that interval.

type ResultRequest added in v0.131.0

type ResultRequest struct {
	Nonce         string `json:"nonce"`
	RequestSHA256 string `json:"requestSHA256"`
}

ResultRequest binds the exact request and a fresh unpredictable host/client nonce. The digest is SHA256 of the agreed canonical request bytes.

type Selector

type Selector struct {
	Kind  string `json:"kind"`
	Value string `json:"value"`
}

Selector, RecordScope, FieldScope and RequestBinding reserve the stored model's later-phase shape. MVP admission refuses their presence.

type StructuredIdentityFacts added in v0.135.0

type StructuredIdentityFacts struct {
	Connection ConnectionRef
	Resources  []StructuredResourceIdentity
}

type StructuredIdentityRequest added in v0.135.0

type StructuredIdentityRequest struct {
	Connection ConnectionRef
	Resources  []StructuredResourceIdentity
}

type StructuredRead added in v0.135.0

type StructuredRead struct {
	TugQL      string `json:"tugql"`
	Parameters string `json:"parameters"`
	MaxRows    uint32 `json:"maxRows"`
	MaxBytes   uint32 `json:"maxBytes"`
}

StructuredRead contains immutable serialized intent, never a caller query or authority. TugQL is the existing serialized YAML/JSON query syntax. Parameters is a strict JSON object of apicontract.TypedValueOrSet. Empty means no bindings. The output is bounded without changing the query's limit, offset or ordering. MaxRows and MaxBytes have the same bounds as TableRead.

func (StructuredRead) RequestFor added in v0.135.0

func (op StructuredRead) RequestFor(nonce string) (ResultRequest, error)

RequestFor binds full operation bytes and bounds to an independently selected fresh nonce. Server and consumer call this from their own original intent.

type StructuredReadSource added in v0.135.0

type StructuredReadSource interface {
	OpenStructuredRead(context.Context, StructuredIdentityRequest) (StructuredReadSpan, error)
}

StructuredReadSource is a trusted execution-only host port. Open follows Core candidacy. It must pin an independently identified native read-only span and a compiler profile that supports the actual operation; no permissions, grants, user policies or model-selected credentials enter it. Unsupported native profiles refuse. A TableReadSource never implies this broader profile.

type StructuredReadSpan added in v0.135.0

type StructuredReadSpan interface {
	Session() dal.ReadSession
	Verify(context.Context, StructuredIdentityRequest) (StructuredIdentityFacts, error)
	Close() error
}

StructuredReadSpan has the same cancellation, rollback, allocation and cleanup-reporting duties as TableReadSpan. Verify must independently attest ALL requested resources and byte-exact compiler/source routing for this span. It is SQL-free while rows are active; request facts are not evidence to echo.

type StructuredResourceIdentity added in v0.135.0

type StructuredResourceIdentity struct {
	Table access.TableName
	Path  string
}

StructuredResourceIdentity describes one source discovered by DALgo, never a permission. Table components are byte-exact; Path names a structural source. A database-qualified/federated source is not admitted by this single-span API.

type StructuredResultEnvelope added in v0.135.0

type StructuredResultEnvelope struct {
	Payload json.RawMessage       `json:"payload"`
	Lease   StructuredResultLease `json:"lease"`
}

func DecodeStructuredResultEnvelope added in v0.135.0

func DecodeStructuredResultEnvelope(data []byte) (StructuredResultEnvelope, error)

type StructuredResultLease added in v0.135.0

type StructuredResultLease struct {
	ResultLease
	Profile   string         `json:"profile"`
	Operation StructuredRead `json:"operation"`
	// ExecutedTugQL is the server-authenticated effective operation after
	// subordinate constraints. It is never imported as executable authority.
	// Its resources join authored resources for fresh retained-value checks.
	ExecutedTugQL   string `json:"executedTugql"`
	ExecutionSHA256 string `json:"executionSHA256"`
}

StructuredResultLease is version3 metadata for the complete immutable structured operation. It is not a capability; v1 and table-v2 refuse it.

type Subject

type Subject struct {
	Realm string      `json:"realm"`
	Kind  SubjectKind `json:"kind"`
	ID    string      `json:"id"`
}

Subject is assigned by the authenticated host, never by execution input.

func (Subject) Validate

func (s Subject) Validate() error

type SubjectKind

type SubjectKind string
const (
	User    SubjectKind = "user"
	Service SubjectKind = "service"
	Agent   SubjectKind = "agent"
)

type TableIdentityFacts added in v0.133.2

type TableIdentityFacts struct {
	Connection ConnectionRef
	Table      access.TableName
}

TableIdentityFacts identifies the source and native logical table that the exact written components execute. Components are values, never SQL syntax. This contract does not assert physical relation lineage across DDL changes.

type TableIdentityRequest added in v0.133.2

type TableIdentityRequest struct {
	Connection ConnectionRef
	Table      access.TableName
}

TableIdentityRequest contains the written identity of one frozen structured source. Connection is the independently authenticated Core source binding; neither field is evidence for the verifier to echo back.

type TableIdentityVerifier added in v0.133.2

type TableIdentityVerifier interface {
	VerifyTableIdentity(context.Context, dal.DB, TableIdentityRequest) (TableIdentityFacts, error)
}

TableIdentityVerifier is a trusted host fact port, not a permission evaluator. It must independently corroborate the actual supplied opened DB and establish immutable source routing and identifier/compiler semantics for its entire secured DB/reader lifetime (or pin an equivalent execution span). Sampling a mutable pool's catalog before/after I/O is insufficient. It must refuse when native folding, quoting, search paths, temporary aliases or routing prevent proof that the written components execute byte-exactly. The closed compiler must preserve source identity for every alias admitted by this profile. Lookup is read-only identity metadata work: no query payload, mutation or secret disclosure is permitted. It receives no grants. Core cannot detect a malicious trusted port lying about the supplied handle. No production opener is certified merely by implementing this interface.

type TableRead added in v0.134.0

type TableRead struct {
	Object   ObjectRef `json:"object"`
	MaxRows  uint32    `json:"maxRows"`
	MaxBytes uint32    `json:"maxBytes"`
}

TableRead is an immutable operation description, not SQL or authorization. MaxRows is 1..100; MaxBytes is 1..262144 and includes protected preview metadata.

type TableReadSource added in v0.134.0

type TableReadSource interface {
	OpenTableRead(context.Context, TableIdentityRequest) (TableReadSpan, error)
}

TableReadSource is a trusted host opener. It independently binds the exact source, table, compiler/options and native allocation limits before opening data rows. No grants or payload callback enter this port. An unproved native profile must refuse; implementing this interface does not certify an opener.

type TableReadSpan added in v0.134.0

type TableReadSpan interface {
	Session() dal.ReadSession
	Verify(context.Context, TableIdentityRequest) (TableIdentityFacts, error)
	Close() error
}

TableReadSpan pins one actual read-only native execution span. Session must remain bound to it; Verify is SQL-free immutable-proof/liveness validation, including while a cursor is active. No pooled sampling, lazy metadata SQL, mutable routing, compiler options, views or fallback are permitted. Close must cancel/invalidate and roll back safely during reads; never commit. The host owns redacted cleanup-error reporting, including after output was handed off.

type TableResultEnvelope added in v0.134.0

type TableResultEnvelope struct {
	Payload json.RawMessage  `json:"payload"`
	Lease   TableResultLease `json:"lease"`
}

func DecodeTableResultEnvelope added in v0.134.0

func DecodeTableResultEnvelope(data []byte) (TableResultEnvelope, error)

type TableResultLease added in v0.134.0

type TableResultLease struct {
	ResultLease
	Profile   string    `json:"profile"`
	Operation TableRead `json:"operation"`
}

TableResultLease is an additive version2 binding for an exact Core operation. It is metadata, not a capability. v1 result decoders/importers refuse it.

Jump to

Keyboard shortcuts

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