feat: Resolve credentials per caller through a resolver seam, with moca's resolver in the moca driver

未关闭
#2,088 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
8/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
活跃
技术栈
go
领域
backend, security

调研方向

This is a design-level change that depends on #2087 and #2086, which are not merged yet, so do not start a patch. Read core/plugins/staticinject/plugin.go for today's credential path, and forwardproxy/tunnel.go between lines 437 and 443, where a CONNECT dials. Done means a new core/credresolve package with Register, Get and a cache, plus the bound-connection rules, passing the conformance cases listed in the issue.

由索引模型根据 Issue 内容生成。

描述

Parent: #2042, step 4 of the build order (#2085 → #2087 → #2086 → #2088 → #2091 → #2089 → #2090). Needs #2087 (Binding, Caller, shared mode) and #2086 (the refusal writer). Replaces #1478 and #1479, which are closed.

Problem

A shared egress proxy must add each caller's own credential for a destination, and open TLS only where that caller has one. Cortex has one credential per host per process, from files, and one interception rule for all callers. moca-egress already does this per caller. Cortex must match it, with no moca code in its core and no new hook on the forward proxy.

Shared contract

This issue adds the credential part of #2042's "Shared contract":

// core/credresolve
type Header struct{ Name, Value string }
type Credential struct {
	Name       string    // for audit lines; never a secret
	Subject    string    // who the credential belongs to, from the lookup reply; for audit only (#2089)
	Port       int       // the destination port it is for, 1-65535
	PathPrefix string    // "/" or a prefix on a "/" boundary
	Headers    []Header  // 1-4 headers, set on a match
	Expires    time.Time // zero: no expiry beyond the cache TTL
}
type Resolver interface {
	// Resolve returns the caller's credentials for host (no port). An empty
	// list with a nil error means "none" (an opaque tunnel), cacheable for ttl.
	// A *Refusal error answers the guest with its status and code, and is not
	// cached. Any other error answers 503 credential_unavailable, and is not cached.
	Resolve(ctx context.Context, c pipeline.Caller, host string) (creds []Credential, ttl time.Duration, err error)
}
type Refusal struct{ Status int; Code string } // implements error; used by #2090 (401)
type Factory func() (Resolver, error)            // reads its settings at the first Get

func Register(name string, f Factory)    // drivers call it in init(), behind their tag
func Get(name string) (*Cache, error)    // ONE cached instance per name per process; an unknown name is a config error
func (c *Cache) Forget(sessionID string) // drop every entry of a session

// core/pipeline, set by a plugin that injected (or found revoked) a credential
func (c *Context) SetCredential(name, subject string, revoked bool)

Today

Read at Cortex main 7f3eec7 and moca main e464dd6 (2026-11-23). Paths are Cortex's unless they say moca.

What Where
Cortex injection static-inject (core/plugins/staticinject/plugin.go): source: secret_dir | mappings (:39), key_by: host | static (:52), an optional placeholder gate (:61), one inject_header (:68). It refuses a credential over plain HTTP with 403 plaintext_credential (:266-275). Its Capabilities() declares no body access (:142-146).
Plugin order rules pipeline.validateCapabilities (core/pipeline/pipeline.go:772) already refuses some orders, for example a reader after a mutator. PluginCapabilities is in core/pipeline/plugin.go.
Cortex interception tlsbridge.Decision.Intercepts(host, port) (core/tlsbridge/decision.go:159): ports[port] && !skip.Match(host), default ports 443 and 8443. Under fail_closed, the default skip list is dropped (:139-141).
Where the forward proxy decides Classify at forwardproxy/bridging.go:31, 52, 55, Intercepts at bridging.go:32 and tunnel.go:476 (failClosed() && Intercepts, the only place that verifies the upstream before the 200). bridgeable → HandlesPort (tunnel.go:388, bridging.go:322-323). The s.TLSBridge != nil gate (about tunnel.go:526). bridgeVerdict's Skip.Contains (:46), Programs.Contains (:62), Trust.OSTrustOnly (:68). bridgeServe's failClosed() at :175, 188, 215, 273, 382: without fail_closed, a failed verify, a client that rejects the CA or a non-TLS peek falls back to an opaque tunnel (:174-182). The transparent listener's sites (transparent.go:79-268) are not reached by a bound request.
How Cortex verifies an upstream verifyUpstream sends a real HEAD https://host through the shared upstream client (bridging.go:117-130). Decrypted requests of every caller share one pooled upstream client, with ForceAttemptHTTP2 (tlsbridge/upstream.go:61). The guest leg offers h2,http/1.1 (tlsbridge/terminator.go:32), and accepts an empty SNI for any host.
Cortex's leaves ECDSA P-256, 24 h, re-minted 1 h before expiry, 1024 hosts (tlsbridge/minter.go:79-88, 159). Differences from moca: NotAfter is ttl + 1 h, one shared leaf key, NotBefore -1 min, no clamp to the CA, and an expired CA only logs a warning (TestMint_WarnsWhenIssuerIsExpiring, minter_test.go:205-232, needs that).
Where a CONNECT dials The DNS and SSRF check, then the dial: between tunnel.go:437 and :443. pctx.DialedAddr is set for CONNECT tunnels (:436).
Capability ceilings plugins.BuildWithDeps reads the unconfigured Capabilities() as the ceiling, and logs a warning when the configured plugin goes above it (core/plugins/deps.go:121, 159-162). WithinCeiling (pipeline/plugin.go:161-176), ceiling_rule_test.go. Configure runs before pipeline.New (deps.go:142-176, pipeline.go:138).
moca's endpoint (phase 1) POST /v1/egress/credential, body {"sandbox": <session>, "host": <host>}, Authorization: Bearer <host token>. Reply {subject, ttlSeconds, credentials: [{name, port, pathPrefix, headers: [{name, value}], expiresAt}]} (moca remote-worker/internal/egress/cpcreds.go:222-283). The subject is kept with each credential (:296). Phase 2 (owed) adds the sandbox token. The harness path (MI1 §6.3) is RFC 8693 and not built. Both are #2090.
moca's client settings MOCA_EGRESS_CREDENTIALS_URL, MOCA_EGRESS_CREDENTIALS_TOKEN_FILE, MOCA_EGRESS_CREDENTIALS_CA, MOCA_EGRESS_CREDENTIALS_TIMEOUT, MOCA_EGRESS_NONE_TTL_S (moca config.go:38-42)
moca's CA settings MOCA_EGRESS_CA_CERT_FILE, MOCA_EGRESS_CA_KEY_FILE, by default $CREDENTIALS_DIRECTORY/egress-ca.crt and egress-ca.key (moca config.go:194-199, NewLeafCA at :234-238). The certificate must be valid now. MOCA_EGRESS_UPSTREAM_CA adds roots to the system roots (:218-231). Other defaults: egress-token, egress-api-ca.crt. moca reads them only when MOCA_EGRESS_CREDENTIALS_URL is set. Cortex's tlsbridge.NewFileSource has no "valid now" check (tlsbridge/ca.go:97-145).
moca's rules, as conformance cases credential_injected_placeholder_overwritten, credential_keyed_by_session, credential_port_scoped, credential_selected_by_path_prefix, credential_sets_every_header, credential_revoked_mid_connection_401, lookup_cached_single_flight, lookup_error_503_no_dial, no_credential_tunnelled_opaque, path_traversal_refused_when_path_scoped, upstream_dropped_after_injection_502, upstream_unverified_502, inner_host_mismatch_421, plaintext_http_credential_403, trace_refused_on_intercepted_conn (moca remote-worker/egress/conformance)
A rule that already exists An inner Host that differs from the CONNECT host gets 421: refuseMisdirected (forwardproxy/tunnel.go:123-153), called at server.go:505
Conformance cases that also need an audit event Most credential cases wait for an audit decision (h.wait(event{"decision": …}) in moca conformance/cases.go): credential_injected, credential_revoked, credential_unavailable, misdirected_request, plaintext_credential, upstream_unverified, and upstream_unreachable after an injection. Cortex writes only tunnel, forward, aborted, conn_cap and request_cap today (vmcontrol/audit.go:15-19). So those cases pass only after #2089.
Prior art for injection Envoy's credential_injector filter: overwrite, allow_request_without_credential, header_value_prefix, a trailing CR/LF trimmed

Change

A. The resolver and its cache
  1. core/credresolve with the contract above. Register and Get follow the plugin registry pattern. Get returns one *Cache per name per process, so the forward proxy and static-inject share one cache and one lookup per key.
  2. The cache, exactly as moca's (moca cpcreds.go:168-219, 285-326):
    • The key is (caller SessionID, host). The caller comes from the binding, never from pctx.SessionID or a header.
    • The TTL comes from the resolver, clamped to 5–300 s, counted from the start of the lookup. It drops to the earliest Expires of the list.
    • A credential with less than 5 s left is dropped. When every credential is dropped, the TTL is 5 s.
    • An empty list is cached for its TTL. A *Refusal and any other error are never cached.
    • At most 4096 entries. When full, first delete expired entries, then evict the entry that expires first.
    • One lookup at a time per key. The lookup runs on its own background context with its own timeout, so a waiter that gives up gets its own ctx.Err() and does not cancel the lookup for the others.
    • Forget(sessionID) drops every entry of a session. The moca driver calls it when the last binding of a session ends (Unregister or dropConn). A secret then stays in memory only while a binding needs it, as Istio's ztunnel holds a pod's credential only while the pod runs on its node.
    • No value appears in a log line, an error or a metric.
B. Interception follows the resolver
  1. Add forwardproxy.Server.Credentials *credresolve.Cache. For a CONNECT with a binding, the forward proxy decides interception itself, after the DNS and SSRF check and before the dial (between tunnel.go:437 and :443):
    • It looks up the caller's credentials for the host, and keeps only the names in Caller.Credentials when that is not nil (D7). When one is left for the CONNECT's port, it intercepts. Otherwise the tunnel stays opaque: no interception and no credential.
    • It ignores every other rule at the sites in the table for a bound request: Classify, Intercepts, HandlesPort, the skip and program sets, OSTrustOnly.
    • A bound, intercepted connection always fails closed, whatever tls_bridge.fail_closed says. A failed verify, a client that rejects the CA, or a non-TLS first byte ends the connection. It is never turned into an opaque tunnel (moca rule I5).
    • A *Refusal answers its status and code, and any other lookup error answers 503 credential_unavailable, through the refusal writer (#2086). Nothing is dialed.
    • Requests without a binding keep tls_bridge's rules unchanged. A laptop sees no change.
  2. TLS rules on a bound, intercepted connection (moca intercept.go, leafca.go). Each rule applies to bound connections only, so laptop and sidecar tests stay as they are (bridgedopen_test.go:329-334 needs h2):
    • Upstream: dial the CONNECT's checked address, and verify the upstream with a TLS handshake on that connection before the guest gets 200 (moca intercept.go:96-115). Send no request to verify. A failure answers 502 upstream_unverified. Use that one HTTP/1.1 connection for the guest connection's decrypted requests, not the shared pooled client. Record its address as the dial address (#2089).
    • Both legs: ALPN http/1.1 only, TLS 1.2 minimum (moca intercept.go:101-103, 124-125). Add an ALPN argument to Terminate.
    • SNI: the guest's SNI must equal the CONNECT host. An empty SNI is allowed only when the CONNECT host is an IP literal (moca intercept.go:160-167). Otherwise fail the handshake, with audit decision misdirected_request.
    • A request-target that is not origin-form (does not start with /) gets 400 bad_request (:273). TRACE and TRACK get 405 bad_request (:280-282).
    • Upgrade is removed, and an upstream 1xx gets 502 upstream_unreachable (:429-434). Cortex forwards WebSocket today (#1488). Until D13 in #2042 is decided, follow moca for bound requests, because its suite checks it.
    • Leaves: keep Cortex's minter, but for a bound connection refuse to mint with a CA that is not valid now (503 leaf_unavailable, moca leafca.go:107-109), and clamp NotAfter to the CA's. Accept the other differences in the table (a shared key, 25 h, -1 min).
    • The CA comes from tlsbridge.NewFileSource on MOCA_EGRESS_CA_CERT_FILE/_KEY_FILE, plus a "valid now" check at start-up. MOCA_EGRESS_UPSTREAM_CA is added to the system roots.
C. Injection
  1. static-inject gains source: resolver with resolver: <name>. It reads pctx.Caller and the shared *Cache from credresolve.Get(name). Unlike the other sources, it requires no bearer from the client and never answers 401 for "no credential". A request with no pctx.Caller gets no injection. For each request:
    • Use only the names in Caller.Credentials when that is not nil (D7), and only credentials for the request's port.
    • Path confusion: when any credential for the port has a prefix other than /, remove the query, then refuse with 400 bad_request a raw path that contains \, ;, %, #, //, or a . or .. segment (moca credpolicy.go:84, intercept.go:234-248, 288-292).
    • The longest PathPrefix on a / boundary wins.
    • On a match (Envoy's overwrite: true): delete the guest's Authorization, then set each header the credential lists. Call pctx.SetCredential(name, subject, false).
    • With no match (Envoy's allow_request_without_credential: true): the request goes on with no injection, and the guest's own Authorization passes unchanged (moca intercept.go:317-324).
    • X-Moca-*, Proxy-* and hop-by-hop headers are removed in both directions (moca forward.go:17-44). A placeholder is not required.
    • Revocation per connection: the core puts a per-tunnel state object into each decrypted request's context, next to the connProcKey copy (bridging.go:333-335). static-inject records each injected PathPrefix → Name there. When a prefix that matches the current request's path has a name that is no longer in the lookup, answer 401 credential_revoked with Connection: close in the Violation's headers, call pctx.SetCredential(name, "", true), and never fall back to the / prefix (moca intercept.go:294-310).
    • A lookup error answers as item 3 says, and nothing is dialed.
    • Plain HTTP when a credential exists for the request's port keeps 403 plaintext_credential (moca handler.go:239-243).
    • All refusals go through the refusal writer (#2086).
  2. Injection runs last. Add InjectsCredential to PluginCapabilities and to WithinCeiling. The unconfigured static-inject declares it (the ceiling), and a configured instance narrows it away for secret_dir and mappings, so BuildWithDeps logs no ceiling warning. validateCapabilities refuses a pipeline where any plugin follows one that declares it, so no other plugin and no recorder sees the secret. Existing static-inject configs still load. /v1/pipeline and agentop's plugin pane show the new capability.
D. moca's resolver
  1. In the moca driver (behind include_driver_moca), credresolve.Register("moca", …):
    • It calls POST /v1/egress/credential as moca's cpcreds.go does, with {"sandbox": Caller.SessionID, "host": host}. It reads moca's setting names above, so one moca deployment configures either proxy.
    • no_credential is an empty list cached for MOCA_EGRESS_NONE_TTL_S (default 60, range 5–300). sandbox_not_found is an empty list cached for 5 s. A ttlSeconds in the 404 reply wins for both. A 404 with any other error code is an error (moca cpcreds.go:263-279).
    • Client hardening, from moca cpcreds.go:89-145, 338-409. A reply that breaks a rule is an error, and it is not cached:
      • HTTPS only (HTTP only for 127.0.0.1), TLS 1.2 minimum, a 3 s default timeout.
      • A URL with no path, query, fragment or userinfo.
      • No redirects and no proxy.
      • A 1 MiB reply limit.
      • 1 to 4 headers per credential. Names of 1–64 characters from [A-Za-z0-9-], no duplicates (case-insensitive), no proxy-* or x-moca-* prefix, and not in moca's refused-header set (it mirrors egress-binding.ts). A value with CR, LF or NUL is refused.
      • port is 1–65535. pathPrefix follows moca's grammar. expiresAt is RFC 3339.
    • The driver reads the CA settings and sets the TLS bridge's CA and upstream roots from them.
    • The built-in config of #2085 adds static-inject with source: resolver, resolver: moca to the outbound pipeline, and sets Server.Credentials from credresolve.Get("moca").
  2. The grant stays opaque. Caller.Grant reaches the resolver unchanged. No core type names a moca claim. #2090 adds the grant to the lookup without changing the seam.
  3. Out of scope here: the transparent listener's interception sites. Shared mode (#2087) does not start that listener.

Not in scope

  • Grant-bound lookups (phase 2, MI1 §6.3) and the harness reply shape (#2090). The seam must accept it: one token and a header name, which the moca driver turns into one Credential with PathPrefix: "/" and the destination's port.
  • Other resolvers (Vault). The demo resolver is #2091.
  • Body-reading plugins (#1487).

Tests

  • credresolve: TTL clamp, the earliest-Expires rule, the 5 s drop and its 5 s TTL, *Refusal and errors not cached, the 4096 limit and its eviction order, one lookup at a time, a waiter that gives up, Forget, an unknown name in Get, and no value in any log line.
  • static-inject with a fake resolver: one case for each rule in item 5, revocation included.
  • validateCapabilities: a plugin after a credential injector is refused, and existing static-inject configs still load with no ceiling warning. ceiling_rule_test.go passes.
  • Bound connections only: TestMint_WarnsWhenIssuerIsExpiring and bridgedopen_test.go pass unchanged.
  • The forward proxy with a fake resolver and a test binding: a host with a credential on the CONNECT's port is intercepted, a host without one stays an opaque tunnel, a name outside Caller.Credentials stays opaque, a lookup error answers 503 and dials nothing, a *Refusal answers its status, a bad upstream answers 502 with fail_closed off, and a client that rejects the CA is not turned into a tunnel. Without a binding, tls_bridge's rules apply as today.
  • The TLS rules in item 4, one case each.
  • The moca resolver against a fake control plane: the request shape, the reply parsing, each hardening rule, an error, a timeout, 404 with and without ttlSeconds, sandbox_not_found.
  • vmcontrol: the last Unregister of a session calls Forget.
  • The moca-conformance job (#2085): remove each case that this issue makes pass. A case that also waits for an audit event stays on the list, with a comment that names #2089.

Done when

  • A hostegress build injects each session's own credential from moca's endpoint, and keeps every other allowed host as an opaque tunnel.
  • Cortex's core has no moca identifier for this feature, and the forward proxy has no new hook.
  • Every credential and interception case passes, or stays on known-failures.txt only because it waits for an audit event (#2089).
主要语言
Go
星标
31
派生
49
平均合并
9 小时 43 分钟
30 天内合并 PR
367

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

rossoctl/cortex 的其他 Issue

查看 rossoctl/cortex 的全部 Issue

相似的 Issue

更多 Go Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。