feat: Resolve credentials per caller through a resolver seam, with moca's resolver in the moca driver
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 5/5
- Thời gian dự kiến
- Hơn một tuần
- Mức phù hợp với người mới
- 8/100
Hướng nghiên cứu
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.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
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
core/credresolvewith the contract above.RegisterandGetfollow the plugin registry pattern.Getreturns one*Cacheper name per process, so the forward proxy andstatic-injectshare one cache and one lookup per key.- 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 frompctx.SessionIDor 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
Expiresof 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
*Refusaland 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 (UnregisterordropConn). 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.
- The key is (caller
B. Interception follows the resolver
- 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 (betweentunnel.go:437and:443):- It looks up the caller's credentials for the host, and keeps only the names in
Caller.Credentialswhen 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_closedsays. 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
*Refusalanswers its status and code, and any other lookup error answers503 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.
- It looks up the caller's credentials for the host, and keeps only the names in
- 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-334needs h2):- Upstream: dial the CONNECT's checked address, and verify the upstream with a TLS handshake on that connection before the guest gets
200(mocaintercept.go:96-115). Send no request to verify. A failure answers502 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.1only, TLS 1.2 minimum (mocaintercept.go:101-103, 124-125). Add an ALPN argument toTerminate. - 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 decisionmisdirected_request. - A request-target that is not origin-form (does not start with
/) gets400 bad_request(:273).TRACEandTRACKget405 bad_request(:280-282). Upgradeis removed, and an upstream1xxgets502 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, mocaleafca.go:107-109), and clampNotAfterto the CA's. Accept the other differences in the table (a shared key, 25 h, -1 min). - The CA comes from
tlsbridge.NewFileSourceonMOCA_EGRESS_CA_CERT_FILE/_KEY_FILE, plus a "valid now" check at start-up.MOCA_EGRESS_UPSTREAM_CAis added to the system roots.
- Upstream: dial the CONNECT's checked address, and verify the upstream with a TLS handshake on that connection before the guest gets
C. Injection
static-injectgainssource: resolverwithresolver: <name>. It readspctx.Callerand the shared*Cachefromcredresolve.Get(name). Unlike the other sources, it requires no bearer from the client and never answers401for "no credential". A request with nopctx.Callergets no injection. For each request:- Use only the names in
Caller.Credentialswhen 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 with400 bad_requesta raw path that contains\,;,%,#,//, or a.or..segment (mocacredpolicy.go:84,intercept.go:234-248, 288-292). - The longest
PathPrefixon a/boundary wins. - On a match (Envoy's
overwrite: true): delete the guest'sAuthorization, then set each header the credential lists. Callpctx.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 ownAuthorizationpasses unchanged (mocaintercept.go:317-324). X-Moca-*,Proxy-*and hop-by-hop headers are removed in both directions (mocaforward.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
connProcKeycopy (bridging.go:333-335).static-injectrecords each injectedPathPrefix → Namethere. When a prefix that matches the current request's path has a name that is no longer in the lookup, answer401 credential_revokedwithConnection: closein theViolation's headers, callpctx.SetCredential(name, "", true), and never fall back to the/prefix (mocaintercept.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(mocahandler.go:239-243). - All refusals go through the refusal writer (#2086).
- Use only the names in
- Injection runs last. Add
InjectsCredentialtoPluginCapabilitiesand toWithinCeiling. The unconfiguredstatic-injectdeclares it (the ceiling), and a configured instance narrows it away forsecret_dirandmappings, soBuildWithDepslogs no ceiling warning.validateCapabilitiesrefuses a pipeline where any plugin follows one that declares it, so no other plugin and no recorder sees the secret. Existingstatic-injectconfigs still load./v1/pipelineand agentop's plugin pane show the new capability.
D. moca's resolver
- In the moca driver (behind
include_driver_moca),credresolve.Register("moca", …):- It calls
POST /v1/egress/credentialas moca'scpcreds.godoes, with{"sandbox": Caller.SessionID, "host": host}. It reads moca's setting names above, so one moca deployment configures either proxy. no_credentialis an empty list cached forMOCA_EGRESS_NONE_TTL_S(default 60, range 5–300).sandbox_not_foundis an empty list cached for 5 s. AttlSecondsin the404reply wins for both. A404with any other error code is an error (mocacpcreds.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), noproxy-*orx-moca-*prefix, and not in moca's refused-header set (it mirrorsegress-binding.ts). A value with CR, LF or NUL is refused. portis 1–65535.pathPrefixfollows moca's grammar.expiresAtis RFC 3339.
- HTTPS only (HTTP only for
- 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-injectwithsource: resolver,resolver: mocato the outbound pipeline, and setsServer.Credentialsfromcredresolve.Get("moca").
- It calls
- The grant stays opaque.
Caller.Grantreaches the resolver unchanged. No core type names a moca claim. #2090 adds the grant to the lookup without changing the seam. - 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
CredentialwithPathPrefix: "/"and the destination's port. - Other resolvers (Vault). The demo resolver is #2091.
- Body-reading plugins (#1487).
Tests
credresolve: TTL clamp, the earliest-Expiresrule, the 5 s drop and its 5 s TTL,*Refusaland errors not cached, the 4096 limit and its eviction order, one lookup at a time, a waiter that gives up,Forget, an unknown name inGet, and no value in any log line.static-injectwith a fake resolver: one case for each rule in item 5, revocation included.validateCapabilities: a plugin after a credential injector is refused, and existingstatic-injectconfigs still load with no ceiling warning.ceiling_rule_test.gopasses.- Bound connections only:
TestMint_WarnsWhenIssuerIsExpiringandbridgedopen_test.gopass 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.Credentialsstays opaque, a lookup error answers503and dials nothing, a*Refusalanswers its status, a bad upstream answers502withfail_closedoff, 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,
404with and withoutttlSeconds,sandbox_not_found. vmcontrol: the lastUnregisterof a session callsForget.- The
moca-conformancejob (#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
hostegressbuild 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.txtonly because it waits for an audit event (#2089).
- Ngôn ngữ chính
- Go
- Star
- 31
- Fork
- 49
- Merge trung bình
- 9 giờ 43 phút
- Pull request đã merge (30 ngày)
- 367
Chuẩn bị môi trường
- Không có Dockerfile hay tệp Docker Compose
- Không có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của rossoctl/cortex
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 1 ngày
-
contextguru plugin: set keepalive.Record.Identity; context-guru v0.7.11 removes Record.AgentĐang mở
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 82/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
Maintainer thường phản hồi trong vòng 1 ngày
-
bug laptop
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 4/5 3-5 ngày Mức phù hợp với người mới 55/100
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của rossoctl/cortex
Issue tương tự
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
Maintainer thường phản hồi trong vòng 1 ngày
-
taskmanager: a failed v1alpha1 backup leaves the partial backup behindCó thể đã có người làm @arshil42 đã nhận hôm nay. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 85/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Packaging: support mise-en-placeĐang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 80/100
ether/etherpad-go#571 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
labeler: read a limit above math.MaxInt as math.MaxInt in nonNegative (CodeQL alerts #20 and #21)Đang mởcost:approved factory:queued factory:tracking priority:p2 rank:12 ready-for-doing task:approved tokens:50k
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 88/100
sisaku-security/sisakulint#860 · 2 bình luận ·