Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ Short commands use `Telemetry.CaptureEvent`, which flushes before exiting. Use `

Never write: narration restating the next line; section headers inside a function; change history; references to plans, tickets, PRs, or reviewers; docstrings restating the signature; commented-out code.

### Agent Vault hooks

A service can have a hook (`packages/agentvault/hook.go`): the customer's server, which the proxy asks before it brokers. Every request to a hooked HTTP or MCP service asks it, in `forward()` after the proxy's own checks (policy, plain-HTTP refusals, tool allowlist) and before substitutions, custom headers and the credential, so the payload only ever holds what the agent sent. A database or SSH service asks once per connection, after `registerNative` and before the tunnel opens. It fails closed: anything but an `allow` or `deny` answer within 3 seconds refuses the request, and a hook Infisical sent that the proxy can't use stays a hook that always fails, never no hook. Keep any new path that attaches a credential behind the same call, and never log the hook URL beyond `scheme://host`.

## Issue and PR guidelines

- Never create a GitHub issue.
Expand Down
39 changes: 24 additions & 15 deletions packages/agentvault/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ type resolvedService struct {
id string
name string
kind string
accessBundleID string
accessBundleName string
// As Infisical sent it, so a credential refresh can name the destination the rejected token went to.
hostPattern string
Expand All @@ -82,6 +83,8 @@ type resolvedService struct {
native *nativeTarget
// Some credential field comes from each member, so a rejection is theirs to fix rather than an admin's.
memberProvided bool
// Asked before the credential is attached. Nil when the service has none.
hook *serviceHook
}

// lastSeen and fetchedAt are wall-clock (Round(0)) so time asleep counts toward the grace and idle windows.
Expand All @@ -92,8 +95,10 @@ type sessionEntry struct {
expiresAt *time.Time
services []*resolvedService
sessionLog *sessionLogGrant
lastSeen time.Time
fetchedAt time.Time
// What a hook is told about the session. Nil from servers that don't send it.
session *api.AgentVaultResolvedSession
lastSeen time.Time
fetchedAt time.Time
// Keyed by service ID. A poll whose resolve began before a swap can return the token that swap replaced,
// so the merge consults this to keep the newer one.
swaps map[string]*credentialSwap
Expand Down Expand Up @@ -245,23 +250,25 @@ func isSessionGone(err error) bool {
}

func (c *sessionCache) get(sessionToken string) ([]*resolvedService, error) {
services, _, err := c.lookup(sessionToken, nil)
return services, err
found, err := c.lookup(sessionToken, nil)
return found.services, err
}

// getAdmitted is get for a caller that rations lookups of tokens it hasn't seen: admit runs only when Infisical
// would be asked, so a known session, or one already refused, never spends from the budget.
func (c *sessionCache) getAdmitted(sessionToken string, admit func() bool) ([]*resolvedService, error) {
services, _, err := c.lookup(sessionToken, admit)
return services, err
found, err := c.lookup(sessionToken, admit)
return found.services, err
}

type cacheLookup struct {
sessionID string
services []*resolvedService
sessionLog *sessionLogGrant
session *api.AgentVaultResolvedSession
}

func (c *sessionCache) lookup(sessionToken string, admit func() bool) ([]*resolvedService, *sessionLogGrant, error) {
func (c *sessionCache) lookup(sessionToken string, admit func() bool) (cacheLookup, error) {
key := sessionKey(sessionToken)

c.mu.Lock()
Expand All @@ -270,22 +277,22 @@ func (c *sessionCache) lookup(sessionToken string, admit func() bool) ([]*resolv
if entry.expiresAt != nil && time.Now().After(*entry.expiresAt) {
c.forgetLocked(key, true)
c.mu.Unlock()
return nil, nil, errSessionGone
return cacheLookup{}, errSessionGone
}
// Past the grace window the entry is a miss, so a stalled refresh loop cannot keep an old credential alive.
if time.Since(entry.fetchedAt) > c.grace() {
c.forgetLocked(key, false)
} else {
entry.lastSeen = time.Now().Round(0)
svcs, grant := entry.services, entry.sessionLog
found := cacheLookup{sessionID: entry.sessionID, services: entry.services, sessionLog: entry.sessionLog, session: entry.session}
c.mu.Unlock()
return svcs, grant, nil
return found, nil
}
}
if refused, ok := c.refused[key]; ok {
if time.Now().Before(refused.until) {
c.mu.Unlock()
return nil, nil, refused.err
return cacheLookup{}, refused.err
}
delete(c.refused, key)
}
Expand Down Expand Up @@ -317,18 +324,18 @@ func (c *sessionCache) lookup(sessionToken string, admit func() bool) ([]*resolv
expiresAt: result.ExpiresAt,
services: result.Services,
sessionLog: result.SessionLog,
session: result.Session,
lastSeen: time.Now().Round(0),
fetchedAt: time.Now().Round(0),
}
c.tokens[key] = sessionToken
c.applyNativeLocked(key, result.Services, result.ExpiresAt)
return cacheLookup{services: result.Services, sessionLog: result.SessionLog}, nil
return cacheLookup{sessionID: result.SessionID, services: result.Services, sessionLog: result.SessionLog, session: result.Session}, nil
})
if err != nil {
return nil, nil, err
return cacheLookup{}, err
}
out := resolved.(cacheLookup)
return out.services, out.sessionLog, nil
return resolved.(cacheLookup), nil
}

func (c *sessionCache) evictIfFullLocked() {
Expand Down Expand Up @@ -440,6 +447,7 @@ func (c *sessionCache) refreshOne(key, token string) {
entry.expiresAt = result.ExpiresAt
entry.services = keepNewerSwaps(entry, result.Services, startGen)
entry.sessionLog = result.SessionLog
entry.session = result.Session
entry.fetchedAt = time.Now().Round(0)
c.applyNativeLocked(key, entry.services, entry.expiresAt)
return
Expand All @@ -451,6 +459,7 @@ func (c *sessionCache) refreshOne(key, token string) {
expiresAt: result.ExpiresAt,
services: result.Services,
sessionLog: result.SessionLog,
session: result.Session,
lastSeen: time.Now().Round(0),
fetchedAt: time.Now().Round(0),
}
Expand Down
35 changes: 35 additions & 0 deletions packages/agentvault/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,3 +399,38 @@ func TestCacheTimesIgnoreTheSleepingClock(t *testing.T) {
t.Fatal("a refresh stamps fetchedAt with a monotonic reading")
}
}

func TestTheSessionAHookIsToldAboutIsKeptAndRefreshed(t *testing.T) {
label := "Nightly refunds"
first := &api.AgentVaultResolvedSession{Label: &label, Actor: api.AgentVaultSessionActor{Type: "machineIdentity", ID: "a-1", Name: "agent"}}
svc := serviceWithSecret("v")
svc.hook = &serviceHook{secret: []byte("s")}
resolver := &stubResolver{result: &resolveResult{SessionID: "s1", Services: []*resolvedService{svc}, Session: first}}
cache := newTestCache(resolver)

found, err := cache.lookup("agv_token", nil)
if err != nil || found.session != first || found.sessionID != "s1" || found.services[0].hook != svc.hook {
t.Fatalf("lookup = %+v, %v", found, err)
}

second := &api.AgentVaultResolvedSession{Actor: api.AgentVaultSessionActor{Type: "user", ID: "u-1", Name: "Ana"}}
resolver.mu.Lock()
resolver.result = &resolveResult{SessionID: "s1", Services: []*resolvedService{svc}, Session: second}
resolver.mu.Unlock()
cache.refresh()
if found, _ := cache.lookup("agv_token", nil); found.session != second {
t.Fatalf("the refresh kept the old session info: %+v", found.session)
}
}

func TestACredentialSwapKeepsThePolledHook(t *testing.T) {
polledHook := &serviceHook{secret: []byte("new")}
polled := &resolvedService{id: "svc-1", hostPattern: "h", credential: oauthToken("stale"), hook: polledHook}
entry := &sessionEntry{swaps: map[string]*credentialSwap{"svc-1": {
installed: oauthToken("fresh"), hostPattern: "h", replaced: map[string]bool{credentialHash(&polled.credential): true}, gen: 2,
}}}
got := keepNewerSwaps(entry, []*resolvedService{polled}, 1)
if string(got[0].credential.value) != "fresh" || got[0].hook != polledHook {
t.Fatalf("merged service = %+v", got[0])
}
}
2 changes: 1 addition & 1 deletion packages/agentvault/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ func (c *ConnectClient) connect(ctx context.Context, service string, probe bool)
}

func refusalOf(resp *http.Response) error {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<10))
message := strings.TrimSpace(string(body))
// The proxy's refusal carries its text in a JSON body; a proxy too old to send one wrote the text itself.
var coded proxyErrorBody
Expand Down
17 changes: 17 additions & 0 deletions packages/agentvault/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,9 +222,20 @@ func writeUncheckedProxyError(w http.ResponseWriter, status int, decision, code,
writeProxyErrorAPIURL(w, status, decision, code, message, false)
}

// Seconds a client waits before retrying a request the hook couldn't answer.
const hookFailedRetryAfter = "5"

// Shared by every refusal writer, so the same code always carries the same headers.
func setRetryAfter(h http.Header, code string) {
if code == errorCodeHookFailed {
h.Set("Retry-After", hookFailedRetryAfter)
}
}

func writeProxyErrorAPIURL(w http.ResponseWriter, status int, decision, code, message string, namesAPIURL bool) {
w.Header().Set(HeaderDecision, decision)
w.Header().Set(HeaderError, code)
setRetryAfter(w.Header(), code)
if apiURL := proxyAPIURL(); apiURL != "" && namesAPIURL {
w.Header().Set(HeaderAPIURL, apiURL)
}
Expand Down Expand Up @@ -270,6 +281,8 @@ const (
errorCodeInfisicalUnreachable = "infisical_unreachable"
errorCodeServiceRefused = "service_refused"
errorCodeTLSRequired = "tls_required"
errorCodeHookDenied = "hook_denied"
errorCodeHookFailed = "hook_failed"
)

var proxyErrorHints = map[string]string{
Expand All @@ -291,4 +304,8 @@ var proxyErrorHints = map[string]string{
"different password or key will not help. " + servicesURLPlaceholder + " lists the session's services and their status.",
errorCodeTLSRequired: "This is the Agent Vault proxy: database and SSH services are reached with infisical agent-vault connect, " +
"which talks to the proxy over TLS.",
errorCodeHookDenied: "This is the Agent Vault proxy, not the API: your organization's hook refused this request. Do what its " +
"message says, including whether to try again.",
errorCodeHookFailed: "This is the Agent Vault proxy, not the API. Try again in a moment; if it keeps failing, an admin has to " +
"check the hook server.",
}
Loading
Loading