What this change means
Atlas added verifierauth to its detector catalog in this update.
| @@ -0,0 +1,166 @@ | ||
| 1 | added: package verifierauth | |
| 2 | added: | |
| 3 | added: import ( | |
| 4 | added: "context" | |
| 5 | added: "fmt" | |
| 6 | added: "net/http" | |
| 7 | added: "strings" | |
| 8 | added: "sync" | |
| 9 | added: "time" | |
| 10 | added: | |
| 11 | added: "github.com/go-logr/logr" | |
| 12 | added: "golang.org/x/oauth2" | |
| 13 | added: | |
| 14 | added: "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb" | |
| 15 | added: ) | |
| 16 | added: | |
| 17 | added: // defaultTokenLifetime is applied when the identity provider omits | |
| 18 | added: // expires_in from its token response. RFC 6749 makes expires_in optional, | |
| 19 | added: // and oauth2 leaves Expiry zero in that case, which ReuseTokenSource treats | |
| 20 | added: // as "never expires". Without a default, one token would be reused for the | |
| 21 | added: // life of the process and every verification would fail once the IdP | |
| 22 | added: // expired it. | |
| 23 | added: const defaultTokenLifetime = 5 * time.Minute | |
| 24 | added: | |
| 25 | added: // ropcTokenSource performs the OAuth2 Resource Owner Password Credentials | |
| 26 | added: // exchange (RFC 6749 section 4.3). It only fetches; caching and refresh are | |
| 27 | added: // layered on top by ReuseTokenSource, and failure backoff by | |
| 28 | added: // tokenErrorCache. | |
| 29 | added: type ropcTokenSource struct { | |
| 30 | added: conf *oauth2.Config | |
| 31 | added: username string | |
| 32 | added: password string | |
| 33 | added: // client performs the token request. It is deliberately separate from | |
| 34 | added: // the detector's client: the token endpoint is the identity provider | |
| 35 | added: // that issues tokens for the auth proxy, not a verification endpoint, so | |
| 36 | added: // detector-specific transport rules (such as blocking private IPs) do | |
| 37 | added: // not apply to it. | |
| 38 | added: client *http.Client | |
| 39 | added: now func() time.Time | |
| 40 | added: logger func() logr.Logger | |
| 41 | added: } | |
| 42 | added: | |
| 43 | added: // newROPCTokenSource builds an unwrapped ROPC token source. Client | |
| 44 | added: // credentials are sent in the request body (AuthStyleInParams) rather than | |
| 45 | added: // as HTTP basic auth, which is what password-grant deployments of the | |
| 46 | added: // identity providers we target expect. | |
| 47 | added: func newROPCTokenSource( | |
| 48 | added: tokenEndpoint string, | |
| 49 | added: ropc *custom_detectorspb.ROPCConfig, | |
| 50 | added: client *http.Client, | |
| 51 | added: now func() time.Time, | |
| 52 | added: logger func() logr.Logger, | |
| 53 | added: ) *ropcTokenSource { | |
| 54 | added: return &ropcTokenSource{ | |
| 55 | added: conf: &oauth2.Config{ | |
| 56 | added: ClientID: ropc.GetClientId(), | |
| 57 | added: ClientSecret: ropc.GetClientSecret(), | |
| 58 | added: Endpoint: oauth2.Endpoint{ | |
| 59 | added: TokenURL: tokenEndpoint, | |
| 60 | added: AuthStyle: oauth2.AuthStyleInParams, | |
| 61 | added: }, | |
| 62 | added: Scopes: strings.Fields(ropc.GetScope()), | |
| 63 | added: }, | |
| 64 | added: username: ropc.GetUsername(), | |
| 65 | added: password: ropc.GetPassword(), | |
| 66 | added: client: client, | |
| 67 | added: now: now, | |
| 68 | added: logger: logger, | |
| 69 | added: } | |
| 70 | added: } | |
| 71 | added: | |
| 72 | added: // Token fetches a new access token. | |
| 73 | added: // | |
| 74 | added: // oauth2.TokenSource.Token takes no context, so the request context is | |
| 75 | added: // rooted in Background and the HTTP client travels on it under the | |
| 76 | added: // oauth2.HTTPClient key, which is how the oauth2 package selects a client. | |
| 77 | added: // The client's timeout is what bounds a hung identity provider. | |
| 78 | added: func (s *ropcTokenSource) Token() (*oauth2.Token, error) { | |
| 79 | added: ctx := context.WithValue(context.Background(), oauth2.HTTPClient, s.client) | |
| 80 | added: | |
| 81 | added: s.logger().V(2).Info("requesting verifier access token") | |
| 82 | added: tok, err := s.conf.PasswordCredentialsToken(ctx, s.username, s.password) | |
| 83 | added: if err != nil { | |
| 84 | added: return nil, fmt.Errorf("ropc token request failed: %w", err) | |
| 85 | added: } | |
| 86 | added: | |
| 87 | added: if tok.Expiry.IsZero() { | |
| 88 | added: tok.Expiry = s.now().Add(defaultTokenLifetime) | |
| 89 | added: s.logger().V(1).Info("identity provider did not return expires_in; using default token lifetime", | |
| 90 | added: "default_lifetime", defaultTokenLifetime, | |
| 91 | added: ) | |
| 92 | added: } | |
| 93 | added: s.logger().V(1).Info("obtained verifier access token", "expires_at", tok.Expiry) | |
| 94 | added: return tok, nil | |
| 95 | added: } | |
| 96 | added: | |
| 97 | added: // Backoff bounds for tokenErrorCache. The window starts small so a brief | |
| 98 | added: // IdP blip clears quickly, and is capped so that wrong credentials cost at | |
| 99 | added: // most one failed login per maxTokenErrorBackoff, which keeps the scanner | |
| 100 | added: // from tripping the identity provider's account lockout policy. | |
| 101 | added: const ( | |
| 102 | added: minTokenErrorBackoff = 5 * time.Second | |
| 103 | added: maxTokenErrorBackoff = 5 * time.Minute | |
| 104 | added: ) | |
| 105 | added: | |
| 106 | added: // tokenErrorCache remembers the most recent token fetch failure and answers | |
| 107 | added: // with it, without contacting the IdP, until a backoff window passes. | |
| 108 | added: // ReuseTokenSource already caches successful tokens; this is the | |
| 109 | added: // counterpart for failures. | |
| 110 | added: // | |
| 111 | added: // It never sleeps. Callers inside a window get the cached error | |
| 112 | added: // immediately, so a failing or hung IdP turns verification for the affected | |
| 113 | added: // auth config into fast "unable to verify" results instead of tying up the | |
| 114 | added: // shared detector worker pool behind token request timeouts. The window | |
| 115 | added: // doubles on each consecutive failure up to maxTokenErrorBackoff and resets | |
| 116 | added: // on the first success. | |
| 117 | added: type tokenErrorCache struct { | |
| 118 | added: base oauth2.TokenSource | |
| 119 | added: now func() time.Time | |
| 120 | added: onFailure func(err error, retryIn time.Duration) | |
| 121 | added: | |
| 122 | added: mu sync.Mutex | |
| 123 | added: lastErr error | |
| 124 | added: retryAt time.Time | |
| 125 | added: window time.Duration | |
| 126 | added: } | |
| 127 | added: | |
| 128 | added: func newTokenErrorCache(base oauth2.TokenSource, now func() time.Time, onFailure func(error, time.Duration)) *tokenErrorCache { | |
| 129 | added: return &tokenErrorCache{base: base, now: now, onFailure: onFailure} | |
| 130 | added: } | |
| 131 | added: | |
| 132 | added: // Token returns a fresh token from the base source, or the cached failure | |
| 133 | added: // while a backoff window is open. | |
| 134 | added: // | |
| 135 | added: // The mutex is held across the base fetch so that, when a window expires, | |
| 136 | added: // exactly one caller makes the next attempt and the rest observe its | |
| 137 | added: // outcome. ReuseTokenSource provides the same serialization in production; | |
| 138 | added: // holding the lock here keeps this type correct on its own. | |
| 139 | added: func (c *tokenErrorCache) Token() (*oauth2.Token, error) { | |
| 140 | added: c.mu.Lock() | |
| 141 | added: defer c.mu.Unlock() | |
| 142 | added: | |
| 143 | added: if c.lastErr != nil && c.now().Before(c.retryAt) { | |
| 144 | added: return nil, fmt.Errorf("token fetch failed recently; next attempt after %s: %w", | |
| 145 | added: c.retryAt.Format(time.RFC3339), c.lastErr) | |
| 146 | added: } | |
| 147 | added: | |
| 148 | added: tok, err := c.base.Token() | |
| 149 | added: if err != nil { | |
| 150 | added: if c.window == 0 { | |
| 151 | added: c.window = minTokenErrorBackoff | |
| 152 | added: } else { | |
| 153 | added: c.window = min(2*c.window, maxTokenErrorBackoff) | |
| 154 | added: } | |
| 155 | added: c.lastErr = err | |
| 156 | added: c.retryAt = c.now().Add(c.window) | |
| 157 | added: if c.onFailure != nil { | |
| 158 | added: c.onFailure(err, c.window) | |
| 159 | added: } | |
| 160 | added: return nil, err | |
| 161 | added: } | |
| 162 | added: | |
| 163 | added: c.lastErr = nil | |
| 164 | added: c.window = 0 | |
| 165 | added: return tok, nil | |
| 166 | added: } | |
| @@ -0,0 +1,164 @@ | ||
| 1 | added: package verifierauth | |
| 2 | added: | |
| 3 | added: import ( | |
| 4 | added: "errors" | |
| 5 | added: "fmt" | |
| 6 | added: "net" | |
| 7 | added: "net/http" | |
| 8 | added: "net/url" | |
| 9 | added: "strings" | |
| 10 | added: ) | |
| 11 | added: | |
| 12 | added: // The errors below reach detectors wrapped in *url.Error by http.Client, and | |
| 13 | added: // both are deliberately leaf errors with no Unwrap. Two consumers depend on | |
| 14 | added: // that: | |
| 15 | added: // - Result.SetVerificationError keeps only the innermost error's message, | |
| 16 | added: // so the leaf is what users see as the verification error. It has to | |
| 17 | added: // say "verifier auth" and carry the oauth2_trace for log correlation. | |
| 18 | added: // - Detectors classify request errors to decide that the verification | |
| 19 | added: // host does not exist, by substring ("no such host", "dial tcp") or by | |
| 20 | added: // errors.As into *net.DNSError. An IdP failure must not be mistaken for | |
| 21 | added: // a missing verification host, so the IdP's error is neither in the | |
| 22 | added: // message nor reachable through the chain. | |
| 23 | added: | |
| 24 | added: // ErrHeaderCollision reports that a request already carries the header the | |
| 25 | added: // access token would be written to. Built-in detectors commonly send the | |
| 26 | added: // secret under test in Authorization; overwriting it would hand the | |
| 27 | added: // verification service the token instead of the secret and produce wrong | |
| 28 | added: // verdicts, so the request is refused instead. The fix is to set tokenHeader | |
| 29 | added: // to a header the auth proxy reads. Match it with errors.Is. | |
| 30 | added: var ErrHeaderCollision = errors.New("verifier auth token header is already set by the detector; set oauth2 tokenHeader to a different header") | |
| 31 | added: | |
| 32 | added: // headerCollisionError is the ErrHeaderCollision instance returned for a | |
| 33 | added: // request, adding the header name and trace to the message. | |
| 34 | added: type headerCollisionError struct { | |
| 35 | added: header string | |
| 36 | added: trace string | |
| 37 | added: } | |
| 38 | added: | |
| 39 | added: func (e *headerCollisionError) Error() string { | |
| 40 | added: return fmt.Sprintf("%v (header %q, oauth2_trace=%s)", ErrHeaderCollision, e.header, e.trace) | |
| 41 | added: } | |
| 42 | added: | |
| 43 | added: func (e *headerCollisionError) Is(target error) bool { return target == ErrHeaderCollision } | |
| 44 | added: | |
| 45 | added: // TokenError reports that no access token could be obtained, so the request | |
| 46 | added: // was not sent. The IdP's error is kept in Err for callers that ask for it | |
| 47 | added: // with errors.As, and every real fetch failure is logged with the same | |
| 48 | added: // oauth2_trace and the token endpoint. | |
| 49 | added: type TokenError struct { | |
| 50 | added: Trace string | |
| 51 | added: Err error | |
| 52 | added: } | |
| 53 | added: | |
| 54 | added: func (e *TokenError) Error() string { | |
| 55 | added: return fmt.Sprintf("verifier auth: could not obtain access token (oauth2_trace=%s; see logs for the cause)", e.Trace) | |
| 56 | added: } | |
| 57 | added: | |
| 58 | added: // WrapClient returns a copy of base whose transport attaches an access token | |
| 59 | added: // to requests bound for allowedEndpoints. Timeout, redirect policy, and | |
| 60 | added: // cookie jar are carried over from base unchanged; base itself is not | |
| 61 | added: // modified. | |
| 62 | added: // | |
| 63 | added: // Only the scheme and host of each allowed endpoint are matched, because | |
| 64 | added: // detectors append their own API paths to the configured endpoint. | |
| 65 | added: // Requests to any other host pass through without a token. The check runs | |
| 66 | added: // on every round trip, so a redirect to another host never carries the | |
| 67 | added: // token either. | |
| 68 | added: func (c *Config) WrapClient(base *http.Client, allowedEndpoints []string) *http.Client { | |
| 69 | added: clone := *base | |
| 70 | added: rt := base.Transport | |
| 71 | added: if rt == nil { | |
| 72 | added: rt = http.DefaultTransport | |
| 73 | added: } | |
| 74 | added: clone.Transport = &authTransport{ | |
| 75 | added: base: rt, | |
| 76 | added: cfg: c, | |
| 77 | added: allowed: originsOf(allowedEndpoints), | |
| 78 | added: } | |
| 79 | added: return &clone | |
| 80 | added: } | |
| 81 | added: | |
| 82 | added: // originsOf reduces endpoints to their lowercase scheme://host form. | |
| 83 | added: // Endpoints that don't parse as absolute URLs contribute nothing, which | |
| 84 | added: // means no token is ever sent on their behalf. | |
| 85 | added: func originsOf(endpoints []string) map[string]struct{} { | |
| 86 | added: origins := make(map[string]struct{}, len(endpoints)) | |
| 87 | added: for _, endpoint := range endpoints { | |
| 88 | added: u, err := url.Parse(endpoint) | |
| 89 | added: if err != nil || u.Scheme == "" || u.Host == "" { | |
| 90 | added: continue | |
| 91 | added: } | |
| 92 | added: origins[origin(u)] = struct{}{} | |
| 93 | added: } | |
| 94 | added: return origins | |
| 95 | added: } | |
| 96 | added: | |
| 97 | added: // defaultPorts maps each scheme a verifier endpoint may use to the port it | |
| 98 | added: // implies when the URL names none. | |
| 99 | added: var defaultPorts = map[string]string{"http": "80", "https": "443"} | |
| 100 | added: | |
| 101 | added: // origin reduces u to the lowercase scheme://host[:port] key used for the | |
| 102 | added: // allowlist. url.URL keeps the host exactly as written, so the same server | |
| 103 | added: // can arrive as "https://h" or "https://h:443": the configured endpoint and | |
| 104 | added: // a detector's rebuilt request URL need not agree on spelling. The default | |
| 105 | added: // port for the scheme is dropped so both forms produce one key; dropping it | |
| 106 | added: // (rather than always adding it) matches how endpoints are usually written. | |
| 107 | added: // Non-default ports are kept, so "https://h:8443" stays a different origin. | |
| 108 | added: func origin(u *url.URL) string { | |
| 109 | added: scheme := strings.ToLower(u.Scheme) | |
| 110 | added: host := strings.ToLower(u.Hostname()) | |
| 111 | added: if port := u.Port(); port != "" && port != defaultPorts[scheme] { | |
| 112 | added: host = net.JoinHostPort(host, port) | |
| 113 | added: } else if strings.Contains(host, ":") { | |
| 114 | added: // Hostname strips the brackets from an IPv6 literal, and | |
| 115 | added: // JoinHostPort only restores them when there is a port. | |
| 116 | added: host = "[" + host + "]" | |
| 117 | added: } | |
| 118 | added: return scheme + "://" + host | |
| 119 | added: } | |
| 120 | added: | |
| 121 | added: // authTransport attaches the access token to requests for allowed origins. | |
| 122 | added: type authTransport struct { | |
| 123 | added: base http.RoundTripper | |
| 124 | added: cfg *Config | |
| 125 | added: allowed map[string]struct{} | |
| 126 | added: } | |
| 127 | added: | |
| 128 | added: // RoundTrip attaches the token and forwards the request, or fails it | |
| 129 | added: // without sending anything. Every failure is returned as a request error, | |
| 130 | added: // which detectors already report as a verification error, never as "not | |
| 131 | added: // verified". | |
| 132 | added: // | |
| 133 | added: // The token is set on a clone because a RoundTripper must not modify the | |
| 134 | added: // caller's request. That also keeps the token off the request http.Client | |
| 135 | added: // reuses to build redirects; each redirect hop comes back through here and | |
| 136 | added: // is checked against the allowlist again. | |
| 137 | added: func (t *authTransport) RoundTrip(req *http.Request) (*http.Response, error) { | |
| 138 | added: if _, ok := t.allowed[origin(req.URL)]; !ok { | |
| 139 | added: return t.base.RoundTrip(req) | |
| 140 | added: } | |
| 141 | added: | |
| 142 | added: if len(req.Header.Values(t.cfg.tokenHeader)) > 0 { | |
| 143 | added: closeBody(req) | |
| 144 | added: return nil, &headerCollisionError{header: t.cfg.tokenHeader, trace: t.cfg.trace} | |
| 145 | added: } | |
| 146 | added: | |
| 147 | added: tok, err := t.cfg.tokens.Token() | |
| 148 | added: if err != nil { | |
| 149 | added: closeBody(req) | |
| 150 | added: return nil, &TokenError{Trace: t.cfg.trace, Err: err} | |
| 151 | added: } | |
| 152 | added: | |
| 153 | added: authed := req.Clone(req.Context()) | |
| 154 | added: authed.Header.Set(t.cfg.tokenHeader, "Bearer "+tok.AccessToken) | |
| 155 | added: return t.base.RoundTrip(authed) | |
| 156 | added: } | |
| 157 | added: | |
| 158 | added: // closeBody honors the RoundTripper contract that the request body is | |
| 159 | added: // closed even when RoundTrip returns an error without sending. | |
| 160 | added: func closeBody(req *http.Request) { | |
| 161 | added: if req.Body != nil { | |
| 162 | added: _ = req.Body.Close() | |
| 163 | added: } | |
| 164 | added: } | |
| @@ -0,0 +1,148 @@ | ||
| 1 | added: // Package verifierauth authenticates verification requests to endpoints that | |
| 2 | added: // sit behind an auth proxy: an OAuth-protected component in front of a | |
| 3 | added: // verification service that requires an access token before it forwards a | |
| 4 | added: // request to that service. | |
| 5 | added: // | |
| 6 | added: // Authentication is purely an HTTP-client concern. A Config wraps a | |
| 7 | added: // detector's existing *http.Client so every request to a configured endpoint | |
| 8 | added: // carries an access token, while the detector keeps full ownership of its | |
| 9 | added: // request shape and of how responses map to verdicts. The wrapper never | |
| 10 | added: // decides "verified" or "not verified"; it either attaches a token or fails | |
| 11 | added: // the request, and a failed request surfaces as a verification error | |
| 12 | added: // ("unable to verify"). | |
| 13 | added: // | |
| 14 | added: // The package sits below pkg/detectors so that both pkg/detectors | |
| 15 | added: // (EndpointSetter, used by built-in detectors) and pkg/custom_detectors can | |
| 16 | added: // use it. It must never import either of them. | |
| 17 | added: package verifierauth | |
| 18 | added: | |
| 19 | added: import ( | |
| 20 | added: "errors" | |
| 21 | added: "fmt" | |
| 22 | added: "net/http" | |
| 23 | added: "strings" | |
| 24 | added: "time" | |
| 25 | added: | |
| 26 | added: "github.com/go-logr/logr" | |
| 27 | added: "github.com/google/uuid" | |
| 28 | added: "golang.org/x/net/http/httpguts" | |
| 29 | added: "golang.org/x/oauth2" | |
| 30 | added: | |
| 31 | added: "github.com/trufflesecurity/trufflehog/v3/pkg/common" | |
| 32 | added: logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context" | |
| 33 | added: "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb" | |
| 34 | added: ) | |
| 35 | added: | |
| 36 | added: // DefaultTokenHeader is the header that carries the access token when the | |
| 37 | added: // configuration does not name one. | |
| 38 | added: const DefaultTokenHeader = "Authorization" | |
| 39 | added: | |
| 40 | added: // Config is a validated, ready-to-use verifier authentication setup. One | |
| 41 | added: // Config is shared by every request (and every detector worker) that uses | |
| 42 | added: // the same auth block, so its token cache and token error cache are shared | |
| 43 | added: // too. A nil *Config means "no auth configured". | |
| 44 | added: type Config struct { | |
| 45 | added: tokens oauth2.TokenSource | |
| 46 | added: tokenHeader string | |
| 47 | added: tokenEndpoint string | |
| 48 | added: // trace correlates every log line and error produced for this auth | |
| 49 | added: // config, so an operator can follow one auth block from token fetch | |
| 50 | added: // through to the verification requests that used it. | |
| 51 | added: trace string | |
| 52 | added: } | |
| 53 | added: | |
| 54 | added: // FromProto validates an auth block and builds a Config from it. It returns | |
| 55 | added: // (nil, nil) when auth is nil, so callers can pass the field through | |
| 56 | added: // unconditionally. | |
| 57 | added: // | |
| 58 | added: // No token is fetched here. Token acquisition is deferred to the first | |
| 59 | added: // verification request that needs one, so an unreachable identity provider | |
| 60 | added: // degrades verification for the affected detector instead of failing | |
| 61 | added: // startup, and the rest of the scan proceeds. Only the structure of the | |
| 62 | added: // config is checked up front. | |
| 63 | added: // | |
| 64 | added: // unsafe has the same meaning as on VerifierConfig: it permits a plain | |
| 65 | added: // http:// token endpoint. | |
| 66 | added: func FromProto(auth *custom_detectorspb.VerifierAuth, unsafe bool) (*Config, error) { | |
| 67 | added: if auth == nil { | |
| 68 | added: return nil, nil | |
| 69 | added: } | |
| 70 | added: oc := auth.GetOauth2() | |
| 71 | added: if oc == nil { | |
| 72 | added: return nil, errors.New("auth is set but names no auth mechanism (expected oauth2)") | |
| 73 | added: } | |
| 74 | added: if err := ValidateEndpoint(oc.GetTokenEndpoint(), unsafe); err != nil { | |
| 75 | added: return nil, fmt.Errorf("oauth2 tokenEndpoint: %w", err) | |
| 76 | added: } | |
| 77 | added: | |
| 78 | added: tokenHeader := oc.GetTokenHeader() | |
| 79 | added: if tokenHeader == "" { | |
| 80 | added: tokenHeader = DefaultTokenHeader | |
| 81 | added: } | |
| 82 | added: if !httpguts.ValidHeaderFieldName(tokenHeader) { | |
| 83 | added: return nil, fmt.Errorf("oauth2 tokenHeader %q is not a valid HTTP header name", tokenHeader) | |
| 84 | added: } | |
| 85 | added: | |
| 86 | added: ropc := oc.GetRopc() | |
| 87 | added: if ropc == nil { | |
| 88 | added: return nil, errors.New("oauth2 auth names no grant (expected ropc)") | |
| 89 | added: } | |
| 90 | added: switch { | |
| 91 | added: case ropc.GetUsername() == "": | |
| 92 | added: return nil, errors.New("oauth2 ropc username is required") | |
| 93 | added: case ropc.GetPassword() == "": | |
| 94 | added: return nil, errors.New("oauth2 ropc password is required") | |
| 95 | added: case ropc.GetClientId() == "": | |
| 96 | added: return nil, errors.New("oauth2 ropc clientId is required") | |
| 97 | added: } | |
| 98 | added: | |
| 99 | added: cfg := &Config{ | |
| 100 | added: tokenHeader: http.CanonicalHeaderKey(tokenHeader), | |
| 101 | added: tokenEndpoint: oc.GetTokenEndpoint(), | |
| 102 | added: trace: uuid.NewString(), | |
| 103 | added: } | |
| 104 | added: base := newROPCTokenSource(oc.GetTokenEndpoint(), ropc, common.SaneHttpClient(), time.Now, cfg.logger) | |
| 105 | added: errCache := newTokenErrorCache(base, time.Now, func(err error, retryIn time.Duration) { | |
| 106 | added: cfg.logger().Error(err, "failed to obtain verifier access token; verification for this auth config is unavailable until the retry", | |
| 107 | added: "retry_in", retryIn, | |
| 108 | added: ) | |
| 109 | added: }) | |
| 110 | added: // ReuseTokenSource caches the token and refreshes it shortly before it | |
| 111 | added: // expires. It serializes callers on its own lock while a fetch is in | |
| 112 | added: // flight, so concurrent detector workers trigger at most one fetch. | |
| 113 | added: cfg.tokens = oauth2.ReuseTokenSource(nil, errCache) | |
| 114 | added: return cfg, nil | |
| 115 | added: } | |
| 116 | added: | |
| 117 | added: // TokenHeader reports the canonical header name that carries the token. | |
| 118 | added: // Callers that build requests from user-supplied headers use it to reject a | |
| 119 | added: // configuration that would collide with the token at load time. | |
| 120 | added: func (c *Config) TokenHeader() string { | |
| 121 | added: return c.tokenHeader | |
| 122 | added: } | |
| 123 | added: | |
| 124 | added: // logger returns a logger tagged with this config's trace ID. It resolves | |
| 125 | added: // the default logger at call time rather than at construction, so log | |
| 126 | added: // output follows whatever logger the process configured after startup. | |
| 127 | added: func (c *Config) logger() logr.Logger { | |
| 128 | added: return logContext.Background().Logger().WithValues( | |
| 129 | added: "oauth2_trace", c.trace, | |
| 130 | added: "token_endpoint", c.tokenEndpoint, | |
| 131 | added: ) | |
| 132 | added: } | |
| 133 | added: | |
| 134 | added: // ValidateEndpoint enforces the transport rule shared by verification | |
| 135 | added: // endpoints and token endpoints: the endpoint must be set, and plain http:// | |
| 136 | added: // is only allowed when the verifier is explicitly marked unsafe. It lives | |
| 137 | added: // here, rather than in pkg/custom_detectors, so this package can apply the | |
| 138 | added: // same rule to token endpoints without importing custom_detectors. | |
| 139 | added: func ValidateEndpoint(endpoint string, unsafe bool) error { | |
| 140 | added: if len(endpoint) == 0 { | |
| 141 | added: return fmt.Errorf("no endpoint") | |
| 142 | added: } | |
| 143 | added: | |
| 144 | added: if strings.HasPrefix(endpoint, "http://") && !unsafe { | |
| 145 | added: return fmt.Errorf("http endpoint must have unsafe=true") | |
| 146 | added: } | |
| 147 | added: return nil | |
| 148 | added: } | |
| @@ -0,0 +1,83 @@ | ||
| 1 | added: // Package verifierauthtest supports tests outside verifierauth that exercise | |
| 2 | added: // the verifier auth path: a fake OAuth2 identity provider that issues a fixed | |
| 3 | added: // access token, and a helper that builds a verifierauth.Config against it. | |
| 4 | added: // It is imported only from tests, so it never ends up in the binary. | |
| 5 | added: package verifierauthtest | |
| 6 | added: | |
| 7 | added: import ( | |
| 8 | added: "encoding/json" | |
| 9 | added: "net/http" | |
| 10 | added: "net/http/httptest" | |
| 11 | added: "sync/atomic" | |
| 12 | added: "testing" | |
| 13 | added: | |
| 14 | added: "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth" | |
| 15 | added: "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb" | |
| 16 | added: ) | |
| 17 | added: | |
| 18 | added: // AccessToken is the access token the fake IdP issues. Verification servers | |
| 19 | added: // in tests expect it as "Bearer " + AccessToken in the configured header. | |
| 20 | added: const AccessToken = "auth-proxy-access-token" | |
| 21 | added: | |
| 22 | added: // IdP is a fake OAuth2 token endpoint for the ROPC grant. It answers every | |
| 23 | added: // token request with AccessToken until RejectCredentials is called. | |
| 24 | added: type IdP struct { | |
| 25 | added: *httptest.Server | |
| 26 | added: hits atomic.Int32 | |
| 27 | added: rejected atomic.Bool | |
| 28 | added: } | |
| 29 | added: | |
| 30 | added: // NewIdP starts a fake IdP that is closed when the test ends. | |
| 31 | added: func NewIdP(t testing.TB) *IdP { | |
| 32 | added: t.Helper() | |
| 33 | added: idp := &IdP{} | |
| 34 | added: idp.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 35 | added: idp.hits.Add(1) | |
| 36 | added: w.Header().Set("Content-Type", "application/json") | |
| 37 | added: if idp.rejected.Load() { | |
| 38 | added: w.WriteHeader(http.StatusUnauthorized) | |
| 39 | added: _ = json.NewEncoder(w).Encode(map[string]any{"error": "invalid_grant"}) | |
| 40 | added: return | |
| 41 | added: } | |
| 42 | added: _ = json.NewEncoder(w).Encode(map[string]any{ | |
| 43 | added: "access_token": AccessToken, | |
| 44 | added: "token_type": "Bearer", | |
| 45 | added: "expires_in": 3600, | |
| 46 | added: }) | |
| 47 | added: })) | |
| 48 | added: t.Cleanup(idp.Close) | |
| 49 | added: return idp | |
| 50 | added: } | |
| 51 | added: | |
| 52 | added: // RejectCredentials makes every later token request fail with invalid_grant, | |
| 53 | added: // which is how an IdP answers wrong service account credentials. | |
| 54 | added: func (idp *IdP) RejectCredentials() { idp.rejected.Store(true) } | |
| 55 | added: | |
| 56 | added: // Hits reports how many token requests the IdP has received. | |
| 57 | added: func (idp *IdP) Hits() int { return int(idp.hits.Load()) } | |
| 58 | added: | |
| 59 | added: // Config builds a verifier auth config that fetches tokens from idp and | |
| 60 | added: // writes them to tokenHeader (empty means the default, Authorization). The | |
| 61 | added: // fake IdP is plain HTTP, so the config is built with unsafe set. | |
| 62 | added: func Config(t testing.TB, idp *IdP, tokenHeader string) *verifierauth.Config { | |
| 63 | added: t.Helper() | |
| 64 | added: cfg, err := verifierauth.FromProto(&custom_detectorspb.VerifierAuth{ | |
| 65 | added: AuthConfig: &custom_detectorspb.VerifierAuth_Oauth2{ | |
| 66 | added: Oauth2: &custom_detectorspb.OAuth2Config{ | |
| 67 | added: TokenEndpoint: idp.URL, | |
| 68 | added: TokenHeader: tokenHeader, | |
| 69 | added: GrantConfig: &custom_detectorspb.OAuth2Config_Ropc{ | |
| 70 | added: Ropc: &custom_detectorspb.ROPCConfig{ | |
| 71 | added: Username: "svc-scanner", | |
| 72 | added: Password: "svc-password", | |
| 73 | added: ClientId: "scanner-client", | |
| 74 | added: }, | |
| 75 | added: }, | |
| 76 | added: }, | |
| 77 | added: }, | |
| 78 | added: }, true) | |
| 79 | added: if err != nil { | |
| 80 | added: t.Fatalf("building verifier auth config: %v", err) | |
| 81 | added: } | |
| 82 | added: return cfg | |
| 83 | added: } | |