gitproxy

package
v0.0.0-...-da39455 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 58 Imported by: 1 module, 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 gitproxy is the only path from a sandbox to GitHub: docs/design.md's git proxy, ported from grain/proxy (Python) to sit alongside the rest of v2. The decision logic is unchanged in spirit -- match one of the four legal smart-HTTP paths, authenticate the caller by its per-sandbox bearer token, decide whether it may touch (owner, repo), select a credential, stream the request through, and audit the tuple -- but one piece moves: which repos a sandbox may touch is no longer a hand-edited allowlist file. It is read live from model's task store (Authorizer, in authorize.go), since a running task's Target and Reads already say exactly that, and a file an operator maintains by hand can only drift from it.

Which refs a push may update is checked here too, but only as far as the plain-text command list at the head of a push (refupdates.go): a sandbox may push its own task's branch and nothing else, to GitHub or to a repository served locally alike. The packfile after it is never parsed, for the reason docs/design.md gives -- a hand-rolled pack parser subtly wrong fails open -- and the command-list reader refuses anything it cannot read in full. What happens to the run's own branch -- force-pushes, deletion -- is the run's business; required reviews stay with GitHub rulesets and the merge queue.

Index

Constants

View Source
const (
	AmbientSourceGH   = "gh"
	AmbientSourceGit  = "git"
	AmbientSourceAuto = "auto"
)

The sources an ambient credential asks that core grain knows itself: gh, git credential fill, and auto's choice between them. Any other is one RegisterAmbientSource added.

View Source
const (
	DefaultMaxPushBodyBytes  int64 = 2 << 30  // 2 GiB, git-receive-pack
	DefaultMaxFetchBodyBytes int64 = 64 << 20 // 64 MiB, git-upload-pack and info/refs
)

The default request-body limits, per action. A push carries a packfile and can be large; anything else is a fetch negotiation (wants, haves, and the odd filter line), which stays small even for a deep history, or a GET with no body at all. Both are generous on purpose: the point is to bound what one request can make the controller hold, not to second-guess git.

View Source
const (
	// DefaultPackageRegistry is GitHub's package registry for
	// github.com. A deployment against GHES names its own instead.
	DefaultPackageRegistry = "ghcr.io"

	// PackageUsername is what the login sends beside the token. See the
	// note above: the token is the credential, and this is the name
	// GitHub itself uses when there is no user behind one.
	PackageUsername = "x-access-token"
)
View Source
const (
	AuthTypePAT       = "pat"
	AuthTypeSSH       = "ssh"
	AuthTypeApp       = "app"
	AuthTypeAnonymous = "none"
)

Auth types, as AuthType reports them and the UI's typed editor names them.

View Source
const AuthTypeAmbient = "ambient"

AuthTypeAmbient is AuthType's answer for an ambient credential.

View Source
const CredentialSecretPrefix = "github-credential-"

CredentialSecretPrefix is the store secret a credential named <name> is kept under: github-credential-<name>.

View Source
const CredentialsInFilesEnv = "GRAIN_GITHUB_CREDENTIALS"

CredentialsInFilesEnv, set to "files", keeps every CredentialSet in this process on the plaintext files -- the rollback switch. The daemon, started with it, writes every store-held credential back out to its file (RestoreFilesFromStore), which is what an older build reads.

View Source
const DefaultCLIWaitSlice = 540 * time.Second

DefaultCLIWaitSlice is the longest one /cli/ci/wait or /cli/ci/run-job request blocks: nine minutes, so the answer is back before the 600s ceiling run_command puts on the command that asked.

View Source
const DefaultMaxNamespaceConcurrentRequests = 8

DefaultMaxNamespaceConcurrentRequests is the default per-sandbox concurrency limit on /fs/ requests to protect the daemon from runaway shell loops.

View Source
const DefaultReachTTL = 2 * time.Minute

DefaultReachTTL is how long Reach keeps a credential's list. Short, because the list is exactly what an operator changes when they grant the credential a repository and then try again; a changed token refreshes it at once anyway (Reach.Repos keys on the token).

View Source
const (
	// DefaultSandboxTokenTTL is how long a minted sandbox token is valid for.
	DefaultSandboxTokenTTL = 24 * time.Hour
)
View Source
const DefaultSpoolThreshold int64 = 16 << 20 // 16 MiB

DefaultSpoolThreshold is the most of a push request body held in memory before spilling to a temporary file on disk. Bodies at or under this threshold stay in memory as a byte slice.

View Source
const ForbiddenReason = "grain's own state repository holds (or once held) its encrypted secrets file, " +
	"so no sandbox may fetch or push it: everything a sandbox can clone is everything it can read. " +
	"A state repository that has never held that file can be dispatched against normally"

ForbiddenReason is the message a request for a Forbidden repo is refused with. It is returned to the caller, so it says what to do rather than only that the answer is no: an agent whose task really does target that repository would otherwise read a bare denial as grain being broken.

View Source
const HostGitEntry = "host-git"

HostGitEntry is the in-tree capability server that runs ambient sources' tools on the host (`grain capability host-git`), and the name of the capability entry in grain hostd's allowlist that starts it.

View Source
const LoginLapsedMarker = "grain: host login lapsed: "

LoginLapsedMarker begins every refusal this proxy gives because a login the grain host itself holds has lapsed -- a forge front end answering with its login page (LoginRedirectError), or an ambient credential's token refused while the tool it came from cannot vouch for its login either (unauthorizedReason). What fixes those is a person renewing that login on the host, so the dispatcher parks the task on it rather than retrying it (orchestrator's hostLoginLapsedError); the marker is what lets it tell, without reading any source's own wording (authfix.Fix), once the refusal has crossed into a sandbox's git as "remote: " lines.

View Source
const MaxCLIProposalsPerAttempt = 10

MaxCLIProposalsPerAttempt caps how many unapproved proposals one sandbox attempt may file through POST /cli/proposals.

View Source
const MaxGitSignPayloadBytes = 1 << 20

MaxGitSignPayloadBytes bounds the commit or tag buffer that may be signed via SignGitPayload or /_grain/git-sign (1 MiB).

View Source
const MigratedSuffix = ".migrated"

MigratedSuffix is appended to a credential file once its contents are in the store. The copy is deleted on the daemon's next start, once the store is seen to hold the value (DeleteMigratedCopies, RetireMigratedCopy).

View Source
const TaskListNoteHeader = "Grain-Task-List-Note"

TaskListNoteHeader carries /cli/tasks' count and elision ("12 task(s) shown of 40 matching ...") out of band, so that the body is the task lines and nothing else: `grain task list | wc -l` counts tasks, and the CLI prints the note on stderr.

Variables

View Source
var CIProtectedBranches = map[string]bool{
	"refs/heads/main": true,
}

CIProtectedBranches are the branches a CI job may neither update nor delete.

View Source
var ErrForgeBodyCut = errors.New("the forge tool stopped before the body ended")

ErrForgeBodyCut is what a forge answer read through a command-line tool is, by errors.Is, when the tool printed a success and its headers and then failed or was stopped before the body ended -- directly or through the host's host-git server. The body read so far is not the whole answer.

View Source
var ErrNoCredential = errors.New("no credential named")

ErrNoCredential is what SetHost, Remove and the reach check wrap when the credential they are given does not exist, so a caller can tell a name nobody configured (the request's fault) from a failure to write.

View Source
var ErrNoSandboxToken = errors.New("gitproxy: no token recorded for this sandbox")

ErrNoSandboxToken is what RefreshToken reports for a sandbox holding no token: never minted one, or already revoked.

View Source
var ErrNoStoreValue = errors.New("the secrets store does not hold this value")

ErrNoStoreValue is RetireMigratedCopy's answer for a rollback copy whose secret the store does not hold: the copy is the only one there is, so it is kept.

Functions

func AmbientAccount

func AmbientAccount() string

ambientAccount is "<user> on <hostname>", for the sentence that says where to log in. AmbientAccount is the account host tools run as, and the host, as a refusal names them ("alice on build-1"): who to run a fix as.

func AmbientAutoSource

func AmbientAutoSource(host string) string

AmbientAutoSource is the source auto asks first for host: what the connection editor shows and the installer writes down.

func AmbientAvailable

func AmbientAvailable() error

AmbientAvailable is nil when this process may use the host's own login: the daemon runs on the bare machine, not inside a container. Which of the two it is comes from pkg/whererun, which calls a daemon containerised only on evidence of a container. Every machine install runs the daemon in the release container (host mode was removed, task 5041), so in practice this is a development daemon's: `grain demo`, or a local `grain daemon` -- or a daemon in the release container beside grain hostd, when hostd's allowlist offers the host-git capability server (UseHostGit, hostgit.go): the host's gh (or a registered source's tool) then runs on the host, through that server.

func AmbientCommandOf

func AmbientCommandOf(host, source string) string

AmbientCommandOf is the tool source asks for host's login ("gh", or a registered source's), or "git credential fill".

func AmbientForgeTransport

func AmbientForgeTransport(h CredentialHost, source string) (github.Transport, bool)

AmbientForgeTransport is the github.Transport for h's REST API through source's tool, for a login that is not saved yet -- the connection editor's Test on an ambient connection it has not saved: ok is false unless source (or the registered source claiming h.Host, when source is empty) is a ForgeViaCommand one, which a saved credential's ForgeTransport would send through `<tool> api` too.

func AmbientForgeViaCommand

func AmbientForgeViaCommand(host, source string) bool

AmbientForgeViaCommand reports whether source's login on host comes from a tool that carries the host's traffic itself (ForgeViaCommand): grain's forge calls to it go through that tool, and its host record needs no proxy.

func AmbientHostHTTPClient

func AmbientHostHTTPClient(h CredentialHost, source string, timeout time.Duration) (*http.Client, bool)

AmbientHostHTTPClient returns an http.Client running `<tool> api` for h when source (or the registered source claiming h.Host when source is empty) sends forge traffic through its CLI tool.

func AmbientLogin

func AmbientLogin(host, baseURL, source string) (token, user string, err error)

AmbientLogin is AmbientToken for a host reached on baseURL (a host record's BaseURL), with the username `git credential fill` answered with beside the token when git is the source that answered: the whole login a plain git host behind basic auth checks.

func AmbientLoginFix

func AmbientLoginFix(host, source string) string

AmbientLoginFix is the command that logs this host's account in to host for source: what a refusal tells the operator to run. For auto it is the command of the source auto asks first.

func AmbientScopeFix

func AmbientScopeFix(host, source string) string

AmbientScopeFix is the command that gives source's login on host the scopes grain needs: `repo`, and `workflow` where the source's own fix asks for it.

func AmbientSourceNames

func AmbientSourceNames() []string

AmbientSourceNames is every source an ambient file may name.

func AmbientToken

func AmbientToken(host, source string) (token, from string, err error)

AmbientToken asks this host's own tools for a token for host: gh, git, or gh then git (AmbientSourceAuto). The error is the sentence to fix it by, naming the account and the host to run the fix as and on.

func CIRefUpdates

func CIRefUpdates(check *pushCheck, owner, repo string, updates []RefUpdate) string

CIRefUpdates returns why a CI job with write access to owner/repo may not make updates, or "" when it may make all of them.

func CapRunKey

func CapRunKey(runID string) string

CapRunKey is the key an agent run's servers are registered under.

func CapSandboxKey

func CapSandboxKey(sandbox string) string

CapSandboxKey is the key a CI job's servers are registered under: its sandbox has no task run to be resolved through.

func CredentialSecretName

func CredentialSecretName(name string) string

CredentialSecretName is the store secret that holds credential name.

func DownloadToFile

func DownloadToFile(client *http.Client, req *http.Request, dest string, timeout time.Duration) (sha256Hex string, written int64, status int, errBody string, err error)

DownloadToFile streams a GET request's 200 response body into dest, an empty placeholder the caller has already created (openStagingPlaceholder: basename prefix "grain-release-asset-", regular, empty, its own), computing its SHA-256 on the fly without holding the body in memory. When client uses CommandForgeTransport beside grain hostd, the host's host-git server streams directly into dest on the shared filesystem, bypassing hostGitMaxBody. dest is left in place, possibly partly written, when it fails: removing it is the caller's.

func ExtractBasicAuthToken

func ExtractBasicAuthToken(header string) (string, bool)

ExtractBasicAuthToken pulls the token out of an "Authorization: Basic base64(user:token)" header. The username is ignored -- a credential helper is configured with an arbitrary username and the token as the password, so the token is what identifies the caller.

func GitHubKnownHosts

func GitHubKnownHosts() string

GitHubKnownHosts is githubKnownHosts, for a UI offering it as the default.

func GitOnlyReason

func GitOnlyReason(cred Credential, owner, repo string) string

GitOnlyReason is the sentence a pull request, check or merge on owner/repo is refused with when cred is an SSH key with no API credential paired to it, or "" when REST calls can go ahead.

func IsAccessRefusal

func IsAccessRefusal(output string) bool

IsAccessRefusal reports whether output -- what a sandbox's git printed, "remote: " lines and all -- carries one of this proxy's refusals for a repository the credential cannot reach. It is what lets the dispatcher stop a task whose clone was refused this way at the first attempt rather than retrying it to the failure limit: nothing about another attempt changes what the team's credential was granted (orchestrator.stopOnAccessRefused, grain/task-1850).

func IsValidGitRequest

func IsValidGitRequest(userAgent, accept, action string) bool

IsValidGitRequest is a tight allowlist of the client shapes a real git client produces -- mirrors what FINOS Git Proxy's validGitRequest() checks (docs/design.md says it's worth stealing): a git/ user agent, and, for the pack endpoints, an Accept header naming the matching x-git-* result type. Rejecting anything else means a browser poking at these paths gets a plain 404 rather than a confusing partial response.

func LoginLapsed

func LoginLapsed(output string) (string, bool)

LoginLapsed reports whether output -- what a sandbox's git printed -- carries one of this proxy's lapsed-login refusals, and if so the first one's sentence, with git's "remote: " and the marker cut off.

func NewHandler

func NewHandler(proxy *GitProxy) http.Handler

NewHandler wraps proxy as an http.Handler: split the path and query, hand the body over unread (GitProxy.HandleRequest reads it, bounded, only once the request is allowed), run the decision logic, and stream the response back with WriteResponse.

func NoTeamCredentialMessage

func NoTeamCredentialMessage(team, repo string) string

NoTeamCredentialMessage is what a CI job that declared access to repo is told when team has no GitHub credential to give it: the team, the repository, and where the team sets one.

team is always the default team now, whose row holds the deployment's git connections (docs/single-tenant-reset.md, stage 1).

func NormalizeAmbientSource

func NormalizeAmbientSource(source string) (string, error)

NormalizeAmbientSource is source as stored: "" is AmbientSourceAuto.

func NormalizeHostProxy

func NormalizeHostProxy(raw string) (string, error)

NormalizeHostProxy checks a host record's proxy: empty, or an http(s)://host:port URL with nothing else in it. A login in it is refused rather than stored, because the host record is not a secret (it is exported, shown and logged like any setting).

func ParseAppPrivateKey

func ParseAppPrivateKey(pemBytes []byte) (*rsa.PrivateKey, error)

ParseAppPrivateKey parses the PEM-encoded RSA private key GitHub generates when an App's private key is created. GitHub's own download is PKCS#1 ("RSA PRIVATE KEY"); PKCS#8 ("PRIVATE KEY") is accepted too, since a key manager an operator routes the download through may re-encode it.

func ParseKnownHostsFor

func ParseKnownHostsFor(knownHosts, addr string) ([]ssh.PublicKey, error)

ParseKnownHostsFor is the pinned keys in knownHosts for addr (host:port): every entry whose host patterns name it, in the form known_hosts writes ("host" on port 22, "[host]:port" otherwise). A hashed or wildcard entry is refused rather than skipped, so a known_hosts that pins nothing usable says so instead of reading as empty.

func PushRefusedHint

func PushRefusedHint(credential Credential, message string) string

PushRefusedHint is what credential's ambient source adds to a push its host rejected with message, or "" when it has nothing to say: the credential is not ambient, its source has no PushRefusedHint, or the hint does not recognise message.

func PushShowsFastForward

func PushShowsFastForward(body io.Reader, newTip, oldTip string) (bool, error)

PushShowsFastForward reads a git-receive-pack request body from its start and reports whether the commits its packfile carries show newTip descending from oldTip: the proof of a fast-forward that needs nothing from the remote, which an ordinary push always carries, since its pack holds every commit from the new tip back to the remote's. A push whose pack does not reach oldTip -- a forced update, or one with no pack at all because the remote already has newTip -- is not shown to be one. Without GitProxy's fallback to the remote's own history this is stricter than refuseRefUpdates, and refuses some pushes that are in fact fast-forwards; it never admits one that is not.

func ReachParkComment

func ReachParkComment(refusal string) string

ReachParkComment is what a task filed by automation is parked on when its team cannot reach a repository it names: the refusal a person filing it would have been given, and what a reply does.

func ReadOnlyPushReason

func ReadOnlyPushReason(owner, repo string) string

ReadOnlyPushReason is the refusal for a push to a repository the sandbox may fetch but not push to -- a CI job's read scope on the repo under test, or a task's Reads entry. HandleRequest gives it at the receive-pack advertisement, where git prints it as "remote: ...".

func RegisterAmbientHomeDir

func RegisterAmbientHomeDir(dir string) (unregister func())

RegisterAmbientHomeDir adds dir as a parent directory of per-user local-disk homes (<dir>/<username>) that ambientHome prefers over the passwd entry's HomeDir when <dir>/<username> is a directory owned by the daemon's own uid -- for workstations whose NSS/LDAP passwd entry names an autofs home that hangs on non-interactive access. It returns a function that removes the registration (for tests).

func RegisterAmbientSource

func RegisterAmbientSource(src AmbientCommandSource) (unregister func())

RegisterAmbientSource adds src to the sources an ambient credential may name, ahead of the built-in ones in auto's order, and returns what takes it away again (for a test). It panics on a name already taken, or one of git and auto: a registration is made once, from init().

func RegisterPackageCredentialSource

func RegisterPackageCredentialSource(hosts []string, src PackageCredentialSource) (unregister func())

RegisterPackageCredentialSource registers src as the container-registry credential source for repositories on hosts (exact hostnames or "*.domain" patterns). An AmbientCommandSource may also set its own PackageCredential field directly. It returns a function that removes the registration.

func RemoteBranchExists

func RemoteBranchExists(h CredentialHost, credential Credential, owner, repo, branch string) (bool, error)

RemoteBranchExists is `git ls-remote --heads` for one branch of owner/repo on h, asked with credential through the same transport the git proxy forwards that credential's requests with. It is how grain reads a branch on a host with no forge API to ask (a plain git host): a GET of info/refs, the first half of any clone.

A repository the remote will not show -- not there, or not readable with credential -- is an error rather than false: "no such branch" is only what an advertisement that lacks it says.

func RemoteBranches

func RemoteBranches(h CredentialHost, credential Credential, owner, repo string) ([]string, error)

RemoteBranches is `git ls-remote --heads` for owner/repo on h: every branch the remote advertises, sorted. It is the branch pickers' listing for a repository on a plain git host, where GitHub's /repos/{owner}/{repo}/branches would ask about some other repository altogether. Errors as RemoteBranchExists's do.

func RemoteRefSHA

func RemoteRefSHA(h CredentialHost, credential Credential, owner, repo, ref string) (string, error)

RemoteRefSHA resolves ref ("" / "HEAD", a branch name, a tag name, or an advertised commit SHA) in owner/repo on h using its smart-HTTP upload-pack ref advertisement. It returns ("", nil) when the repository is reachable but does not advertise ref.

func RetireMigratedCopy

func RetireMigratedCopy(copyPath, ref string, stored func() ([]byte, bool, error), same func(copy, stored []byte) bool) (bool, error)

RetireMigratedCopy deletes copyPath, a <file>.migrated rollback copy a move into the secrets store left behind, once the store verifiably holds the value it stands for. The design kept these copies for one release (secrets-key-protection §6); a rollback no longer needs them, since GRAIN_GITHUB_CREDENTIALS=files writes every file back from the store's own value.

stored reads the value from the store, ok false when it holds none. It must read the store itself, not a cache, since that read is the verification. same compares the copy's bytes with it (bytes.Equal when nil); a copy whose value the store holds but differently -- the credential was changed after the move -- is superseded and deleted too, since a rollback restores the store's value, never the copy's.

A copy is kept, with an error, when the store cannot be read (stored's error) or holds no value (ErrNoStoreValue). Each deletion, and each copy kept, is logged here; a missing copy does nothing. ref names the store value in the logs ("secret/key").

func RetiredConfigRepo

func RetiredConfigRepo(host, owner, name string) bool

RetiredConfigRepo reports whether (owner, name) on the default host is shaped like one of the per-team configuration repositories (grain/config-<team>, grain/config-default) a multi-team grain served beside grain/config. No forge holds them and this controller keeps none of them, so the proxy answers them not found -- to every sandbox, whatever its scope says -- rather than forwarding a request for the virtual grain/ owner to a forge with this deployment's credential.

func RetiredConfigRepoReason

func RetiredConfigRepoReason(owner, name string) string

RetiredConfigRepoReason is what a request for a RetiredConfigRepo is told.

func ServeHostGit

func ServeHostGit(s *protocol.CapabilityServer) error

ServeHostGit adds host-git's tools to s: the server side, run on the host by `grain capability host-git`. Each tool answers a failure of the command it ran as {"error": "..."} -- the sentence the same failure is on a daemon on the host -- and keeps tool errors for requests it refuses.

func SmartHTTPAdvertises

func SmartHTTPAdvertises(h CredentialHost, credential Credential, owner, repo, service string) (bool, string)

SmartHTTPAdvertises is whether owner/repo on h answers credential's smart-HTTP ref advertisement for service ("git-upload-pack" for read, "git-receive-pack" for push), asked through the same transport the git proxy forwards that credential's requests with. It is how a credential on a plain git host is tested, that host having no API to ask: a host that refuses the credential, or only lets it read, answers the receive-pack advertisement with a 401 or 403. When it does not, the string says why.

func TeamCredentialRefusedNote

func TeamCredentialRefusedNote(team, repo string) string

TeamCredentialRefusedNote is appended to GitHub's own refusal of a request a CI job made as team: the credential that was refused is the team's, so the team's settings are where its access is changed.

func UseHostGit

func UseHostGit(c *HostGitClient) (restore func())

UseHostGit makes every ambient source's tool run on the host through c, for a daemon in the release container beside grain hostd; nil goes back to running them as this process's own children. It returns what puts the previous one back (for a test).

func ValidCredentialName

func ValidCredentialName(name string) error

ValidCredentialName reports whether name may be used for a credential written through SetToken: it becomes a filename in the secrets directory, and it becomes half of a capability id (model.GitCredentialCapability), so it is held to a conservative shape rather than to whatever the filesystem happens to tolerate. A name already on disk that does not match this is still read as it always was -- this gates writing, not loading.

"anonymous" is refused because load reads it as a credential shape of its own (no Authorization header at all); a file of that name would be written, listed, and then never used.

func ValidateForwardTarget

func ValidateForwardTarget(host string, useTLS bool) error

ValidateForwardTarget is whether host may be forwarded to at all, over TLS or not. A custom git host (GitHub Enterprise, a mock) is a supported configuration, so this does not insist on github.com; what it insists on is that the request -- and the credential riding on it -- goes to the host that was configured, and is not readable on the way there:

  • host must be a bare hostname or IP, with an optional port: no scheme, userinfo, path, query or fragment. Forward builds its URL from this string, and "github.com@evil.example" or "evil.example/github.com" would otherwise send the request, Basic auth and all, somewhere other than where it reads as going.
  • plain HTTP is allowed only to a loopback address (the mock-GitHub test seam, -github-insecure-http). Anywhere else a token sent in the clear is a token handed to anyone on the path.

func WorkflowScopeRefused

func WorkflowScopeRefused(message string) bool

WorkflowScopeRefused reports whether message is a GitHub host refusing a push that creates or updates a file under .github/workflows because the OAuth token it came with has no `workflow` scope:

refusing to allow an OAuth App to create or update workflow
`.github/workflows/ci.yml` without `workflow` scope

A GitHub App's refusal ("without `workflows` permission") is not one: no scope fixes that, only the App's own permissions.

func WriteResponse

func WriteResponse(w http.ResponseWriter, resp ProxyResponse)

WriteResponse writes resp to w: its headers, less the hop-by-hop ones and Content-Length (which a decision about an upstream response could get wrong for this transport's own), then its body. A Stream is copied through as it is read and flushed after every read, so a large packfile is never held whole and git's progress messages reach the sandbox when they are sent; it is closed once copied. A Stream that fails part way aborts the response rather than ending it cleanly, so the client sees a truncated transfer as one instead of as a complete response that happens to be short.

Types

type AmbientCommandSource

type AmbientCommandSource struct {
	// Name is the source as an ambient file stores it.
	Name string
	// Command is the executable, looked up on PATH; Args follow it.
	Command string
	Args    []string
	// Env is added to the daemon's own environment for the run.
	Env []string
	// LoginFix is the command that logs the daemon's account in.
	LoginFix string
	// Hosts are the host patterns this source is auto's answer for: an
	// exact host, or "*.domain" for any host under domain. A host none
	// of the sources names gets gh, then git.
	Hosts []string
	// OnlyHosts makes Hosts the only hosts the source may be asked for,
	// even by name -- a tool for one forge is never asked for a
	// github.com login.
	OnlyHosts bool
	// ScopeFix is the command that adds the scopes grain needs to the
	// login: `repo`, and `workflow` for a push that touches
	// .github/workflows.
	ScopeFix string
	// PushRefusedHint, when set, is asked about a push the source's host
	// rejected a ref of: message is the host's own words (the reasons on
	// its "ng" report lines and the "remote:" text beside them), and what
	// it answers is added to what the pusher sees, as more "remote:"
	// lines (or on the ng line, to a client without side-band): what to
	// run to fix a refusal the host's text names but does not explain,
	// such as a login without the `workflow` scope. Empty says nothing
	// more; so does nil (pushhint.go).
	PushRefusedHint func(host, message string) string
	// ForgeViaCommand, when set, marks a tool that is the only way to the
	// hosts it is for: they sit behind a front end that answers any
	// client without the workstation's own login with a redirect to a
	// login page, and the tool applies that login and transport itself.
	// grain then opens no connection of its own to such a host for a
	// credential from this source: its forge API calls and the git
	// proxy's upstream hop are each one `<Command> api` run on this host
	// (CommandForgeTransport, commandforge.go). A proxy in the host record
	// is optional, and honoured when an operator sets one.
	ForgeViaCommand *CommandForge
	// PackageCredential, when set, mints the container-registry login
	// (CredentialSet.PackageCredential) for repositories on this source's
	// hosts via a host tool instead of sending the git token to ghcr.io.
	PackageCredential *PackageCredentialSource
	// UI is how the connection editor offers the source. Nil offers it in
	// the Source menu by its command alone.
	UI *AmbientSourceUI
}

AmbientCommandSource is one host tool that prints a token for a host: the command, the environment it needs, and the command that fixes a missing login -- data, so another wrapper around gh is one more RegisterAmbientSource rather than more code. "{host}" anywhere in Args, Env, LoginFix or ScopeFix is the host name the token is for.

func RegisteredAmbientSources

func RegisteredAmbientSources() []AmbientCommandSource

RegisteredAmbientSources is every source RegisterAmbientSource added, in auto's order: what the connection editor offers beside gh and git.

type AmbientCredential

type AmbientCredential struct {
	Host   string
	Source string
	// From is the source that actually answered: "gh" or "git", which
	// for AmbientSourceAuto is whichever came first.
	From string
	// User is the username `git credential fill` answered with beside
	// the password, when that is the source that answered. It is who a
	// credential on a plain git host acts as: such a host has no /user
	// to ask (AmbientIdentityOf).
	User string
}

AmbientCredential is set on a Credential loaded from an ambient file: where its token came from, so a refusal can say what to fix and a 401 can drop it (Refused).

type AmbientFile

type AmbientFile struct {
	Host   string `json:"host"`
	Source string `json:"source"`
}

AmbientFile is <name>.ambient.json: a host and a source, and nothing that is a secret.

type AmbientIdentity

type AmbientIdentity struct {
	Login  string
	Scopes []string
	// NoRepoScope is set for a classic OAuth token without `repo`, which
	// can read public repositories and push nothing.
	NoRepoScope bool
	// NoWorkflowScope is set for a classic OAuth token without
	// `workflow`, whose host refuses a push that creates or changes a
	// file under .github/workflows. A warning rather than a fault: work
	// that never edits a workflow does not need the scope.
	NoWorkflowScope bool
	// ID and Name are the account's numeric id and display name, as
	// /user reports them: what NoreplyEmail and AmbientGitIdentity
	// (ambient_identity.go) build a commit identity for the login out
	// of. Zero and empty on a plain git host, which has no /user.
	ID   int64
	Name string
}

AmbientIdentity is who an ambient credential's token acts as, and whether it carries the `repo` and `workflow` scopes: GitHub's own /user lookup with the token load would send, so it is the answer for exactly the login a push would use. scopes is nil for a token GitHub reports none for (a fine-grained or App user token).

func (AmbientIdentity) NoreplyEmail

func (id AmbientIdentity) NoreplyEmail(host string) string

NoreplyEmail is the address GitHub itself attributes to this login's commits when the account keeps its address private -- <id>+<login>@users.noreply.<host> -- and so one GitHub matches to the account exactly as it does a verified address (and a CLA or DCO check that looks the author up finds the person, not nobody). Empty for an identity /user did not answer for.

type AmbientSourcePreset

type AmbientSourcePreset struct {
	Host  string
	Label string
}

AmbientSourcePreset is one host an AmbientSourceUI offers.

type AmbientSourceUI

type AmbientSourceUI struct {
	// Label is the source's entry in the Source menu.
	Label string
	// Help is said under the form when one of Presets is chosen: where
	// the token comes from, how to check the login and what to run when
	// it lapses.
	Help string
	// Presets are hosts the editor offers to fill a new connection in
	// for: the host, a GitHub kind and this source.
	Presets []AmbientSourcePreset
}

AmbientSourceUI is what the connection editor says about a registered source: its own label in the Source menu, the hosts it fills the form in for, and what to tell the operator once one of them is chosen. "{host}" anywhere in Help is the host; text between backticks is shown as code.

type AnyRefLookup

type AnyRefLookup interface {
	GitPushAnyRef(ctx context.Context, sandbox string) (bool, error)
}

AnyRefLookup is the optional half of BranchLookup that answers whether a sandbox's live run holds model.GitPushAnyRefGrant (or the retired bare git-push-any-ref it replaced), the team grant that lifts the one-branch rule. model.Store implements it; a lookup that does not is read as nobody holding it.

type AppCredential

type AppCredential struct {
	AppID          string
	InstallationID string
	PrivateKey     *rsa.PrivateKey
	WebhookSecret  string
}

AppCredential is one GitHub App installation (or multi-installation App when InstallationID is empty) this deployment can mint installation tokens for. AppID and InstallationID are kept as strings, as GitHub itself prints them and as the JSON below carries them, because neither is ever arithmetic.

type AuditEntry

type AuditEntry struct {
	Time    time.Time
	Sandbox string
	// Host is the git host the request was for, empty for the default.
	Host       string
	Owner      string
	Repo       string
	Action     string
	Credential string // empty when no credential was selected
	Outcome    string
	// Ref, Task, Template and Declaration are set on the entry recorded
	// for each update of a ref other than a run's own branch that was let
	// through (RefGrant): the ref, the task whose run pushed it, and the
	// template and declaration file whose `push:` allowed it.
	Ref         string
	Task        string
	Template    string
	Declaration string
}

AuditEntry is one decision the proxy made.

type AuditLog

type AuditLog interface {
	Record(entry AuditEntry)
}

AuditLog records one AuditEntry per request.

type Authorizer

type Authorizer interface {
	Authorize(ctx context.Context, sandbox, owner, repo, action string) (bool, error)
}

Authorizer decides whether a sandbox may perform action against owner/repo through the proxy. For a repository on a git host other than the default, owner is host/owner (GitRequest.ScopeOwner, the form model.RepoRef.StoredOwner writes), so an implementation that compares owners as strings keeps one host's repositories apart from another's without knowing about hosts at all.

type BranchLookup

type BranchLookup interface {
	GitPushBranch(ctx context.Context, sandbox string) (branch string, live bool, err error)
}

BranchLookup resolves a sandbox to the one branch its live run may push. model.Store implements this via GitPushBranch; a test supplies a stub instead. live false means no live run, and so no branch.

type BuildConfig

type BuildConfig struct {
	// DataDir holds secrets/github/{credentials.json,*.token} and
	// secrets/sandbox-tokens.json, and receives state/git-proxy/audit.log.
	DataDir string
	// Store answers GitScope for the sandbox a request authenticates as.
	Store *model.Store
	// ForwardHost overrides the real github.com forward target -- the
	// git-transport half of a mock-GitHub live-test seam. Empty means
	// "github.com over TLS". Any host is accepted, but only as a bare
	// host[:port], and plain HTTP (ForwardTLS false) only to loopback --
	// see ValidateForwardTarget.
	ForwardHost string
	ForwardTLS  bool
	// Forbidden is ModelAuthorizer.Forbidden: the live set of repos no
	// sandbox may reach through this proxy at all. Nil for a deployment
	// with none and no way of acquiring any; a caller that can change
	// which repository grain's state lives in passes a set it keeps a
	// handle on instead, and replaces its contents when that changes
	// (cmd/grain's stateManager).
	Forbidden *ForbiddenSet
	// ReadScopes is the registry of sandboxes that may fetch one
	// repository without a task behind them -- grain CI's job sandboxes,
	// and nothing else today (see readscope.go). Nil for a deployment
	// running no CI, which grants nothing this way and leaves every
	// request answered by the model exactly as it was before.
	ReadScopes *ReadScopes
	// WriteScopes is the registry of sandboxes that may push to (and fetch
	// from) repositories in CI. Nil for a deployment running no CI.
	WriteScopes *WriteScopes
	// SandboxTeams is GitProxy.SandboxTeams: the CI sandboxes whose
	// requests go out with their team's credential. Nil for a deployment
	// running no CI.
	SandboxTeams *SandboxTeams
	// Local is the controller-owned repository exposed through its stable
	// alias instead of forwarded to the external git host.
	Local *LocalRepository
	// MaxPushBodyBytes and MaxFetchBodyBytes are GitProxy's request-body
	// limits; zero leaves each at its default.
	MaxPushBodyBytes  int64
	MaxFetchBodyBytes int64
	// SingleTenant is GitProxy.SingleTenant: always true from the daemon.
	SingleTenant bool
	// Namespace serves /fs/<scheme>/<path> when set.
	Namespace       *namespace.Server
	NamespaceScopes NamespaceScopeLookup
	// CLI is GitProxy.CLI.
	CLI CLIBackend
	// CLIActions and WaitCredit are GitProxy's own: what the acting /cli/
	// routes act through, and what credits their waits.
	CLIActions CLIActions
	WaitCredit CLIWaitCreditor
	// ReportChecker is GitProxy.ReportChecker.
	ReportChecker CLIReportChecker
	API           http.Handler
	// CapServers is GitProxy.CapServers.
	CapServers      *CapRegistry
	ShutdownStarted <-chan struct{}
}

BuildConfig is what BuildProxy needs to wire the real files under a /data-shaped directory (docs/design.md, "secrets on /data") to the live model store that now answers what a hand-edited allowlist file used to.

type CIStartRequest

type CIStartRequest struct {
	Jobs       []string
	Workflow   string
	Commit     string
	Recheck    bool
	FailedOnly bool
}

CIStartRequest is what a /cli/ci/ action asks grain CI to run on the task's own branch: ui.TaskCIRunOptions in this package's terms.

type CLIAPIRoute

type CLIAPIRoute struct {
	Method      string `json:"method"`
	Path        string `json:"path"`
	Scope       string `json:"scope"`
	Tool        string `json:"tool"`
	Description string `json:"description"`
	NeedsReason bool   `json:"needs_reason,omitempty"`
}

CLIAPIRoute is one route returned by GET /cli/api-routes.

type CLIActionResult

type CLIActionResult struct {
	Text    string
	Refused bool
}

CLIActionResult is a PR action's answer: the sentence the MCP tool it replaces would have said, and whether that sentence is a refusal.

type CLIActions

type CLIActions interface {
	// StartTaskCI starts grain CI on taskID's own branch, or attaches to
	// the identical run already in flight.
	StartTaskCI(ctx context.Context, taskID string, req CIStartRequest) (ci.Run, error)
	// CIRun reads one run by id. Its false is "not remembered" -- unless
	// the actions are a ci.Readiness saying CI is not up yet, when it is
	// that instead (served as 503, not 404).
	CIRun(ctx context.Context, id string) (ci.Run, bool)
	// OpenPullRequest opens (or finds) the pull request for taskID's
	// branch and reports it.
	OpenPullRequest(ctx context.Context, taskID string) (CLIActionResult, error)
	// ReplyToPullRequestComment posts body on taskID's own open pull
	// request: in commentID's thread, or top-level when commentID is 0.
	ReplyToPullRequestComment(ctx context.Context, taskID string, commentID int, body string) (CLIActionResult, error)
	// ResolveReviewThread resolves a thread on taskID's own open pull
	// request, named by threadID or by a commentID in it.
	ResolveReviewThread(ctx context.Context, taskID, threadID string, commentID int) (CLIActionResult, error)
	// RevertInfo describes target for a revert asked for by taskID's run.
	RevertInfo(ctx context.Context, taskID, target string, anyTask bool) (RevertInfo, error)
}

CLIActions is the daemon behind the acting /cli/ routes. Every method takes the task the authenticated sandbox belongs to and resolves its repository, branch and pull request from that task's own record. Implemented by pkg/ui's SandboxCLIActions.

type CLIBackend

type CLIBackend interface {
	IssueTools(ctx context.Context, scope namespace.Scope) []mcp.Tool
	// DBQueryTool is query_grain_db, read-only whatever else the run
	// holds: the proxy serves reads, and db-write's execute_grain_db
	// stays a tool.
	DBQueryTool(ctx context.Context, scope namespace.Scope) mcp.Tool
}

CLIBackend builds, for one run, the MCP tools the /cli/ reads below stand in for, so that each answers with the very text its tool would: list_issues and read_issue (pkg/mcp's issue_tools.go) for /cli/issues, and query_grain_db (pkg/capability/dbaccess) for /cli/db/query. The grant is checked here, before the backend is asked; the backend decides what the run reads with (its git credential, its task id).

type CLIDroppedDefault

type CLIDroppedDefault struct {
	Grant  string `json:"grant"`
	Reason string `json:"reason"`
}

CLIDroppedDefault is one default grant the capability policy kept off a proposal, and why.

type CLIGitHubCheckActions

type CLIGitHubCheckActions interface {
	UsesGitHubChecks(ctx context.Context, taskID string) (bool, error)
	WaitForGitHubChecks(ctx context.Context, taskID string, timeout, poll time.Duration, onPoll func(waited time.Duration)) (mcp.GitHubCheckWaitResult, error)
}

CLIGitHubCheckActions is an optional extension of CLIActions for tasks whose repository gates on GitHub check runs (ci_mode: "github") rather than Grain CI. When UsesGitHubChecks reports true for a task, /cli/ci/wait polls GitHub check runs via WaitForGitHubChecks instead of starting a Grain CI run via StartTaskCI.

type CLIGitHubRerunActions

type CLIGitHubRerunActions interface {
	RerunGitHubChecks(ctx context.Context, taskID string, req CIStartRequest) (CLIActionResult, error)
}

CLIGitHubRerunActions is an optional extension of CLIActions: grain ci retrigger and run-job on a task whose repository gates on GitHub Actions (UsesGitHubChecks), where there is no grain CI run to start. RerunGitHubChecks re-runs req -- its Jobs, or with none its failed jobs (FailedOnly) or every job -- of the Actions runs at the head of the task's own pull request, through the daemon's forge connection, bound per head; it names no repository, branch or run, so a run re-runs its own pull request's checks and nobody else's. Implemented by pkg/ui's SandboxCLIActions.

type CLIJobVerdict

type CLIJobVerdict struct {
	Name       string `json:"name"`
	Conclusion string `json:"conclusion"`
}

CLIJobVerdict is one job's state in a wait's answer.

type CLINotifyRequest

type CLINotifyRequest struct {
	Subject    string                   `json:"subject"`
	Title      string                   `json:"title"`
	Body       string                   `json:"body,omitempty"`
	Severity   string                   `json:"severity,omitempty"`
	Task       string                   `json:"task,omitempty"`
	ClearsWhen *model.NotificationClear `json:"clears_when,omitempty"`
}

CLINotifyRequest is POST /cli/notify's body.

type CLINotifyResult

type CLINotifyResult struct {
	ID       int64  `json:"id"`
	Subject  string `json:"subject"`
	Severity string `json:"severity"`
	Count    int    `json:"count"`
	New      bool   `json:"new"`
}

CLINotifyResult is POST /cli/notify's answer.

type CLIProposeRequest

type CLIProposeRequest struct {
	ID              string              `json:"id,omitempty"`
	Title           string              `json:"title"`
	Body            string              `json:"body"`
	Repo            string              `json:"repo,omitempty"`
	Branch          string              `json:"branch,omitempty"`
	NoRepo          bool                `json:"no_repo,omitempty"`
	DependsOn       []string            `json:"depends_on,omitempty"`
	Capabilities    []string            `json:"capabilities,omitempty"`
	CustomFields    map[string][]string `json:"custom_fields,omitempty"`
	NotBefore       *time.Time          `json:"not_before,omitempty"`
	FixesBaseBranch bool                `json:"fixes_base_branch,omitempty"`
	NoPort          bool                `json:"no_port,omitempty"`
	KeepRunning     bool                `json:"keep_running,omitempty"`
	Origin          string              `json:"origin,omitempty"`
	Reads           []string            `json:"reads,omitempty"`
	Designs         []string            `json:"designs,omitempty"`
	HoldForApproval *bool               `json:"hold_for_approval,omitempty"`
	AutoMerge       *bool               `json:"auto_merge,omitempty"`
	Supersedes      string              `json:"supersedes,omitempty"`
	Priority        *int                `json:"priority,omitempty"`
}

CLIProposeRequest is POST /cli/proposals' body.

type CLIProposeResult

type CLIProposeResult struct {
	ID              string `json:"id"`
	URL             string `json:"url"`
	HoldForApproval bool   `json:"hold_for_approval"`
	AutoMerge       bool   `json:"auto_merge"`
	Queued          bool   `json:"queued"`
	Held            bool   `json:"held"`
	ApprovalNote    string `json:"approval_note,omitempty"`
	// DroppedDefaults is the default grants the capability policy kept
	// off the proposal, each with the policy's reason
	// (ui.Task.DroppedDefaults).
	DroppedDefaults []CLIDroppedDefault `json:"dropped_defaults,omitempty"`
}

CLIProposeResult is POST /cli/proposals' answer.

type CLIQuarantineRequest

type CLIQuarantineRequest struct {
	TestName     string `json:"test_name"`
	Reason       string `json:"reason"`
	TTL          string `json:"ttl,omitempty"`
	FileFollowUp *bool  `json:"file_follow_up,omitempty"`
}

CLIQuarantineRequest is POST /cli/quarantine's body.

type CLIQuarantineResult

type CLIQuarantineResult struct {
	TaskID         string `json:"task_id"`
	FollowUpTaskID string `json:"follow_up_task_id,omitempty"`
	// FollowUpError is why the repair proposal asked for was not filed,
	// so the caller can say so rather than report a quarantine that
	// quietly has nobody fixing it.
	FollowUpError string `json:"follow_up_error,omitempty"`
}

CLIQuarantineResult is POST /cli/quarantine's answer.

type CLIReportChecker

type CLIReportChecker interface {
	CheckReportDraft(ctx context.Context, taskID, runID, report string) (text string, failed bool, err error)
}

CLIReportChecker checks a draft closing report against the records the run has read so far: the check grain runs on the report once it is posted (orchestrator's stewardReportCheck), run early so the agent can fix the report first. failed is whether that check would flag it; text says why, line by line.

type CLIReviewThreadActions

type CLIReviewThreadActions interface {
	ListReviewThreads(ctx context.Context, taskID string, unresolvedOnly bool) (CLIActionResult, error)
}

CLIReviewThreadActions is an optional extension of CLIActions: the review threads on a task's own pull request (grain pr threads), each with the IDs grain pr reply and grain pr resolve take. A read of the task's own pull request, so it needs no CI grant.

type CLITaskActions

type CLITaskActions interface {
	NotifyOperator(ctx context.Context, taskID string, req CLINotifyRequest) (CLINotifyResult, error)
	MessageTask(ctx context.Context, callerTaskID, targetTaskID, body string) (int64, error)
	CheckWaitTargets(ctx context.Context, callerTaskID string, ids []string) ([]model.WaitTarget, error)
	ProposeTask(ctx context.Context, callerTaskID, runID string, req CLIProposeRequest) (CLIProposeResult, error)
	ListAPIRoutes(ctx context.Context, callerTaskID string, grants []string, scopeFilter string) ([]CLIAPIRoute, error)
}

CLITaskActions extends CLIActions with the Stage 3 collaboration, wait, proposal, and API-discovery actions. Implemented by pkg/ui's SandboxCLIActions and pkg/daemon's sandboxCLIGate.

type CLITaskWaitRequest

type CLITaskWaitRequest struct {
	IDs            []string `json:"ids"`
	Until          string   `json:"until,omitempty"`
	TimeoutSeconds int      `json:"timeout_seconds,omitempty"`
	Park           bool     `json:"park,omitempty"`
	ResumeAt       string   `json:"resume_at,omitempty"`
}

CLITaskWaitRequest is POST /cli/tasks/wait's body.

type CLITaskWaitResponse

type CLITaskWaitResponse struct {
	Status      string             `json:"status"`
	Until       string             `json:"until"`
	Targets     []model.WaitTarget `json:"targets"`
	Summary     string             `json:"summary"`
	WaitedMS    int64              `json:"waited_ms"`
	CreditMS    int64              `json:"credit_used_ms"`
	CreditCapMS int64              `json:"credit_cap_ms,omitempty"`
	CreditLive  bool               `json:"credit_live"`
}

CLITaskWaitResponse is POST /cli/tasks/wait's answer.

type CLIWaitCredit

type CLIWaitCredit struct {
	Blocked  time.Duration
	Credited time.Duration
	Cap      time.Duration
	Live     bool
}

CLIWaitCredit is what one report of CLI-blocked time bought.

type CLIWaitCreditor

type CLIWaitCreditor interface {
	CreditCLIWait(ctx context.Context, taskID string, blocked time.Duration) (CLIWaitCredit, error)
}

CLIWaitCreditor credits a run for time the sandbox CLI spent blocked on its behalf. blocked is the run's cumulative CLI total, never a delta. Implemented by pkg/daemon over orchestrator.RunWaitCredits.

type CLIWaitResponse

type CLIWaitResponse struct {
	// Status is "passed", "failed" or "running" (the slice ran out).
	Status      string          `json:"status"`
	RunID       string          `json:"run_id"`
	ResumeRunID string          `json:"resume_run_id,omitempty"`
	Commit      string          `json:"commit,omitempty"`
	Conclusion  string          `json:"conclusion,omitempty"`
	Error       string          `json:"error,omitempty"`
	Report      string          `json:"report,omitempty"`
	Selective   bool            `json:"selective,omitempty"`
	Jobs        []CLIJobVerdict `json:"jobs"`
	WaitedMS    int64           `json:"waited_ms"`
	CreditMS    int64           `json:"credit_used_ms"`
	CreditCapMS int64           `json:"credit_cap_ms,omitempty"`
	CreditLive  bool            `json:"credit_live"`
	// CancelReason is the note a cancelled run was left with, and
	// CancelledByHand whether a person (not grain) wrote it -- what
	// wait_for_checks says of a cancellation (pkg/mcp's ciRunReport).
	CancelReason    string `json:"cancel_reason,omitempty"`
	CancelledByHand bool   `json:"cancelled_by_hand,omitempty"`
	// SupersededBy is the run grain cancelled this one for, when that run
	// is on another commit of this task's branch -- a newer push, which
	// followSuperseded does not follow -- and SupersededByCommit its
	// commit: the verdict the wait's asker most likely wants next.
	SupersededBy       string `json:"superseded_by,omitempty"`
	SupersededByCommit string `json:"superseded_by_commit,omitempty"`
}

CLIWaitResponse is what /cli/ci/wait and /cli/ci/run-job answer.

type CapRegistry

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

CapRegistry is where the servers a sandbox may reach under /cap/ are registered: by an agent run's run ID (CapRunKey) or a CI job's sandbox name (CapSandboxKey), for exactly as long as the materialization that proxies them is open.

func NewCapRegistry

func NewCapRegistry() *CapRegistry

NewCapRegistry returns an empty registry.

func (*CapRegistry) Register

func (r *CapRegistry) Register(key string, servers []CapServer) (unregister func())

Register makes servers the ones key reaches, replacing any before, and returns what removes them again -- which removes nothing once a later Register has replaced them.

func (*CapRegistry) Servers

func (r *CapRegistry) Servers(key string) ([]CapServer, bool)

Servers returns what key reaches, and whether anything is registered.

type CapServer

type CapServer struct {
	// Name is the server's name in the attempt (protocol.AssignServerNames).
	Name string
	// Grant is the capability reference it was granted under.
	Grant string
	Tools []CapTool
	// Handler is the grant's endpoint proxy: it injects the server's own
	// credentials, so it is reached only after the delivery check.
	Handler http.Handler
}

CapServer is one granted capability server as a sandbox reaches it.

type CapTool

type CapTool struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	InputSchema map[string]any `json:"inputSchema,omitempty"`
	ModelOnly   bool           `json:"modelOnly"`
}

CapTool is one tool of a capability server's attempt toolset, with the delivery grain resolved for it (protocol.ResolveModelOnly).

type CommandForge

type CommandForge struct {
	// GitAuthorization is the Authorization header the hosts' git
	// smart-HTTP endpoints take for token, handed to the tool for those
	// requests only; nil sends them with the tool's own login, as a REST
	// call is.
	GitAuthorization func(token string) string
	// LoginPage reports whether text -- what the tool printed on stderr,
	// or an HTML page it answered with -- is the front end's login page,
	// and the login address it names, which authfix.ClassifyRedirect then
	// turns into what to run (LoginRedirectError).
	LoginPage func(text string) (location string, ok bool)
	// RetryLogin reports whether a login page at location -- the
	// address LoginPage, or a redirect, named -- can clear by itself, so
	// an idempotent request answered with it is worth trying again after
	// a pause (CommandForgeTransport.RoundTrip). nil retries every one; a
	// source whose login only a person can renew answers false for it.
	RetryLogin func(location string) bool
	// GitRefusedHint is said when a git endpoint refused a token whose
	// login the REST API still accepts: how the hosts' git endpoints take
	// a token and how to check that by hand. Empty, or nil, says nothing
	// more.
	GitRefusedHint func(host, owner, repo string) string
}

CommandForge is what a ForgeViaCommand source says about its hosts beyond the tool itself. Every field is optional.

type CommandForgeTransport

type CommandForgeTransport struct {
	// Host is the host the tool is asked about (GH_HOST).
	Host string
	// APIBase is scheme://host/prefix of the host's REST API: a request
	// under it is given to the tool as the endpoint relative to it, which
	// the tool prefixes with the same base itself, and any other URL
	// (git smart HTTP) is given whole.
	APIBase string
	// Proxy, when set, is put in the tool's environment as HTTPS_PROXY:
	// an operator's proxy for the host, honoured but never required.
	Proxy string
	// Timeout bounds one run; zero is commandForgeTimeout. The request's
	// own context bounds it too.
	Timeout time.Duration

	// Source is the ambient source the tool is, by name: what a daemon
	// beside grain hostd asks the host's host-git server to run.
	Source string
	// Command is the tool, looked up on PATH; Env is added to the
	// account's environment for it ({host} already expanded).
	Command string
	Env     []string
	// LoginFix is the command that logs the account in to Host, for the
	// refusal of a tool that is not installed.
	LoginFix string
	// Forge is the source's own part: how its host's git endpoints take
	// a token, and what its login page looks like.
	Forge CommandForge
}

CommandForgeTransport sends each request as one `<command> api` run on this host. The zero value is not usable: newCommandForgeTransport builds one from a source.

func (*CommandForgeTransport) RoundTrip

func (t *CommandForgeTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip runs the tool for req and answers with what it printed: the status line and headers --include puts first, and the body after them, streamed. A request the tool could not send at all is an error naming the command and what it said on stderr (never its stdout, which is the response body); one answered with a login page is LoginRedirectError.

An idempotent request (loginRetryable) the tool reports answering with a login page (CommandForge.LoginPage), one the source deems worth waiting out (CommandForge.RetryLogin), is tried again after each of commandForgeLoginRetries before the LoginRedirectError is returned. A front end's own redirect to its login (LoginRedirectError.Redirected) is returned at once: that login does not come back by itself. A push or a REST write is never sent twice here: whether it took effect is the caller's to find out.

type CommitIdentity

type CommitIdentity struct {
	Name       string
	Email      string
	SigningKey string
}

CommitIdentity is a git user.name, user.email, and optional SSH SigningKey, any of which may be empty: the shape AmbientGitIdentity answers in, kept apart from mcp.GitIdentity only so this package need not import mcp.

func (CommitIdentity) Empty

func (i CommitIdentity) Empty() bool

Empty reports whether neither half is set.

func (CommitIdentity) String

func (i CommitIdentity) String() string

String is the identity as git prints it, `Name <email>`, or whichever half there is.

type ConfigProposalLookup

type ConfigProposalLookup interface {
	GitConfigProposalPrefix(ctx context.Context, sandbox string) (string, error)
}

ConfigProposalLookup is the optional half of BranchLookup that answers which grain/config branches a sandbox's live run may push beyond its own: the proposal branches propose_config_change pushes, under model.ConfigProposalBranchPrefix, for a run whose task holds grain/config in its Writes (model.Store.GitConfigProposalPrefix). "" is a run with none. A lookup that does not implement it is read as no run having any.

type ConnectionResolver

type ConnectionResolver func(owner, repo string) (string, bool)

ConnectionResolver names the credential the deployment's git connections give (owner, repo) on the default host, false when none covers it (model.Store.GitConnectionOn).

type Credential

type Credential struct {
	Name  string
	Token *string
	// MintFailure is set only on the one anonymous credential that is
	// *not* that deliberate shape: a *.app.json credential whose
	// installation token could not be minted, which load serves with a
	// nil Token so a public repo keeps working (see MintFailure's own doc
	// comment). It travels on the credential rather than being looked up
	// separately so that everything already handed a Credential -- the
	// proxy's refusal messages, the named-token check, the Settings pane
	// -- can tell that anonymous apart from the intended one without
	// asking the ladder a second question.
	MintFailure *MintFailure
	// WrongHost is set, with a nil Token, on a credential recorded for a
	// git host other than the one the request it was loaded for goes to
	// (hosts.go): the sentence a refusal says, since such a credential is
	// never sent.
	WrongHost string
	// SSH is set on an SSH key credential (<name>.ssh.json, sshkey.go),
	// with a nil Token: its requests are run over SSH on its own host
	// rather than forwarded over HTTPS (sshforward.go).
	SSH *SSHCredential
	// Unusable is set, with a nil Token, on a credential whose file is
	// there but cannot be used -- an SSH key that will not parse, or pins
	// no host key -- and is the sentence the request is refused with.
	// Unlike an App that cannot mint, nothing is sent anonymously in its
	// place: an SSH credential has no anonymous HTTPS equivalent to fall
	// back to on the host it names.
	Unusable string
	// Ambient is set on a credential loaded from <name>.ambient.json
	// (ambient.go): its Token was asked of this host's own gh or git
	// login rather than read from a file, and is dropped on a 401
	// (Refused) so a re-login is followed.
	Ambient *AmbientCredential
}

Credential is a named credential. A nil Token means anonymous -- no Authorization header at all, which is what a public repo needs and is a deliberate credential shape, not an error case.

func ParseSSHKey

func ParseSSHKey(name string, f SSHKeyFile) (Credential, error)

ParseSSHKey checks f as SetSSHKey would and returns it as a Credential named name, without writing anything: what a Test of a key not yet saved runs with.

type CredentialHost

type CredentialHost struct {
	// Host is the normalized git host (model.NormalizeGitHost).
	Host string `json:"host"`
	// Kind is model.GitHostGitHub or model.GitHostGit.
	Kind model.GitHostKind `json:"kind,omitempty"`
	// BaseURL is the scheme://host[:port] the host is reached on, when
	// that is not https on the default port. Empty means https://Host.
	BaseURL string `json:"base_url,omitempty"`
	// Proxy is the http(s)://host:port proxy every connection grain's
	// daemon makes to this host goes through -- git fetches and pushes,
	// REST calls, token checks -- and that no other host's traffic uses.
	// Empty means the daemon's own environment decides, as for any host.
	// It never carries a login: the record is not a secret.
	Proxy string `json:"proxy,omitempty"`
	// Author is the human user's name or login recorded when a user
	// delegates their credential to grain (`grain git-login`). When set,
	// grain signs new pull requests and comments made with this credential
	// as "Signed by <Author> (via Grain)".
	Author string `json:"author,omitempty"`
	// Recorded is false for a credential with no host file, whose host
	// is the set's default.
	Recorded bool `json:"-"`
}

CredentialHost is one credential's host record.

func NormalizeCredentialHost

func NormalizeCredentialHost(h CredentialHost) (CredentialHost, error)

NormalizeCredentialHost checks and normalizes h: a host is required, the kind must be known, and a base URL must be an http(s) URL on that same host with nothing past it.

func (CredentialHost) APIBase

func (h CredentialHost) APIBase() (host, prefix string, ok bool)

APIBase is h's REST API, as the github.RealTransport host and path prefix a call to it needs: api.github.com for github.com, and <host>/api/v3 for a GitHub Enterprise Server. A git-kind host has no API, and answers ok false.

func (CredentialHost) CheckTransport

func (h CredentialHost) CheckTransport() error

CheckTransport is whether the git proxy will forward to h at all: the refusal ValidateForwardTarget gives every request to an http:// base URL on anything but loopback, given when the host is saved instead of on each clone after it.

A host behind a proxy of its own is left alone. Its REST calls go to that proxy, which is what reaches the host (GitHub-on-Prem behind uplink), and its git traffic can go over SSH and never reach the forwarder.

func (CredentialHost) HTTPClient

func (h CredentialHost) HTTPClient(timeout time.Duration) *http.Client

HTTPClient is an http.Client for h's REST API, bounded by timeout and sent through h's proxy when it has one (HTTPTransport). A redirect to a login page authfix knows is not followed but answered as LoginRedirectError, so a host behind a front end whose login has lapsed says so rather than handing back the login page's HTML.

func (CredentialHost) HTTPTransport

func (h CredentialHost) HTTPTransport(base *http.Transport) http.RoundTripper

HTTPTransport is the round tripper for connections to h: a clone of base (http.DefaultTransport when nil) sending through h's proxy when it has one, and base itself otherwise -- so a host with no proxy is reached exactly as before, the daemon's own HTTPS_PROXY and NO_PROXY included.

func (CredentialHost) UseTLS

func (h CredentialHost) UseTLS() bool

UseTLS reports whether h is reached over https.

type CredentialOverrideLookup

type CredentialOverrideLookup interface {
	GitCredentialOverride(ctx context.Context, sandbox, owner, repo string) (name string, ok bool, err error)
}

CredentialOverrideLookup resolves a sandbox to the named credential its live task asks the proxy to use in place of the owner/repo ladder -- bwsalmon/agents#52's `grain-github-<name>` label, by way of model.GitCredentialGrant. model.Store implements this via GitCredentialOverride; a test supplies a stub instead. Kept separate from ScopeLookup because it answers a different question (which credential, not which repo) that GitProxy.Handle only needs to ask once authorization has already allowed the request through.

type CredentialSet

type CredentialSet struct {

	// AppTransport, when set, is where every *.app.json credential's
	// installation token gets minted -- a test's github.FakeTransport, the
	// same way live_test.go overrides RealForwarder. nil mints each
	// credential against its own host's REST API (appTransportFor in
	// hosts.go): api.github.com, or <host>/api/v3 on GitHub Enterprise.
	AppTransport github.Transport
	// ForwardHost is the host[:port] the git proxy attaches this set's
	// tokens to (BuildConfig.ForwardHost), or "" for a set that does not
	// know. It is the default host of a credential with no host record,
	// and a set that knows it never hands out a credential recorded for
	// another host (wrongHost in hosts.go, Credential.WrongHost).
	ForwardHost string
	// ForwardInsecure is set when ForwardHost is reached over plain http
	// (BuildConfig.ForwardTLS false: a test's fake server), which a
	// credential with no host record then is too.
	ForwardInsecure bool
	// Now is load's clock, overridable so a test can advance past an App
	// token's expiry without an actual hour passing. nil means time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

CredentialSet is the git credential material in a secrets directory.

Select and Get are called from GitProxy.Handle, which NewHandler wires straight into net/http -- one goroutine per inbound request, so every sandbox's concurrent git traffic reaches load's cache at once. mu guards it for exactly that reason.

func LoadCredentialSet

func LoadCredentialSet(secretsDir string) (*CredentialSet, error)

LoadCredentialSet loads the credential material under secretsDir: one <name>.token, <name>.app.json, <name>.ssh.json or <name>.ambient.json per credential. Which credential a repository uses is the deployment's git connections' answer (SetConnections), never a file in this directory: the credentials.json ladder that used to say so is gone (docs/single-tenant-reset.md, stage 2).

func (*CredentialSet) APICredential

func (c *CredentialSet) APICredential(cred Credential) (Credential, bool)

APICredential is the credential REST calls go out under on name's behalf: name itself for a token or App, its paired api_credential for an SSH key. ok is false for an SSH key with no pair, whose repositories are git-only (GitOnlyReason).

func (*CredentialSet) AmbientGitIdentity

func (c *CredentialSet) AmbientGitIdentity(name string) (CommitIdentity, error)

AmbientGitIdentity is the commit identity a run pushing through the ambient credential name commits under when its team has named none: what already exists on this host, in this order --

  1. the host account's own git identity (HostGitIdentity), which is what the person that login belongs to commits as by hand; and
  2. for whichever half that leaves empty, the ambient login itself as GitHub knows it (AmbientIdentityOf): its display name, or its login when it has none, and its noreply address, <id>+<login>@users.noreply.<host> (AmbientIdentity.NoreplyEmail), which GitHub attributes to the account exactly as it does a verified address. A plain git host has no /user to ask, so this half is only the credential helper's username there.

An error is a name that is not an ambient credential, or a login the host's tools could not produce when the host's git config was not enough on its own; the caller falls back to grain's own default identity then, as it would for any other credential. An identity with both halves empty is returned as such, with no error, when the host simply has none to offer.

func (*CredentialSet) AmbientIdentityOf

func (c *CredentialSet) AmbientIdentityOf(name string) (AmbientIdentity, error)

AmbientIdentityOf resolves name the way a request would and asks GitHub who that token is.

func (*CredentialSet) AmbientIdentityWithin

func (c *CredentialSet) AmbientIdentityWithin(name string, wait time.Duration) (id AmbientIdentity, pending bool, err error)

AmbientIdentityWithin is AmbientIdentityOf for a caller that answers a person -- a settings pane, a Save -- and so must not sit on a host tool that is slow or stuck: it waits at most wait, and otherwise reports pending while the lookup goes on in the background, so that asking again later (the pane polls) finds it done, or joins it if it is not. The lookup itself stays bounded by ambientCommandTimeout and appMintTimeout.

func (*CredentialSet) AmbientOf

func (c *CredentialSet) AmbientOf(name string) (AmbientFile, bool)

AmbientOf is name's ambient file, when it is one.

func (*CredentialSet) AppBotLogin

func (c *CredentialSet) AppBotLogin(name string) (string, bool, error)

AppBotLogin returns `<slug>[bot]` when credential name (or its paired SSH API credential) is backed by a GitHub App, or ("", false) when name is not an App credential.

func (*CredentialSet) AppMintFailure

func (c *CredentialSet) AppMintFailure(name string) (MintFailure, bool)

AppMintFailure reports whether name is an App-backed credential that cannot be turned into an installation token right now, and what GitHub said about it -- the answer a pane showing that credential needs before it can report anything better than "present" (grain/task-158).

It resolves the credential exactly as a request would, through load and its cache, rather than reporting only what this process happened to have hit already: the callers are a human's own read of the credential, and a set that has not been asked for this name yet knows nothing to tell them. So this can mint -- one token exchange, then cached for the token's own hour, or for appMintFailureRetryDelay if it failed -- and it is bounded by appMintTimeout above.

The answer is this process's ladder, which is not the git proxy's own (see forget's doc comment: a deployment holds several). It is the same files, the same App and the same GitHub, so a failure here is the failure a push would hit; what it cannot do is report the exact moment the proxy last tried.

func (*CredentialSet) AppWebhookSecret

func (c *CredentialSet) AppWebhookSecret(name string) (string, bool)

AppWebhookSecret returns the webhook_secret stored in name.app.json, if name is a GitHub App credential carrying one.

func (*CredentialSet) AuthType

func (c *CredentialSet) AuthType(name string) string

AuthType is which kind of credential name is: AuthTypeSSH, AuthTypeApp or AuthTypePAT for its file, AuthTypeAnonymous for "anonymous", and "" for nothing configured. load prefers them in that order when a name somehow has more than one file.

func (*CredentialSet) AuthorOf

func (c *CredentialSet) AuthorOf(name string) string

AuthorOf returns the human author attribution name recorded for credential name (or its paired SSH API credential), or "" when none is recorded.

func (*CredentialSet) CredentialGitIdentity

func (c *CredentialSet) CredentialGitIdentity(name string) (CommitIdentity, error)

CredentialGitIdentity is the commit identity a run pushing with credential name commits under: the account that credential's token acts as, in the shapes this file's own comment lists. An error is a credential that names nobody GitHub can say (anonymous, an SSH key with no API credential paired, a plain git host) or a lookup that failed; the caller then falls back to grain's own default identity.

func (*CredentialSet) CredentialGitIdentityWithin

func (c *CredentialSet) CredentialGitIdentityWithin(name string, wait time.Duration) (id CommitIdentity, pending bool, err error)

CredentialGitIdentityWithin is CredentialGitIdentity for a caller that answers a person -- a settings pane -- and so must not sit on a slow API: it waits at most wait, and otherwise reports pending while the lookup goes on in the background, so that asking again later finds it done (cached) or joins it.

func (*CredentialSet) CredentialOwnerIdentity

func (c *CredentialSet) CredentialOwnerIdentity(name string) (CommitIdentity, error)

CredentialOwnerIdentity is who credential name belongs to, as its own forge answers for it: the same lookup CredentialGitIdentity makes, but without the host account's git config (HostGitIdentity) laid over the answer. CredentialGitIdentity prefers the host's git config because a commit is the host person's own work; a signature ("Signed by <Author> (via Grain)") instead says whose credential acted, and that is the token's owner even on a host whose own git user is somebody else (design/design/git-login.design.md). For an ambient credential the owner is the host's login as GitHub knows it (AmbientIdentityOf), falling back to AmbientGitIdentity when that login cannot be read.

func (*CredentialSet) CredentialOwnerIdentityWithin

func (c *CredentialSet) CredentialOwnerIdentityWithin(name string, wait time.Duration) (id CommitIdentity, pending bool, err error)

CredentialOwnerIdentityWithin is CredentialOwnerIdentity bounded the way CredentialGitIdentityWithin is, for a caller that answers a person -- recording who a connection signs as when it is saved.

func (*CredentialSet) DefaultHost

func (c *CredentialSet) DefaultHost() string

DefaultHost is the host a credential with no host record is on, and the host a request naming none goes to: the ForwardHost this set's tokens go to, or github.com.

func (*CredentialSet) DeleteMigratedCopies

func (c *CredentialSet) DeleteMigratedCopies() ([]string, error)

DeleteMigratedCopies retires every <name>.token.migrated, <name>.app.json.migrated and <name>.ssh.json.migrated copy MigrateFilesToStore left in this set's directory (RetireMigratedCopy): deleted once the store holds that credential, read from the store's file rather than this set's snapshot, and kept, with a warning, while it does not. A set with no store deletes nothing: its copies are what RestoreFilesFromStore renames back.

func (*CredentialSet) Dir

func (c *CredentialSet) Dir() string

Dir is the secrets directory this set was loaded from -- for a caller that has to *name* it to a human (pkg/ui's Settings pane, explaining where the token it just wrote landed). It is a path, and says nothing about what is in it.

func (*CredentialSet) ExtraNames

func (c *CredentialSet) ExtraNames() []string

ExtraNames is every named credential a task can ask for by name, which is exactly the set that becomes a capability of its own (model.GitCredentialCapability, pkg/capability/githubtoken).

func (*CredentialSet) ForgeHTTPClient

func (c *CredentialSet) ForgeHTTPClient(name string, timeout time.Duration) *http.Client

ForgeHTTPClient is the http.Client for credential name's forge API, bounded by timeout: one that runs `<tool> api` for a credential whose source is such a tool, and the host record's own (HTTPClient) otherwise.

func (*CredentialSet) ForgeTransport

func (c *CredentialSet) ForgeTransport(name string) (github.Transport, error)

ForgeTransport is the github.Transport for credential name's own host's REST API: what a check of that credential, or a listing of what it reaches, sends with.

func (*CredentialSet) ForgeTransportOn

func (c *CredentialSet) ForgeTransportOn(name, host string) (github.Transport, error)

ForgeTransportOn is the github.Transport for the REST API of a repository on host whose git traffic credential name carries -- the one route the server side reaches a forge on any host but its own -github-host by, so that a pull request, a branch read or a merge for a repository on that host goes where its pushes went:

  • an ambient credential (the host's own login) is asked through ambientTransportFor, which for a ForgeViaCommand source means a `<tool> api` run per request (CommandForgeTransport) against https://<host>/api/v3, the one way through the front end;
  • a credential recorded on host is sent to that host's API base (APIBase: api.github.com, or <host>/api/v3 for an Enterprise host), through its proxy if it names one;
  • no credential, or one on another host, falls back to host's own record, so the request at least goes to the right host and is refused there rather than answered by some other forge.

A plain git host has no API to send to, and is an error.

func (*CredentialSet) ForgeViaCommand

func (c *CredentialSet) ForgeViaCommand(name string) bool

ForgeViaCommand reports whether credential name's forge calls go through a host tool (`<tool> api`) rather than grain's own HTTP client.

func (*CredentialSet) Get

func (c *CredentialSet) Get(name string) (Credential, bool)

Get returns a named credential directly, bypassing the owner/repo pattern ladder Select uses -- bwsalmon/agents#52's per-task grain-github-<name> label, for a task that needs a scope the default ladder deliberately withholds (docs/design.md, "scopes to withhold"). The second return is false if no such credential is configured (neither <name>.token nor <name>.app.json exists, and name isn't the literal "anonymous").

func (*CredentialSet) GetForRepo

func (c *CredentialSet) GetForRepo(name, owner, repo string) (Credential, bool)

GetForRepo is Get narrowed the way SelectForRepo narrows Select: the named credential, with an App-backed one's token minted for (owner, repo) alone.

func (*CredentialSet) GetForRepoOn

func (c *CredentialSet) GetForRepoOn(name, host, owner, repo string) (Credential, bool)

GetForRepoOn is GetForRepo for a repository on host (empty: the set's default host): a credential recorded for any other host comes back with no token and a WrongHost refusal, and nothing -- an App's JWT included -- is sent anywhere to find that out.

func (*CredentialSet) HostGitIdentity

func (c *CredentialSet) HostGitIdentity() CommitIdentity

HostGitIdentity is the git identity this host's own account commits with by hand: its global `git config user.name` and `user.email`, read as the account whose login an ambient credential borrows (ambientEnv, so a host-mode daemon whose HOME points into its data directory still reads the account's real ~/.gitconfig). Either half the account never set is empty. It is only answered where an ambient credential is (AmbientAvailable): inside the deployment container there is no account of a person's to read.

Cached on c for hostGitIdentityTTL, under its own key so a test that changes the fake host's answer can advance Now past it.

func (*CredentialSet) HostOf

func (c *CredentialSet) HostOf(name string) CredentialHost

HostOf is name's host record, or the set's default host for a credential with none. When name is a host rather than a credential in the set, it returns the host record of the first credential recorded on that host. A record that will not parse is logged and read as the default host too -- the same fail-soft every other credential file gets here -- except that it is never quietly some *other* host.

func (*CredentialSet) InStore

func (c *CredentialSet) InStore() bool

InStore reports whether this set keeps credentials in the secrets store rather than in files.

func (*CredentialSet) IsAmbient

func (c *CredentialSet) IsAmbient(name string) bool

IsAmbient reports whether name is backed by a <name>.ambient.json file.

func (*CredentialSet) IsApp

func (c *CredentialSet) IsApp(name string) bool

IsApp reports whether name is backed by a <name>.app.json file -- a GitHub App installation whose token load re-mints, rather than a *.token file read as-is. Callers that offer to *edit* a credential need this: SetToken below refuses to write over an App credential, and a UI is better off saying so up front than after the fact.

func (*CredentialSet) IsSSH

func (c *CredentialSet) IsSSH(name string) bool

IsSSH reports whether name is backed by a <name>.ssh.json file.

func (*CredentialSet) MigrateCredentialHosts

func (c *CredentialSet) MigrateCredentialHosts()

MigrateCredentialHosts writes the set's default host down for every credential that has no host record yet, so a credential configured while the deployment forwarded to one host stays on that host if ForwardHost later changes. It does nothing on a github.com set, whose unrecorded credentials are already where they always were.

func (*CredentialSet) MigrateFilesToStore

func (c *CredentialSet) MigrateFilesToStore() ([]MigratedFile, error)

MigrateFilesToStore imports every <name>.token, <name>.app.json and <name>.ssh.json file in this set's directory into the store: each is Set, read back from a fresh decrypt of the store's file and compared byte for byte, and only then renamed to <file>.migrated, the copy a rollback restores. A file that fails any step is left where it is, and logged, and is still read as before.

It is safe to run on every start. A tree already migrated has no such files and does nothing. A file that is back (an older setup.sh re-seeded it, or an operator rolled back and forward again) is the newer word and overwrites what the store holds, and its earlier .migrated copy.

A set with no store migrates nothing.

func (*CredentialSet) Names

func (c *CredentialSet) Names() []string

Names is every credential this deployment has configured: one per github-credential-<name> secret in the store, and per <name>.token, <name>.app.json, <name>.ssh.json or <name>.ambient.json file in the secrets directory, sorted, with a name that has several counted once (load prefers the SSH key, then the App, so it is one credential either way).

Read from the directory rather than from credentials.json, because the two answer different questions: the pattern file says which credential a repo falls back to, while this says which credentials exist at all -- including the extra named tokens an operator drops in for Get above to reach, which no pattern ever names (ExtraNames below).

Unlike load's own cache this re-reads the directory on every call: it is called at startup, not per request, and a listing is cheap next to the "restart the one service that reads it" contract the rest of this file keeps.

func (*CredentialSet) PackageCredential

func (c *CredentialSet) PackageCredential(registry, owner, repo string) (PackageCredential, error)

PackageCredential is the login that publishes owner/repo's packages: the ladder's own credential for that repository, addressed to registry (DefaultPackageRegistry when empty, or the registered PackageCredentialSource's default registry).

It fails rather than falling back to an anonymous push. Every other caller of the ladder has a reason to serve a credential-less request -- a public repository stays readable through a failed App mint (MintFailure's own doc comment) -- and a publish has none: an unauthenticated `docker push` is refused by the registry, several minutes of upload later, with the registry's error rather than this deployment's reason. So the reason is given here, before a job starts.

func (*CredentialSet) PackageToken

func (c *CredentialSet) PackageToken(owner, repo string) (string, bool)

PackageToken returns the bearer/basic token Select resolves for (owner, repo), satisfying pkgcache.RegistryCredentials without pkg/pkgcache importing this package. Safe to call on a nil *CredentialSet.

func (*CredentialSet) PrimaryAmbientCredential

func (c *CredentialSet) PrimaryAmbientCredential() string

PrimaryAmbientCredential returns the name of an ambient credential in c when one exists.

func (*CredentialSet) Refused

func (c *CredentialSet) Refused(cred Credential)

Refused tells the set that cred's token was refused (a 401): an ambient credential's cached token is dropped so the next request asks the host's tools again and picks up a re-login. Nothing else is affected -- a stored token does not get better by being re-read.

func (*CredentialSet) RefusedToken

func (c *CredentialSet) RefusedToken(token string)

RefusedToken is Refused for a caller that holds only the token it sent (the REST client): every ambient credential currently serving that token is dropped.

func (*CredentialSet) Remove

func (c *CredentialSet) Remove(name string) error

Remove deletes the files backing name -- both forms, since a name with a *.token and a *.app.json is one credential either way (Names' own doc comment). It reports an error when nothing of that name is configured, so a caller can tell "removed" from "was never there."

It says nothing about credentials.json: a pattern naming a credential that no longer exists is a real, and deliberately visible, failure (Select's own fail-closed "no credential configured"). PatternsFor above is how a caller checks before asking for this.

func (*CredentialSet) RestoreFilesFromStore

func (c *CredentialSet) RestoreFilesFromStore() ([]string, error)

RestoreFilesFromStore is MigrateFilesToStore's reversal: every credential the store holds is written back to its file, from the store's current value (which a Settings edit since the migration may have changed), a .migrated copy with no store value is renamed back, and the store's copy is deleted, so the files are once more the only answer -- what an older build reads. It opens the store beside the directory even when CredentialsInFilesEnv is set, since that is when it is run.

func (*CredentialSet) SSHKeyInfoOf

func (c *CredentialSet) SSHKeyInfoOf(name string) (SSHKeyInfo, bool)

SSHKeyInfoOf is name's SSHKeyInfo.

func (*CredentialSet) Select

func (c *CredentialSet) Select(owner, repo string) (Credential, bool)

Select returns the credential the deployment's git connections give (owner, repo), full scope. The second return is false if no connection covers it, or if this set was given no Connections to ask -- a distinct, fail-closed condition from "not allowed at all." Its callers name packages rather than repositories (PackageCredential, the package cache's registry pulls), which is why it is not narrowed the way GetForRepo is.

func (*CredentialSet) ServerGitRemoteFor

func (c *CredentialSet) ServerGitRemoteFor(ctx context.Context, credential Credential, host, owner, repo string) (*ServerGitRemote, error)

ServerGitRemoteFor is the ServerGitRemote for owner/repo on host with credential, or nil when credential's git traffic needs no tool in front of it -- the caller's own https URL and askpass are right for it, as they always were. The listener lives until Close or ctx ends.

Every server-side git command against a repository (grain CI's workflow and history reads, repository declarations, and whatever is added next) asks this first, so a command-backed host is reached the same way however the command came to be run.

func (*CredentialSet) SetAmbient

func (c *CredentialSet) SetAmbient(name, host, source string) error

SetAmbient writes name as an ambient credential for host, asking source, replacing any token, App or SSH key of the same name. It is refused where AmbientAvailable is: the guard is here, and not only in the UI, so nothing that writes credentials can create one in a container.

func (*CredentialSet) SetAmbientOn

func (c *CredentialSet) SetAmbientOn(name string, h CredentialHost, source string) error

SetAmbientOn is SetAmbient on a host of either kind. On a plain git host (model.GitHostGit) the only tool that can know a login is git's own credential helper, so source must be git (auto is stored as git): gh holds GitHub logins only.

func (*CredentialSet) SetApp

func (c *CredentialSet) SetApp(name, appID, installationID, privateKey string) error

SetApp writes a GitHub App credential, <name>.app.json, replacing a token or SSH key of the same name. The private key must parse; an empty installationID leaves installation discovery per-repository at mint time.

func (*CredentialSet) SetAppWithWebhookSecret

func (c *CredentialSet) SetAppWithWebhookSecret(name, appID, installationID, privateKey, webhookSecret string) error

SetAppWithWebhookSecret is SetApp with an optional webhook secret stored alongside the App's credentials in <name>.app.json.

func (*CredentialSet) SetConnections

func (c *CredentialSet) SetConnections(r ConnectionResolver)

SetConnections gives Select the deployment's git connections to ask. Safe to call while requests are in flight.

func (*CredentialSet) SetHost

func (c *CredentialSet) SetHost(name string, h CredentialHost) error

SetHost records name's host. The credential itself must already exist: a host record for nothing is a file nobody would ever read.

func (*CredentialSet) SetPAT

func (c *CredentialSet) SetPAT(name, token string) error

SetPAT writes token as name's credential, replacing an SSH key or App credential of the same name: the typed editor's PAT save, where SetToken alone refuses to overwrite an App.

func (*CredentialSet) SetSSHKey

func (c *CredentialSet) SetSSHKey(name string, f SSHKeyFile, kind model.GitHostKind) error

SetSSHKey writes f as name's credential: <name>.ssh.json, mode 0600, replacing any token or App credential of the same name, and a host record (kind) beside it. The file is checked first -- the key parses with its passphrase, known_hosts pins the host's key, and an API credential, if named, exists on the same host -- so nothing unusable is ever written.

func (*CredentialSet) SetToken

func (c *CredentialSet) SetToken(name, token string) error

SetToken writes token as name's credential material -- name.token in the secrets directory, mode 0600, replacing whatever was there.

Written to a temporary file and renamed into place, so a reader that catches this mid-write (the git proxy in another process, serving a push right now) sees either the old token or the new one, never half of one. The temporary file's own name deliberately does not end in .token, so a crash between create and rename cannot leave something Names would report as a credential.

Refused for a name already backed by name.app.json: load prefers the App credential, so the file this would write would be loaded by nothing, and silently doing nothing is the worst answer available.

The value takes effect for a process that has not loaded it yet; everything already running keeps what it cached (this file's own doc comment on why the ladder is not hot-reloaded). Callers that offer this to a human should say so.

func (*CredentialSet) SignGitPayload

func (c *CredentialSet) SignGitPayload(ctx context.Context, credName, namespace string, payload []byte) ([]byte, error)

SignGitPayload signs a commit or tag payload on the host for ambient credential credName.

func (*CredentialSet) UseStore

func (c *CredentialSet) UseStore(store *secrets.Store)

UseStore backs this set with store instead of the one beside its directory (nil: files only). For a caller that opened the deployment's store itself, and for tests.

type DeclaredPushLookup

type DeclaredPushLookup interface {
	GitDeclaredPush(ctx context.Context, sandbox string) (*model.DeclaredPush, error)
}

DeclaredPushLookup is the optional half of BranchLookup that answers which refs beyond its own branch a sandbox's live run may push by declaration: the `push:` list of the repository-declared template its task was filed from, as that repository's default branch has it (model.Store.GitDeclaredPush, grain/task-2536). A lookup that does not implement it is read as no run having one.

type DeploymentRepoLister

type DeploymentRepoLister interface {
	TargetRepos(ctx context.Context) ([]string, error)
}

DeploymentRepoLister lists the repositories this deployment works in -- Settings, Repositories; model.Store.TargetRepos. An empty list is an unrestricted deployment (model.RepoAllowed). Optional on ModelAuthorizer.Store: a store that cannot answer it restricts nothing beyond the run's own scope.

type FakeForwarder

type FakeForwarder struct {
	Response UpstreamResponse
	Err      error
	Calls    []ForwardCall
}

FakeForwarder records calls and replays a scripted response. For tests.

func (*FakeForwarder) Forward

func (f *FakeForwarder) Forward(method, path, query string, headers map[string]string, body []byte, token *string) (UpstreamResponse, error)

type FastForwardOnlyLookup

type FastForwardOnlyLookup interface {
	GitPushFastForwardOnly(ctx context.Context, sandbox string) (bool, error)
}

FastForwardOnlyLookup is the optional half of BranchLookup that answers whether a sandbox's live run may only fast-forward its own branch, because that branch is another task's: a security review working on the change it reviews (model.Store.GitPushFastForwardOnly). A lookup that does not implement it is read as no run being bound this way.

type FileAuditLog

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

FileAuditLog appends one JSON line per entry to a file.

func NewFileAuditLog

func NewFileAuditLog(path string) (*FileAuditLog, error)

NewFileAuditLog returns a FileAuditLog appending to path, creating the directory that holds it. The file itself is created on the first Record.

func (*FileAuditLog) Record

func (l *FileAuditLog) Record(entry AuditEntry)

type ForbiddenSet

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

ForbiddenSet holds the repos no sandbox may reach, for reading by the proxy's request goroutines while another goroutine replaces it.

A nil *ForbiddenSet reads as empty rather than panicking: a proxy wired up without one -- a test stub, or an Authorizer built by hand -- forbids nothing, which is the same answer the nil slice used to give.

func NewForbiddenSet

func NewForbiddenSet(repos ...model.RepoRef) *ForbiddenSet

NewForbiddenSet is a set holding repos, which may be none: an empty set that something later fills is the ordinary way to start, since the daemon has to hand the proxy the holder before it knows what belongs in it.

func (*ForbiddenSet) Forbids

func (s *ForbiddenSet) Forbids(owner, repo string) bool

Forbids reports whether owner/repo is in the set as it stands, matched the way every other repo comparison here is: case-insensitively, with or without .git. For a repository on a git host other than the default, owner is host/owner (model.RepoRef.StoredOwner).

func (*ForbiddenSet) Repos

func (s *ForbiddenSet) Repos() []model.RepoRef

Repos is what the set holds right now. The result is the set's own backing array and must not be written to.

func (*ForbiddenSet) Set

func (s *ForbiddenSet) Set(repos []model.RepoRef)

Set replaces the whole set, atomically: what is forbidden is re-read as a whole (cmd/grain's forbiddenRepos), so adopting a repository that has never held the secrets file has to be able to *unforbid* just as readily as adopting one that has forbids.

The slice is copied, so a caller may keep and reuse its own.

type ForwardCall

type ForwardCall struct {
	Method  string
	Path    string
	Query   string
	Headers map[string]string
	Body    []byte
	Token   *string
}

ForwardCall is one recorded call to FakeForwarder.Forward.

type Forwarder

type Forwarder interface {
	Forward(method, path, query string, headers map[string]string, body []byte, token *string) (UpstreamResponse, error)
}

Forwarder sends one validated request on to the real git host.

type GitProxy

type GitProxy struct {
	Authorizer  Authorizer
	Credentials *CredentialSet
	Tokens      *SandboxTokens
	Forwarder   Forwarder
	Audit       AuditLog
	Now         func() time.Time
	// CredentialOverrides resolves bwsalmon/agents#52's per-task named
	// credential override, if any. nil (every existing caller/test)
	// leaves every request on the ordinary owner/repo ladder, the same
	// as an override lookup that always answered false.
	CredentialOverrides CredentialOverrideLookup
	// SandboxTeams names the team a CI job's sandbox runs as, for a job
	// whose repository access is its team's to give (readscope.go's
	// SandboxTeams). A registered sandbox's requests go out with that
	// team's credential, resolved through TeamCredentials, and never with
	// the deployment's own ladder. nil registers nothing.
	SandboxTeams *SandboxTeams
	// TeamCredentials resolves a registered sandbox's team to its
	// credential. nil with a registered sandbox refuses the request
	// rather than falling back to the deployment's ladder.
	TeamCredentials TeamCredentialLookup
	// SingleTenant is the single-tenant engine, which the daemon always
	// runs (false is left only for the team tests until team RBAC goes,
	// docs/single-tenant-reset.md 3e-iii-d): one tenant, the
	// machine's owner, so a task or CI job whose team has no credential
	// is not refused (grain/task-1592's isolation is between tenants, and
	// there is one) but goes out on the deployment's own ladder. A CI
	// job's sandbox is resolved as the default team's, the same team a
	// single-tenant store resolves every task as (model.Store.SingleTenant).
	SingleTenant bool
	// Local, when set, is the controller-owned repository served under
	// its stable alias. It is authorized like every other repository but
	// never forwarded to GitHub or made to depend on a GitHub credential.
	Local *LocalRepository
	// ForwarderFor is where a request for a git host other than the
	// default is forwarded: the forwarder for the credential's own host.
	// nil sends it to that host's address (CredentialHost.hostPort,
	// base_url) with a RealForwarder; a test supplies fakes per host.
	ForwarderFor func(CredentialHost) (Forwarder, error)
	// PushSpoolThresholdBytes is the most of a push body held in memory
	// before spooling to disk. Zero means DefaultSpoolThreshold (16 MiB).
	PushSpoolThresholdBytes int64
	// MaxPushBodyBytes and MaxFetchBodyBytes cap the request body the
	// proxy will read for git-receive-pack and for everything else. Zero
	// means DefaultMaxPushBodyBytes / DefaultMaxFetchBodyBytes.
	MaxPushBodyBytes  int64
	MaxFetchBodyBytes int64
	// Namespace serves /fs/<scheme>/<path> over the same per-sandbox HTTP
	// listener and token authentication.
	Namespace       *namespace.Server
	NamespaceScopes NamespaceScopeLookup
	// CLI answers the /cli/ reads that are neither files nor grain CI's
	// records -- GitHub issues and grain's database (cli.go). nil answers
	// them 501 to a run holding the grant.
	CLI                     CLIBackend
	MaxNamespaceConcurrency int

	// Activity, when set, narrates each /fs/ request on the live run's
	// activity row and records it in task_run_tool (activity.go).
	Activity ProxyActivityRecorder

	// CLIActions, when set, serves the acting /cli/ routes -- grain ci
	// wait / run-job / retrigger, grain pr open / reply / resolve /
	// review-comment, and grain git revert's revert-info
	// (cli_actions.go). Nil answers each of them 501.
	CLIActions CLIActions
	// ReportChecker, when set, answers POST /cli/report/check (grain
	// report check): a draft closing report checked against what the run
	// has read so far. Nil answers it 501.
	ReportChecker CLIReportChecker
	// WaitCredit, when set, credits the time /cli/ci/wait and
	// /cli/ci/run-job block back to the run's wall-clock deadline.
	WaitCredit CLIWaitCreditor

	// API, when set, serves /api/... requests from the sandbox, forwarded
	// with X-Grain-Acting-Task, X-Grain-Acting-Run, and
	// X-Grain-Channel: sandbox-cli so agentAPIGate enforces non-dangerous
	// scope rules.
	API http.Handler
	// CapServers holds the external capability servers each attempt (or
	// CI job) may reach from its sandbox under /cap/<server>/mcp; nil
	// reaches none.
	CapServers *CapRegistry
	// ShutdownStarted, when set, is closed as the daemon begins to stop:
	// a blocking /cli/ci/wait or /cli/ci/run-job ends its slice at once
	// and hands back ResumeRunID rather than holding the proxy's
	// graceful shutdown until the slice expires.
	ShutdownStarted <-chan struct{}
	// contains filtered or unexported fields
}

GitProxy is the proxy's whole decision logic, wired to its dependencies. Now is injected rather than read from time.Now() so core_test.go can assert on audit timestamps deterministically.

func BuildProxy

func BuildProxy(cfg BuildConfig) (*GitProxy, error)

BuildProxy wires the real files under DataDir plus the live model store into a GitProxy ready to serve.

func (*GitProxy) Handle

func (p *GitProxy) Handle(ctx context.Context, method, path, query string, headers map[string]string, body []byte) ProxyResponse

Handle is HandleRequest for a body already in memory; nil is no body.

func (*GitProxy) HandleRequest

func (p *GitProxy) HandleRequest(ctx context.Context, method, path, query string, headers map[string]string, body io.Reader) ProxyResponse

HandleRequest decides how to answer one request and, if it is allowed, forwards it -- the entire proxy, as one call.

body is not touched until the request has been decided from its path and headers alone: a caller that is not running git, has no valid token, or is not scoped to the repository is answered without a byte of it being read, and an allowed one is read only up to maxBodyBytes for its action (413 past that). Anything that can reach the proxy can send a body, so reading it first would let any of them make the controller hold as much as they cared to send. nil is no body.

func (*GitProxy) ServeAPIHTTP

func (p *GitProxy) ServeAPIHTTP(w http.ResponseWriter, r *http.Request)

ServeAPIHTTP handles a request under /api/..., authenticating with the sandbox's per-attempt proxy token and forwarding to p.API (grain's UI/API server) with X-Grain-Acting-Task, X-Grain-Acting-Run, and X-Grain-Channel: sandbox-cli so agentAPIGate enforces non-dangerous scope boundaries and records the call.

func (*GitProxy) ServeCLIHTTP

func (p *GitProxy) ServeCLIHTTP(w http.ResponseWriter, r *http.Request)

ServeCLIHTTP handles a request under /cli/<route>.

func (*GitProxy) ServeCapHTTP

func (p *GitProxy) ServeCapHTTP(w http.ResponseWriter, r *http.Request)

ServeCapHTTP handles a request under /cap/..., authenticating with the sandbox's per-attempt proxy token and auditing the call. Built-in capability endpoints (/cap/memory, /cap/release-notes, /cap/quarantine) delegate to the corresponding API or CLI routes; external capability servers are the sandbox-callable ones CapServers holds for the attempt or CI job (capserver.go).

func (*GitProxy) ServeGitSignHTTP

func (p *GitProxy) ServeGitSignHTTP(w http.ResponseWriter, r *http.Request)

ServeGitSignHTTP handles POST /_grain/git-sign (and /git-sign), signing a git commit or tag payload on the host for a sandbox.

The signature is the host account owner's, so it is handed out only to a sandbox that could already push as that owner: the sandbox must have a target repository (sandboxTargetRepo), the authorizer must let it push there (git-receive-pack), and the credential resolveCredential picks for that repository must be an ambient one with an SSH signing key. A sandbox granted no repository, or only read access, gets 403 -- there is no fallback to some other credential, because a signature minted for a sandbox that may push nowhere is a verified object it can carry anywhere. The payload must look like the commit or tag object git asks to have signed (validGitSignPayload), so the oracle signs nothing git would not.

func (*GitProxy) ServeNamespaceHTTP

func (p *GitProxy) ServeNamespaceHTTP(w http.ResponseWriter, r *http.Request)

ServeNamespaceHTTP handles a GET or HEAD request under /fs/<scheme>/<path>, authenticating with the sandbox's proxy token and enforcing the live task's namespace scope before delegating to p.Namespace.ServeHTTP.

type GitRequest

type GitRequest struct {
	Owner  string
	Repo   string
	Action string // "info/refs", "git-upload-pack", or "git-receive-pack"
	// Host is the git host the path named, as written, or empty for the
	// old /owner/repo form, which means the default host. HandleRequest
	// normalizes it, and empties it for the default host, before
	// anything else reads it.
	Host string
}

GitRequest is one of the four legal smart-HTTP paths, decomposed.

func ParsePath

func ParsePath(path string) (GitRequest, bool)

ParsePath matches path against the four legal smart-HTTP shapes. The second return is false if it isn't one of them.

func (GitRequest) ScopeOwner

func (r GitRequest) ScopeOwner() string

ScopeOwner is the owner a request is authorized against: Owner, or host/Owner off the default host -- model.RepoRef.StoredOwner's form, so an Authorizer comparing it with a scope's RepoRefs keeps two hosts' owner/repo apart without an interface of its own for the host.

type Grant

type Grant struct {
	Sandbox string    `json:"sandbox,omitempty"`
	TaskID  string    `json:"taskId,omitempty"`
	Attempt int       `json:"attempt,omitempty"`
	Token   string    `json:"token"`
	Expires time.Time `json:"expires,omitempty"`
}

Grant is a per-attempt sandbox credential issued for one sandbox run. When TaskID and Attempt are bound at token issuance, the proxy refuses the token if the sandbox is later running a different task or a newer attempt.

type HostCredentialOverrideLookup

type HostCredentialOverrideLookup interface {
	GitCredentialOverrideOn(ctx context.Context, sandbox, host, owner, repo string) (name string, ok bool, err error)
}

HostCredentialOverrideLookup is CredentialOverrideLookup for a repository on a git host, empty meaning the default host (model.Store.GitCredentialOverrideOn). Optional: a lookup without it answers the default host only, and a request for any other host is refused rather than resolved as if it were on the default one.

type HostGitClient

type HostGitClient struct {
	Hostd hostd.Client
	// Stderr receives the server's diagnostics; nil discards them.
	Stderr io.Writer
	// contains filtered or unexported fields
}

HostGitClient is the daemon's side of host-git: every ambient source's tool runs through it once UseHostGit has installed one.

type HostTeamCredentialLookup

type HostTeamCredentialLookup interface {
	TeamGitCredentialOn(ctx context.Context, team, host, owner, repo string) (string, error)
}

HostTeamCredentialLookup is TeamCredentialLookup for a repository on a git host, empty meaning the default host (model.Store.TeamGitCredentialOn), optional the way HostCredentialOverrideLookup is.

type HostTeamCredentials

type HostTeamCredentials interface {
	TeamGitCredentialOn(ctx context.Context, team, host, owner, repo string) (string, error)
}

HostTeamCredentials is TeamCredentials for a repository on a git host other than the deployment's default -- model.Store.TeamGitCredentialOn. Refusal asks it for a repository named with its host, so the team's connection on that host is the one checked, not its default host's.

type LocalRepository

type LocalRepository struct {
	Owner   string
	Name    string
	Dir     string
	Enabled func() bool
}

LocalRepository is a repository the grain controller owns on its own disk -- grain's state repository -- served through git http-backend instead of being forwarded to GitHub. Owner and Name are its stable alias and Dir its checkout. It is the only repository served locally: the per-team grain/config-<team> repositories that used to be served beside it are gone (RetiredConfigRepo).

func (*LocalRepository) DisabledFor

func (r *LocalRepository) DisabledFor(owner, name string) bool

DisabledFor reports whether (owner, name) names this local repository while local hosting is disabled (for example, when an external configuration repository is configured). Checked ahead of authorization and upstream forwarding so a disabled local alias is refused outright rather than forwarded to a forge's grain/ owner.

func (*LocalRepository) Forward

func (r *LocalRepository) Forward(method, action, query string, headers map[string]string, body []byte) (UpstreamResponse, error)

Forward is ForwardRepo for the repository's own alias.

func (*LocalRepository) ForwardRepo

func (r *LocalRepository) ForwardRepo(owner, name, method, action, query string, headers map[string]string, body []byte) (UpstreamResponse, error)

ForwardRepo answers one smart-HTTP request for (owner, name) by running git http-backend against its directory under receiveHardening. The caller has already authorized the request.

func (*LocalRepository) ForwardRepoStream

func (r *LocalRepository) ForwardRepoStream(owner, name, method, action, query string, headers map[string]string, body io.Reader, contentLength int64) (UpstreamResponse, error)

ForwardRepoStream answers one smart-HTTP request for (owner, name) reading the request body from reader.

func (*LocalRepository) Matches

func (r *LocalRepository) Matches(owner, name string) bool

Matches reports whether (owner, name) is served locally: the alias, compared case-insensitively as GitHub compares names.

type LoginRedirectError

type LoginRedirectError struct {
	// Host is the host the request was for.
	Host string
	// Location is where the front end sent it.
	Location string
	// Fix is authfix.ClassifyRedirect's verdict on Location.
	Fix authfix.Fix
	// Redirected is set when the front end answered with the redirect
	// itself, rather than a command-line tool reporting the login page
	// it ended up on (CommandForge.LoginPage). A front end that redirects
	// to its login is asking for a login only a person renews, so the
	// request is not tried again (CommandForgeTransport.RoundTrip).
	Redirected bool
}

LoginRedirectError is a request to a forge that was answered with a login page rather than by the forge: a front end in the way wants a login of the workstation's own (one authfix.RegisterRedirect knows), and what fixes it is what that classifier says, run as the account grain runs as -- nothing about the git credential.

func AsLoginRedirect

func AsLoginRedirect(err error) (*LoginRedirectError, bool)

AsLoginRedirect is err's LoginRedirectError, if it carries one.

func NewLoginRedirect

func NewLoginRedirect(host, location string) (*LoginRedirectError, bool)

NewLoginRedirect is the LoginRedirectError for a request to host sent to location, when location is a login page a registered classifier knows (authfix.ClassifyRedirect); ok is false for any other address, which is an ordinary redirect.

func (*LoginRedirectError) Error

func (e *LoginRedirectError) Error() string

type MigratedFile

type MigratedFile struct {
	Name string // credential name
	File string // the file's path before it was renamed to File+MigratedSuffix
}

MigratedFile is one credential file MigrateFilesToStore moved.

type MintFailure

type MintFailure struct {
	// Time is when the mint was attempted, by the CredentialSet's own
	// clock (CredentialSet.Now).
	Time time.Time
	// Status is what GitHub answered the token exchange with, and 0 when
	// the exchange never got an answer at all -- a key that would not
	// sign, a name that would not resolve, a body that would not parse.
	Status int
	// Message is what to tell a human: GitHub's own sentence when the
	// response carried one (a suspended installation answers
	// {"message":"This installation has been suspended"}), and this
	// package's own error text otherwise. Empty when neither was fit to
	// repeat.
	//
	// Already reduced to a short, single-line, plain-text string by
	// shortMessage below, because these are somebody else's bytes and
	// they end up in a git "remote:" line, in a JSON API response and on
	// a settings pane.
	Message string
	// NoExchange marks a failure decided before any token exchange was
	// attempted (a credential on a host with no App API, appTransportFor), whose Message is the
	// whole reason rather than something GitHub or the exchange said.
	NoExchange bool
}

MintFailure is one failed attempt to turn an App credential into an installation access token, kept rather than discarded so the failure can be *shown* to somebody.

load serves a credential it cannot mint a token for anonymously -- deliberately, so a public repo goes on being readable through a transient failure -- and until this type existed that decision was visible nowhere but the daemon's own log (grain/task-158). A private repo answered 401 to the unauthenticated request and the sandbox's git said "Authentication failed"; a public one went on working right up to the first push, which failed with "No anonymous write access"; and the credential's row on Settings -> GitHub read "present" throughout. Every one of those is a sentence about something other than the App installation that actually broke.

The material was always there -- mintInstallationToken returns GitHub's own status and body as a *github.Error -- it was just thrown away at the call site. This is that material, carried on the Credential the failure produced (Credential.MintFailure) and so reaching everything that already handles one: the proxy's refusal messages, the named-token capability check, and the Settings pane.

func (MintFailure) Describe

func (f MintFailure) Describe() string

Describe is the failure as one clause, for a sentence that has already named the credential it is about.

type ModelAuthorizer

type ModelAuthorizer struct {
	Store ScopeLookup
	// Forbidden names repos no sandbox may reach through this proxy, in
	// any way, whatever its task scope says -- checked before the scope
	// is even read, so being a task's own Target does not get past it.
	//
	// It exists for one repository: grain's own state (pkg/staterepo)
	// when that repository holds, or has ever held, the encrypted
	// secrets file. Dispatching a task at the state repository is a
	// supported and intended thing to do -- it is how a settings change
	// becomes a pull request -- but authorization here is per repository
	// and cannot be anything else: this proxy streams a packfile it does
	// not parse, so a sandbox allowed to fetch a repository is a sandbox
	// that gets every object in it, including a file deleted long ago.
	// A state repository written by a build that kept secrets.enc in it
	// is therefore one no sandbox may clone, and saying so here is the
	// only place that can be enforced. cmd/grain's startGitProxy decides
	// which repo, if any, that is; see staterepo.Repo.HasSecrets.
	//
	// A holder rather than a slice because which repository that is can
	// change under a running proxy: adopting a state repository points
	// the installation at a different one without a restart, so the
	// answer is re-read into this set rather than baked in at startup
	// (ForbiddenSet's own doc comment). Nil forbids nothing.
	Forbidden *ForbiddenSet

	// Branches resolves the one branch a sandbox may push
	// (AuthorizeRefUpdates). Nil reads it from Store when Store can
	// answer, as model.Store does; with neither, every push is refused.
	Branches BranchLookup
}

ModelAuthorizer is the Authorizer backed by the live task model.

func (*ModelAuthorizer) Authorize

func (a *ModelAuthorizer) Authorize(ctx context.Context, sandbox, owner, repo, action string) (bool, error)

Authorize reports whether sandbox may perform action against owner/repo. git-receive-pack (push) is allowed against the run's own write target or any of its task's granted write targets (Writes) -- and then, in every one of them, only to its own branch (AuthorizeRefUpdates, which Handle asks once the push's command list is in hand). A push's info/refs advertisement (?service=git-receive-pack) arrives here as "git-receive-pack" too: HandleRequest authorizes it as the push it opens (isPush). Every other action (info/refs, git-upload-pack) is allowed against that target or any Reads or Writes entry.

func (*ModelAuthorizer) AuthorizeRefUpdates

func (a *ModelAuthorizer) AuthorizeRefUpdates(ctx context.Context, sandbox, owner, repo string, updates []RefUpdate) (string, error)

AuthorizeRefUpdates implements RefAuthorizer: every update must be to refs/heads/<the run's own branch>, in whichever repository it may push to -- its target or any Writes entry alike. Creating, moving, force-moving and deleting that one branch are all its own business -- except for a run whose branch is another task's, which may only fast-forward it (refuseBorrowedBranchRewrite). Every other ref is refused, the default branch and the Writes entries' base branches included, unless one of two things says otherwise:

  • the `push:` list of the repository-declared template the run's task was filed from (DeclaredPushLookup, grain/task-2536), for refs of that same repository -- with a deletion allowed only where the matching entry says `delete: true`, and a tag moved or a branch moved anywhere the pack does not show is a fast-forward only where it says `force: true`;
  • model.GitPushAnyRefGrant, the https://grain.dev/capabilities/repo#write grant formerly named git-push-any-ref (AnyRefLookup), a team grant for ad-hoc work.

No team policy and no admin grant sits behind either: the team's own git credential, which every push is forwarded with, is the only other bound.

A push it lets through that fast-forwards a borrowed branch is recorded against the run's task (recordBorrowedPushes) before it is forwarded.

func (*ModelAuthorizer) Refusal

func (a *ModelAuthorizer) Refusal(owner, repo string) (string, bool)

Refusal implements Refuser: it is how the denial above reaches the caller as an explanation rather than as the generic "not in scope" every other refusal gets.

func (*ModelAuthorizer) RemovedReason

func (a *ModelAuthorizer) RemovedReason(ctx context.Context, sandbox, owner, repo string) (string, bool)

RemovedReason implements RemovalExplainer: the refusal Authorize gave sandbox for owner/repo, when it gave it because the repository came off the deployment's list.

type NamespaceScopeLookup

type NamespaceScopeLookup interface {
	SandboxNamespaceScope(ctx context.Context, sandbox string) (model.NamespaceScope, bool, error)
}

NamespaceScopeLookup resolves a sandbox name to the namespace scope of its currently live task run. Implemented by *model.Store.

type NullAuditLog

type NullAuditLog struct{}

NullAuditLog discards every entry.

func (NullAuditLog) Record

func (NullAuditLog) Record(AuditEntry)

type PackageCredential

type PackageCredential struct {
	// Registry is the registry host, with no scheme and no path.
	Registry string
	// Username is what to log in as -- PackageUsername today, kept a
	// field because it is the registry's convention and not the
	// caller's business to know.
	Username string
	// Token is the material. A GitHub token, with whatever package
	// permission the credential behind it carries: this resolves which
	// credential publishes, and only the registry can say whether that
	// credential is allowed to.
	Token string
	// Name is which ladder credential answered, for a log line or an
	// error that has to say where a refused push got its token from. It
	// is a name, never material.
	Name string
}

PackageCredential is one registry login, ready for `docker login`.

type PackageCredentialSource

type PackageCredentialSource struct {
	// Registry is the default container registry hostname when the caller
	// did not specify one (for example "us-docker.pkg.dev").
	Registry string
	// RegistryEnv, when set, names an environment variable whose non-empty
	// value overrides Registry when the caller did not specify one.
	RegistryEnv string
	// Username is the registry login username beside the token (for example
	// "oauth2accesstoken"). Empty defaults to PackageUsername.
	Username string
	// Command is the executable on PATH; Args follow it.
	Command string
	Args    []string
	// Env is added to the daemon's own environment for the run.
	Env []string
	// LoginFix is the command or instructions that repair a missing login.
	LoginFix string
}

PackageCredentialSource is a host tool that mints a container-registry login for repositories on a forge whose release images do not publish to GitHub Packages (such as a self-hosted forge publishing to a cloud registry). "{host}" anywhere in Args, Env or LoginFix is the forge hostname.

type ProxyAPICallRecorder

type ProxyAPICallRecorder interface {
	RecordProxyAPICall(ctx context.Context, runID, tool, targetIDs string, resultBytes int64) error
}

ProxyAPICallRecorder is an optional extension of ProxyActivityRecorder that records each served proxy call in task_run_api_call. Implemented by *model.Store.

type ProxyActivityRecorder

type ProxyActivityRecorder interface {
	SetTaskActivity(ctx context.Context, taskID, activity string, at time.Time) (live bool, err error)
	RecordProxyToolCall(ctx context.Context, runID, tool string, resultBytes int64, errored bool) error
}

ProxyActivityRecorder is where the proxy reports what a sandbox's live run is doing and what it called. Implemented by *model.Store.

type ProxyResponse

type ProxyResponse struct {
	Status  int
	Headers map[string]string
	Body    []byte
	Stream  io.ReadCloser
}

ProxyResponse is what Handle decided to answer with. Body and Stream are as on UpstreamResponse: a response carrying a Stream is passing an upstream body through unread, and whoever receives it must Close it (WriteResponse does).

func Denial

func Denial(status int, message string) ProxyResponse

Denial is how this proxy refuses one request: an HTTP status, and the reason as plain text.

Plain text, not the ERR pkt-line this used to send. A git client only parses pkt-lines out of a *200* response carrying a git content type; against the 401/403/500 a refusal is, it falls back to printing the body verbatim as "remote: " lines, so the pkt-line's own 4-hex length prefix ended up in front of the sentence an operator reads:

remote: 00c6ERR no credential configured for owner/repo -- ...

which is what the first clone of a deployment with no GitHub credential yet actually printed (found by hand, task 244). The Content-Type is explicit for the same reason: git only shows the body at all when it is told the body is text.

type Reach

type Reach struct {
	Credentials *CredentialSet
	API         github.Transport
	// Host is the git host API is the REST API of (the daemon's
	// -github-host). A credential recorded on any other host is never
	// listed against API: its token is that host's, not this one's.
	// Empty checks only the kind (a plain git host is never listed).
	Host string
	// Transports maps non-default git hosts to their github.Transport,
	// allowing Reach to talk to GitHub Enterprise instances.
	Transports map[string]github.Transport
	// TTL is how long a listing is kept; zero is DefaultReachTTL.
	TTL time.Duration
	// Now is the clock; nil is time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

Reach lists, and caches, the repositories each credential in Credentials can reach, through API (the GitHub REST API). The zero value is not usable; a nil *Reach answers every question "unknown".

func (*Reach) Check

func (r *Reach) Check(name, owner, repo string, push bool) (Reachability, error)

Check is whether credential name can reach owner/repo -- push access when push is true, read otherwise.

func (*Reach) Refusal

func (r *Reach) Refusal(ctx context.Context, teams TeamCredentials, team string, target *model.RepoRef,
	reads []model.RepoRef, writes []model.WriteTarget) (string, error)

Refusal is the sentence a task is refused (or parked) with when its team's credential cannot reach one of the repositories it names -- push for its target and every extra write, read for every read -- and "" when it can, or when nothing can say: a nil Reach, a listing GitHub would not give, a config repository the controller serves itself. Unknown never refuses; the dispatch-side stop (orchestrator.stopOnAccessRefused) is still there behind it.

func (*Reach) Repos

func (r *Reach) Repos(name string) ([]ReachableRepo, bool, error)

Repos is the list of repositories credential name reaches, and false when no list can be had: no API to ask, no such credential, an anonymous one, or GitHub refusing or failing the listing -- each of which err says, for a caller that wants to report it.

func (*Reach) ReposForHost

func (r *Reach) ReposForHost(name, host string) ([]ReachableRepo, bool, error)

ReposForHost is the list of repositories credential name reaches on host, and false when no list can be had: no API to ask, no such credential, an anonymous one, or GitHub refusing or failing the listing.

func (*Reach) TaskRefusal

func (r *Reach) TaskRefusal(ctx context.Context, teams TeamCredentials, task model.Task) (string, error)

TaskRefusal is Refusal for a task already stored: its own target, reads and writes.

type Reachability

type Reachability int

Reachability is what Check concludes about one repository.

const (
	// ReachUnknown is every answer Check cannot vouch for: no listing
	// available (no API, an anonymous credential, GitHub erroring), or a
	// listing too long to have been read to the end. A caller refuses
	// nothing on it.
	ReachUnknown Reachability = iota
	// Reachable: the credential can do what was asked.
	Reachable
	// Unreachable: GitHub listed what the credential reaches and the
	// repository is not on it, or is on it without the push asked for.
	Unreachable
)

type ReachableRepo

type ReachableRepo struct {
	Repo string `json:"repo"`
	Push bool   `json:"push"`
}

ReachableRepo is one repository a credential can reach, as GitHub spells it, and whether the credential may push there.

type ReadOnlyScopeAuthorizer

type ReadOnlyScopeAuthorizer struct {
	// Scopes is the read-only registry. nil grants nothing.
	Scopes *ReadScopes
	// WriteScopes is the write registry. nil grants nothing.
	WriteScopes *WriteScopes
	// Next is consulted for everything Scopes does not allow. Required.
	Next Authorizer
	// Forbidden is the set of repos no sandbox may reach at all, checked
	// before Scopes -- so a read grant cannot be the thing that gets a
	// CI job into the one repository this proxy refuses to everybody
	// (ModelAuthorizer.Forbidden). GitProxy.Handle already refuses those
	// through Refusal below, before Authorize is ever called; this is
	// the same answer given again where the decision is actually made,
	// so that a caller wiring this by hand cannot end up with a scope
	// that outranks the refusal.
	Forbidden *ForbiddenSet
}

ReadOnlyScopeAuthorizer answers from a ReadScopes registry first and falls through to Next -- the model-backed authorizer, in a deployment -- for every sandbox that holds no read grant.

That order is deliberate and costs nothing: a CI sandbox has no live run behind it, so asking the model about it is a store read that can only ever answer "nothing". The ordinary case (an agent run's sandbox) reaches Next after one map lookup.

func (*ReadOnlyScopeAuthorizer) Authorize

func (a *ReadOnlyScopeAuthorizer) Authorize(ctx context.Context, sandbox, owner, repo, action string) (bool, error)

Authorize implements Authorizer.

func (*ReadOnlyScopeAuthorizer) AuthorizeRefUpdates

func (a *ReadOnlyScopeAuthorizer) AuthorizeRefUpdates(ctx context.Context, sandbox, owner, repo string, updates []RefUpdate) (string, error)

AuthorizeRefUpdates implements RefAuthorizer. It has to: Handle only checks a push's refs when its Authorizer is a RefAuthorizer, and this wrapper is the Authorizer every deployment runs (BuildProxy puts it in front of ModelAuthorizer whenever a scope registry is wired), so a wrapper without this method switched the whole check off.

A CI job holding a write grant for owner/repo may update the refs of it CIRefUpdates allows: repo-write is that job's own declaration, to a workflow whose job is to push (docs/ci-capabilities.md), and that job has no task branch to be held to. Every other sandbox is answered by Next -- an agent run's, held to its own task branch -- and a Next that decides no refs refuses rather than allows.

func (*ReadOnlyScopeAuthorizer) Refusal

func (a *ReadOnlyScopeAuthorizer) Refusal(owner, repo string) (string, bool)

Refusal implements Refuser by passing the question straight on to Next where Next answers it at all. A wrapper that swallowed it would turn the one refusal this proxy explains into the generic "not in scope", which is exactly the confusion ForbiddenReason exists to prevent.

func (*ReadOnlyScopeAuthorizer) RemovedReason

func (a *ReadOnlyScopeAuthorizer) RemovedReason(ctx context.Context, sandbox, owner, repo string) (string, bool)

RemovedReason implements RemovalExplainer by passing the question on to Next, as Refusal does.

func (*ReadOnlyScopeAuthorizer) WithheldReason

func (a *ReadOnlyScopeAuthorizer) WithheldReason(sandbox, owner, repo string) (string, bool)

WithheldReason reports why a request that Authorize refused was withheld by the CI event gate on a grant sandbox declared, if WriteScopes recorded one.

type ReadScopes

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

ReadScopes is the registry: which sandbox may fetch which repositories, as it stands right now.

Every method is safe on a nil *ReadScopes, which reads as an empty registry -- a proxy wired up without one grants nothing this way, and a CI service that was handed none grants nothing either. Both are fail-closed: the grant is missing, so the fetch is refused, rather than the fetch being allowed by something that was never asked.

func NewReadScopes

func NewReadScopes() *ReadScopes

NewReadScopes returns an empty registry, ready for a CI service to grant into and a proxy to read from at the same time.

func (*ReadScopes) Drop

func (s *ReadScopes) Drop(sandbox string)

Drop forgets all grants for sandbox. Called as the job's sandbox is released, success or failure alike, and safe to call for a sandbox that has none -- a job that failed before it was granted anything has nothing to drop, and dropping twice is what a retried cleanup does.

func (*ReadScopes) Grant

func (s *ReadScopes) Grant(sandbox string, repo model.RepoRef)

Grant records that sandbox may fetch repo, and nothing else. Called as a CI job's sandbox is built, before anything in it runs git.

Granting multiple times for one sandbox adds to its allowed set.

func (*ReadScopes) Len

func (s *ReadScopes) Len() int

Len is how many sandboxes hold a grant right now -- for a test, and for anything that wants to say how many CI jobs are in flight.

func (*ReadScopes) Repo

func (s *ReadScopes) Repo(sandbox string) (model.RepoRef, bool)

Repo returns one of the repositories sandbox may fetch, and false where it may fetch none.

func (*ReadScopes) Repos

func (s *ReadScopes) Repos(sandbox string) []model.RepoRef

Repos returns all repositories sandbox may fetch.

type RealForwarder

type RealForwarder struct {
	Host   string
	UseTLS bool
	Client *http.Client
	// Username, when set, is sent as the Basic auth username with the
	// token as its password -- what git itself sends for a login its
	// credential helper answered with a username, and what a plain git
	// host behind ordinary basic auth checks. Empty is GitHub's
	// convention below.
	Username string
}

RealForwarder talks to a git smart-HTTP endpoint over HTTPS by default. UseTLS false is the git-transport half of the mock-GitHub test seam: it lets a live test point a real GitProxy's forward target at a local stand-in server instead of github.com.

Client, when set, is used for the request, but its CheckRedirect is always replaced by one that refuses to follow anything; when nil, defaultForwardClient is used.

func (*RealForwarder) Forward

func (f *RealForwarder) Forward(method, path, query string, headers map[string]string, body []byte, token *string) (UpstreamResponse, error)

Forward sends the request to Host, with token (when non-nil) as Basic auth, and returns the response with its body as Stream, unread.

func (*RealForwarder) ForwardStream

func (f *RealForwarder) ForwardStream(method, path, query string, headers map[string]string, body io.Reader, contentLength int64, token *string) (UpstreamResponse, error)

ForwardStream sends the request to Host reading body from reader with the given contentLength (-1 if unknown).

type RecordingAuditLog

type RecordingAuditLog struct {
	Entries []AuditEntry
}

RecordingAuditLog collects entries in memory. For tests.

func (*RecordingAuditLog) Record

func (l *RecordingAuditLog) Record(entry AuditEntry)

type RefAuthorizer

type RefAuthorizer interface {
	// AuthorizeRefUpdates returns a non-empty reason when sandbox may not
	// make updates to owner/repo. The reason is returned to the caller.
	AuthorizeRefUpdates(ctx context.Context, sandbox, owner, repo string, updates []RefUpdate) (reason string, err error)
}

RefAuthorizer is an Authorizer that also decides which refs a push may update. Optional, like Refuser: Handle asks for it and carries on without it, so a test stub need not implement it. ModelAuthorizer does.

type RefGrant

type RefGrant struct {
	Ref string
	// Kind is "create", "update", "force" or "delete".
	Kind string
	// Via is "declared push" or the capability's name.
	Via         string
	TaskID      string
	TemplateID  string
	Declaration string
}

RefGrant is one update of a ref other than the run's own branch that AuthorizeRefUpdates let through, and on whose say-so -- what the audit log records for it (GitProxy.refuseRefUpdates).

type RefUpdate

type RefUpdate struct {
	Old, New, Ref string
}

RefUpdate is one command of a push: move Ref from Old to New. An all-zero New deletes Ref; an all-zero Old creates it.

func ParseReceivePackCommands

func ParseReceivePackCommands(body []byte) ([]RefUpdate, error)

ParseReceivePackCommands reads the command list at the start of a git-receive-pack request body: any shallow lines, then one command per pkt-line up to the flush-pkt that ends the list. Anything else -- a truncated list, a malformed command, a signed push's certificate, which carries its commands inside the certificate -- is an error, and the caller refuses the push.

type Refuser

type Refuser interface {
	Refusal(owner, repo string) (reason string, refused bool)
}

Refuser is an Authorizer that refuses some repos to every sandbox and can say why. Optional: Handle asks for it and carries on without it, so a test stub or a future Authorizer that has no such repos need not implement anything. ModelAuthorizer does, for the one repo that has to be refused this way -- grain's own state, when it holds the encrypted secrets file.

type RemovalExplainer

type RemovalExplainer interface {
	RemovedReason(ctx context.Context, sandbox, owner, repo string) (string, bool)
}

RemovalExplainer is an Authorizer that can say a refusal was because the repository was removed from the deployment while the run asking was live (ModelAuthorizer.RemovedReason). Optional, as Refuser is.

type RevertInfo

type RevertInfo struct {
	Task        string `json:"task"`
	Title       string `json:"title,omitempty"`
	Repo        string `json:"repo,omitempty"`
	Branch      string `json:"branch,omitempty"`
	PullRequest string `json:"pull_request,omitempty"`
}

RevertInfo is what grain git revert needs to find a task's work in the sandbox's own history: the branch it was pushed on (the merge commit names it) and the pull request it was opened as, if any.

type ReviewedBranchPushRecorder

type ReviewedBranchPushRecorder interface {
	RecordReviewedBranchPush(ctx context.Context, sandbox, old, new string) error
}

ReviewedBranchPushRecorder is the optional half of BranchLookup that records each fast-forward of a borrowed branch a sandbox's live run was let through (model.Store.RecordReviewedBranchPush): what tells a review's own commits on the change it reviews from one a person pushed to the same branch from outside grain meanwhile. A lookup that does not implement it records nothing, and the review is credited with no push.

type RouteActivity

type RouteActivity struct {
	// Tool is the canonical tool name recorded in task_run_tool.
	Tool string
	// Phrase is the run's activity row while the request is served.
	Phrase string
	// Targets are the task or CI run IDs touched by the request, recorded in
	// task_run_api_call.
	Targets []string
}

RouteActivity is what one proxy request is, in the terms of the MCP tool it replaces.

func CLIRouteActivity

func CLIRouteActivity(path string) RouteActivity

CLIRouteActivity names a /cli/<route> request after the MCP tool it stands in for.

func NamespaceRouteActivity

func NamespaceRouteActivity(path string, query url.Values) RouteActivity

NamespaceRouteActivity names a /fs/<scheme>/<path> request after the MCP tool it stands in for.

type SSHCredential

type SSHCredential struct {
	// Host is the normalized git host the key is for.
	Host string
	// Addr is the host:port dialled.
	Addr string
	// User is the SSH login, "git" unless the file says otherwise.
	User string
	// PathPrefix is put before owner/repo.git in the remote command, for
	// a server whose repositories are not at the login's root.
	PathPrefix string
	// APICredential names the PAT or App credential REST calls for this
	// credential's repositories use instead, "" when there is none.
	APICredential string
	// contains filtered or unexported fields
}

SSHCredential is a loaded SSH key credential: everything a request needs to run git-upload-pack or git-receive-pack on its host.

type SSHKeyFile

type SSHKeyFile struct {
	Host          string `json:"host"`
	Port          int    `json:"port,omitempty"`
	User          string `json:"user,omitempty"`
	PrivateKey    string `json:"private_key"`
	Passphrase    string `json:"passphrase,omitempty"`
	KnownHosts    string `json:"known_hosts,omitempty"`
	PathPrefix    string `json:"path_prefix,omitempty"`
	APICredential string `json:"api_credential,omitempty"`
}

SSHKeyFile is <name>.ssh.json as written and read.

type SSHKeyInfo

type SSHKeyInfo struct {
	Host          string `json:"host"`
	User          string `json:"user"`
	Fingerprint   string `json:"fingerprint"`
	APICredential string `json:"apiCredential,omitempty"`
	Error         string `json:"error,omitempty"`
}

SSHKeyInfo is what may be said about name's SSH key without its material: the host, login and fingerprint, and the paired API credential. ok is false when name is not an SSH credential.

type SandboxTeams

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

SandboxTeams is the registry of which team a CI job's sandbox runs as, for the jobs whose repository access is the team's to give (grain/task-1654).

A job that declares `repo-read:` or `repo-write:` in its own workflow file has said what it needs; the team's GitHub credential is what decides whether it gets it. So such a job's sandbox is registered here for as long as it runs, and every request it makes through the proxy goes out with that team's credential (Store.TeamGitCredential) rather than the deployment's own ladder -- GitHub then refuses whatever the team's token cannot do, which is how a repository's owner decides which teams may reach it. A job that declares neither is not registered and is answered exactly as it was before.

Like the scope registries above, every method is safe on a nil *SandboxTeams, which registers nothing.

func NewSandboxTeams

func NewSandboxTeams() *SandboxTeams

NewSandboxTeams returns an empty registry.

func (*SandboxTeams) Drop

func (s *SandboxTeams) Drop(sandbox string)

Drop forgets sandbox's team.

func (*SandboxTeams) Grant

func (s *SandboxTeams) Grant(sandbox, team string)

Grant records that sandbox's git requests go out as team.

func (*SandboxTeams) Team

func (s *SandboxTeams) Team(sandbox string) (string, bool)

Team is the team sandbox runs as, and false where none is registered.

type SandboxTokenStore

type SandboxTokenStore struct {
	KeyFile string
	Key     *secrets.Key
	TTL     time.Duration
	Now     func() time.Time
	// contains filtered or unexported fields
}

SandboxTokenStore is the write side of the same sandbox-tokens.json file SandboxTokens reads -- called as each run's sandbox is prepared, to mint that sandbox's token (orchestrator's own runOne). Split from SandboxTokens because the two do different things to the same file: the proxy only ever looks tokens up, caching what it has read, while minting one is a read-modify-write against the file the proxy trusts.

func NewSandboxTokenStore

func NewSandboxTokenStore(path string) *SandboxTokenStore

NewSandboxTokenStore returns a SandboxTokenStore writing the token file at path.

func (*SandboxTokenStore) EnsureGrant

func (s *SandboxTokenStore) EnsureGrant(sandbox, taskID string, attempt int) (string, error)

EnsureGrant returns the sandbox's token bound to (taskID, attempt), reusing an unexpired token only when its bound TaskID and Attempt match (or were unbound), and minting a fresh token when the sandbox is starting a different task or attempt.

func (*SandboxTokenStore) EnsureToken

func (s *SandboxTokenStore) EnsureToken(sandbox string) (string, error)

EnsureToken returns the sandbox's existing token if valid, or a freshly minted one recorded to disk. Idempotent per sandbox name, and safe to call from several goroutines at once -- see the type's own doc comment.

func (*SandboxTokenStore) Issue

func (s *SandboxTokenStore) Issue(sandbox, taskID string, attempt int) (Grant, error)

Issue mints or reuses a per-attempt sandbox token Grant bound to (sandbox, taskID, attempt).

func (*SandboxTokenStore) RefreshToken

func (s *SandboxTokenStore) RefreshToken(sandbox string) (string, error)

RefreshToken extends the sandbox's token to now + TTL and returns it -- the orchestrator's own keepSandboxTokenFresh, on a timer, for as long as the run on that sandbox is live, so a run that outlives the TTL keeps its git access. The TTL stays the backstop for a token whose Revoke never comes (the daemon dying mid-run): nothing refreshes that one.

A token already past its expiry is extended all the same, since the sandbox still holds it and whoever is refreshing it says its run is live. A sandbox with no token is ErrNoSandboxToken rather than a fresh mint: a new token is one the sandbox's credential helper has never been given, and minting one here would also resurrect an entry Revoke just dropped.

func (*SandboxTokenStore) Revoke

func (s *SandboxTokenStore) Revoke(sandbox string) error

Revoke drops a sandbox's token, so this file holds one entry per sandbox that still exists rather than one per run the deployment has ever dispatched.

func (*SandboxTokenStore) Rotate

func (s *SandboxTokenStore) Rotate(sandbox string) (string, error)

Rotate mints and records a fresh token unconditionally, replacing any existing one.

type SandboxTokens

type SandboxTokens struct {
	KeyFile string
	Key     *secrets.Key
	Now     func() time.Time
	// contains filtered or unexported fields
}

SandboxTokens maps a bearer token to the sandbox it identifies.

File format: encrypted JSON containing {"sandbox-0": {"token": "<token>", "expires": "<time>"}, ...}, or legacy plaintext JSON, minted as each sandbox is created -- see docs/design.md, "sandbox identity."

It re-reads that file when it is shown a token it does not recognise and the file has changed since it last read it. That used to be unnecessary and was deliberately not done: every sandbox was a slot, every slot's token was minted before the proxy started, and the map could be read once and then treated as fixed for the life of the process. A sandbox created per run mints its token while the proxy is already serving, so a map pinned at startup would reject every git operation from every run -- fail-closed, but closed against everything.

Re-reading when the file has changed rather than on every request keeps the ordinary path an os.Stat and a map lookup with no read/decrypt I/O. It re-reads only when the file has changed since it was last read: an os.Stat, outside the lock, compared with the stat of the file that read came from (tokenFileVersion). Without that, every unknown token (or check against a modified file) cost a read and a decryption under the write lock, so a flood of distinct bogus tokens serialized all of the proxy's authentication behind file I/O; with it, the flood costs one stat each and no reads, while a revoked token or freshly minted token reloads immediately as soon as the file changes. A token that is unknown because it is new or revoked is never missed: the store writes by rename (SandboxTokenStore.save), so the minting or revoking write replaces the file the stat describes, and tokenFileVersion says when a stat alone cannot be trusted to show that.

func LoadSandboxTokens

func LoadSandboxTokens(path string) (*SandboxTokens, error)

LoadSandboxTokens reads the token map from path. A missing file yields an empty map, matching the Python original: the git-proxy service can be enabled before any sandbox has ever minted a token.

func (*SandboxTokens) Authenticate

func (t *SandboxTokens) Authenticate(token string) (string, bool)

Authenticate returns the sandbox name owning this token, and false if it is unknown or expired -- unknown meaning "not in the file as of just now," since a miss against the cached map (or a cached hit whose backing file has changed since it was read) re-reads the file before answering whenever it has changed since it was last read (see the type's own doc comment).

func (*SandboxTokens) AuthenticateGrant

func (t *SandboxTokens) AuthenticateGrant(token string) (Grant, bool)

AuthenticateGrant returns the full Grant owning this token (including any bound TaskID and Attempt), and false if the token is unknown or expired.

type ScopeLookup

type ScopeLookup interface {
	GitScope(ctx context.Context, sandbox string) (*model.RepoRef, []model.RepoRef, []model.RepoRef, error)
}

ScopeLookup resolves a sandbox to the write target its live run was dispatched against, the repos it may fetch but never push, and the repos it may push to. model.Store implements this today via GitScope; a test supplies a stub instead.

type ServerGitRemote

type ServerGitRemote struct {
	URL string
	// contains filtered or unexported fields
}

ServerGitRemote is the remote a git command grain runs on this host itself -- not a sandbox's, which reaches its repository through the git proxy -- names for a repository only its host's own tool reaches: a forge behind a front end, where plain `git clone https://<host>/...` is redirected to a login page (AmbientCommandSource.ForgeViaCommand).

The route is the one the proxy's own upstream hop takes for that host (GitProxy.forwarderFor): every smart-HTTP request is one `<tool> api` run with the whole URL, carrying the credential's token in the shape the source says its git endpoints take (CommandForgeTransport.args). git cannot speak through a Go RoundTripper, so it is handed a loopback URL instead, served by a listener that exists for the one command and forwards only that repository's paths.

URL is what to pass to git in place of https://<host>/<owner>/<repo>.git, and Close stops the listener; both are safe to use on a nil remote, which is the answer for a repository that needs none of this.

func (*ServerGitRemote) Close

func (r *ServerGitRemote) Close()

Close stops the listener. Safe on nil and more than once.

func (*ServerGitRemote) Err

func (r *ServerGitRemote) Err() error

Err returns the first upstream forwarding error seen by this listener, if any.

type TaskRefLookup

type TaskRefLookup interface {
	TaskCIRef(ctx context.Context, taskID string) (repo, branch string, found bool, err error)
}

TaskRefLookup is what a NamespaceScopeLookup also implements to name another task's repository and branch, for /cli/ci/runs?task= and /cli/pr/status?task=. Implemented by *model.Store.

type TeamAuditLog

type TeamAuditLog struct {
	Next AuditLog
	Sink TeamAuditSink
	// SandboxTeams names the team of a CI job's sandbox, which has no
	// task for Sink to attribute it through.
	SandboxTeams *SandboxTeams
}

TeamAuditLog records every entry to Next and, when the request can be charged to a team, to Sink as that team's credential access. An entry with no team behind it -- an unregistered sandbox with no live task -- stays in Next alone.

func (*TeamAuditLog) Record

func (l *TeamAuditLog) Record(entry AuditEntry)

type TeamAuditSink

type TeamAuditSink interface {
	SandboxAuditAttribution(ctx context.Context, sandbox string) (model.AuditAttribution, bool, error)
	RecordCredentialAccess(ctx context.Context, entry model.CredentialAccessEntry) error
}

TeamAuditSink attributes a sandbox to the task, run and team it is working for, and records a credential access against that team. *model.Store implements it.

type TeamCredentialLookup

type TeamCredentialLookup interface {
	TeamGitCredential(ctx context.Context, team, owner, repo string) (string, error)
}

TeamCredentialLookup resolves a team to the named credential it clones and pushes owner/repo with, or an error wrapping model.ErrNoTeamGitCredential when it has none. model.Store implements this via TeamGitCredential. It answers for the CI sandboxes registered in GitProxy.SandboxTeams, which have no task behind them for CredentialOverrideLookup to resolve.

type TeamCredentials

type TeamCredentials interface {
	TeamGitCredential(ctx context.Context, team, owner, repo string) (string, error)
}

TeamCredentials is which named credential a team uses for a repository -- model.Store.TeamGitCredential.

type UpstreamResponse

type UpstreamResponse struct {
	Status  int
	Headers map[string]string
	Body    []byte
	Stream  io.ReadCloser
}

UpstreamResponse is what the forward target answered.

The body is in one of two places. Stream, when set, is the body still being read from the forward target -- which is how the real forwarders answer, so a clone's packfile goes on to the sandbox as it arrives rather than being held whole in the controller's memory -- and whoever receives the response owns it and must Close it. Body is the whole body already in memory, for a response that was built rather than forwarded (FakeForwarder, a test); it is ignored when Stream is set.

func SSHForward

func SSHForward(ctx context.Context, credential Credential, owner, repo, action, query string,
	headers map[string]string, body []byte, maxBody int64) (resp UpstreamResponse, refusal string, err error)

SSHForward runs one smart-HTTP request (action and query as ParsePath and the URL give them) against owner/repo on credential's SSH host. refusal is the remote's own explanation when it would not serve the repository at all (stderr from a session that advertised nothing); err is a failure to reach or trust the host. maxBody bounds an inflated gzip body.

type WriteScopes

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

WriteScopes is the registry of write scopes: which sandbox may push to (and fetch from) which repositories in CI.

Every method is safe on a nil *WriteScopes, which reads as an empty registry.

func NewWriteScopes

func NewWriteScopes() *WriteScopes

NewWriteScopes returns an empty write scope registry.

func (*WriteScopes) Drop

func (s *WriteScopes) Drop(sandbox string)

Drop forgets all write grants and withheld notes for sandbox.

func (*WriteScopes) Grant

func (s *WriteScopes) Grant(sandbox string, repo model.RepoRef)

Grant records that sandbox may push to (and fetch from) repo.

func (*WriteScopes) Len

func (s *WriteScopes) Len() int

Len is how many sandboxes hold a write grant right now.

func (*WriteScopes) NoteWithheld

func (s *WriteScopes) NoteWithheld(sandbox string, repo model.RepoRef, reason string)

NoteWithheld records why sandbox was not handed a declared write grant for repo on this CI event. It grants no git action: Authorize still answers false, and HandleRequest reads the note only when writing its 403 refusal so the job's author can tell an event-gated grant from an undeclared repo.

func (*WriteScopes) Repos

func (s *WriteScopes) Repos(sandbox string) []model.RepoRef

Repos returns all repositories sandbox has write access to.

func (*WriteScopes) WithheldReason

func (s *WriteScopes) WithheldReason(sandbox, owner, repo string) (string, bool)

WithheldReason returns the note recorded by NoteWithheld for sandbox and owner/repo when sandbox holds no active write grant for that repository.

Directories

Path Synopsis
Package gitproxytest is a made-up command-backed ambient source for tests outside pkg/gitproxy: what a registered forge tool looks like to core grain (gitproxy.RegisterAmbientSource), with no real one behind it.
Package gitproxytest is a made-up command-backed ambient source for tests outside pkg/gitproxy: what a registered forge tool looks like to core grain (gitproxy.RegisterAmbientSource), with no real one behind it.

Jump to

Keyboard shortcuts

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