Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement AccessorID resolution and client ip propagation #19

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
20 changes: 13 additions & 7 deletions admissionctrl/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,18 @@ type JobValidator interface {
}

type JobHandler struct {
mutators []JobMutator
validators []JobValidator
logger hclog.Logger
mutators []JobMutator
validators []JobValidator
resolveToken bool
logger hclog.Logger
}

func NewJobHandler(mutators []JobMutator, validators []JobValidator, logger hclog.Logger) *JobHandler {
func NewJobHandler(mutators []JobMutator, validators []JobValidator, logger hclog.Logger, resolverToken bool) *JobHandler {
return &JobHandler{
mutators: mutators,
validators: validators,
logger: logger,
mutators: mutators,
validators: validators,
logger: logger,
resolveToken: resolverToken,
}
}

Expand Down Expand Up @@ -97,6 +99,10 @@ func (j *JobHandler) AdmissionValidators(origJob *api.Job) ([]error, error) {

}

func (j *JobHandler) ResolveToken() bool {
return j.resolveToken
}

func copyJob(job *api.Job) *api.Job {
jobCopy := &api.Job{}
data, err := json.Marshal(job)
Expand Down
12 changes: 12 additions & 0 deletions admissionctrl/mutator/json_patch_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/mxab/nacp/config"
"net/http"
"net/url"

Expand Down Expand Up @@ -48,6 +49,17 @@ func (j *JsonPatchWebhookMutator) Mutate(job *api.Job) (*api.Job, []error, error
if err != nil {
return nil, nil, err
}
// Add context headers if available
if ctx := req.Context(); ctx != nil {
if reqCtx, ok := ctx.Value("request_context").(*config.RequestContext); ok {
if reqCtx.ClientIP != "" {
req.Header.Set("X-Forwarded-For", reqCtx.ClientIP)
}
if reqCtx.AccessorID != "" {
req.Header.Set("X-Nomad-Accessor-ID", reqCtx.AccessorID)
}
}
}
res, err := httpClient.Do(req)
if err != nil {
return nil, nil, err
Expand Down
12 changes: 12 additions & 0 deletions admissionctrl/mutator/webhook_mutator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mutator
import (
"bytes"
"encoding/json"
"github.com/mxab/nacp/config"
"net/http"
"net/url"

Expand All @@ -27,6 +28,17 @@ func (w *WebhookMutator) Mutate(job *api.Job) (out *api.Job, warnings []error, e
if err != nil {
return nil, nil, err
}
// Add context headers if available
if ctx := req.Context(); ctx != nil {
if reqCtx, ok := ctx.Value("request_context").(*config.RequestContext); ok {
if reqCtx.ClientIP != "" {
req.Header.Set("X-Forwarded-For", reqCtx.ClientIP)
}
if reqCtx.AccessorID != "" {
req.Header.Set("X-Nomad-Accessor-ID", reqCtx.AccessorID)
}
}
}
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
Expand Down
12 changes: 12 additions & 0 deletions admissionctrl/validator/webhook_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/mxab/nacp/config"
"net/http"
"net/url"

Expand Down Expand Up @@ -34,6 +35,17 @@ func (w *WebhookValidator) Validate(job *api.Job) ([]error, error) {
if err != nil {
return nil, err
}
// Add context headers if available
if ctx := req.Context(); ctx != nil {
if reqCtx, ok := ctx.Value("request_context").(*config.RequestContext); ok {
if reqCtx.ClientIP != "" {
req.Header.Set("X-Forwarded-For", reqCtx.ClientIP)
}
if reqCtx.AccessorID != "" {
req.Header.Set("X-Nomad-Accessor-ID", reqCtx.AccessorID)
}
}
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
Expand Down
123 changes: 107 additions & 16 deletions cmd/nacp/nacp.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"os"
"regexp"
"strconv"
"strings"
"time"

"github.com/hashicorp/go-hclog"
Expand Down Expand Up @@ -44,6 +45,62 @@ var (
nomadTimeout = 310 * time.Second
)

// New function to get client IP
func getClientIP(r *http.Request) string {
// Check X-Forwarded-For header first
forwarded := r.Header.Get("X-Forwarded-For")
if forwarded != "" {
return strings.Split(forwarded, ",")[0]
}

// Fall back to RemoteAddr
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
}

func resolveTokenAccessor(transport *http.Transport, nomadAddress *url.URL, token string) (string, error) {
if token == "" {
return "", nil
}

client := &http.Client{
Transport: transport,
}
if transport == nil {
client = http.DefaultClient
}

selfURL := *nomadAddress
selfURL.Path = "/v1/acl/token/self"

req, err := http.NewRequest("GET", selfURL.String(), nil)
if err != nil {
return "", err
}

req.Header.Set("X-Nomad-Token", token)

resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to resolve token: %s", resp.Status)
}

var tokenInfo struct {
AccessorID string `json:"AccessorID"`
}

if err := json.NewDecoder(resp.Body).Decode(&tokenInfo); err != nil {
return "", err
}

return tokenInfo.AccessorID, nil
}

func NewProxyHandler(nomadAddress *url.URL, jobHandler *admissionctrl.JobHandler, appLogger hclog.Logger, transport *http.Transport) func(http.ResponseWriter, *http.Request) {

proxy := httputil.NewSingleHostReverseProxy(nomadAddress)
Expand Down Expand Up @@ -80,6 +137,25 @@ func NewProxyHandler(nomadAddress *url.URL, jobHandler *admissionctrl.JobHandler

appLogger.Info("Request received", "path", r.URL.Path, "method", r.Method)

ctx := r.Context()
reqCtx := &config.RequestContext{
ClientIP: getClientIP(r),
}

token := r.Header.Get("X-Nomad-Token")
if jobHandler.ResolveToken() {
accessorID, err := resolveTokenAccessor(transport, nomadAddress, token)
if err != nil {
appLogger.Error("Resolving token failed", "error", err)
writeError(w, err)
}
reqCtx.AccessorID = accessorID
}

// Store context
ctx = context.WithValue(ctx, "request_context", reqCtx)
r = r.WithContext(ctx)

var err error
//var err error
if isRegister(r) {
Expand Down Expand Up @@ -457,20 +533,28 @@ func buildServer(c *config.Config, appLogger hclog.Logger) (*http.Server, error)
}
proxyTransport.TLSClientConfig = nomadTlsConfig
}
jobMutators, err := createMutators(c, appLogger.Named("mutators"))

jobMutators, resolveTokenMutators, err := createMutators(c, appLogger.Named("mutators"))
if err != nil {
return nil, fmt.Errorf("failed to create mutators: %w", err)
}
jobValidators, err := createValidators(c, appLogger.Named("validators"))

jobValidators, resolveTokenValidators, err := createValidators(c, appLogger.Named("validators"))
if err != nil {
return nil, fmt.Errorf("failed to create validators: %w", err)
}

var resolveToken bool
if resolveTokenMutators || resolveTokenValidators {
resolveToken = true
}

handler := admissionctrl.NewJobHandler(

jobMutators,
jobValidators,
appLogger.Named("handler"),
resolveToken,
)

proxy := NewProxyHandler(backend, handler, appLogger, proxyTransport)
Expand Down Expand Up @@ -535,72 +619,79 @@ func createTlsConfig(caFile string, noClientCert bool) (*tls.Config, error) {
return tlsConfig, nil
}

func createMutators(c *config.Config, logger hclog.Logger) ([]admissionctrl.JobMutator, error) {
func createMutators(c *config.Config, logger hclog.Logger) ([]admissionctrl.JobMutator, bool, error) {
var jobMutators []admissionctrl.JobMutator
var resolveToken bool
for _, m := range c.Mutators {
if m.ResolveToken {
resolveToken = true
}
switch m.Type {

case "opa_json_patch":
notationVerifier, err := buildVerifierIfEnabled(m.OpaRule.Notation, logger.Named("notation_verifier"))
if err != nil {
return nil, err
return nil, resolveToken, err
}
mutator, err := mutator.NewOpaJsonPatchMutator(m.Name, m.OpaRule.Filename, m.OpaRule.Query, logger.Named("opa_mutator"), notationVerifier)
if err != nil {
return nil, err
return nil, resolveToken, err
}
jobMutators = append(jobMutators, mutator)

case "json_patch_webhook":
mutator, err := mutator.NewJsonPatchWebhookMutator(m.Name, m.Webhook.Endpoint, m.Webhook.Method, logger.Named("json_patch_webhook_mutator"))
if err != nil {
return nil, err
return nil, resolveToken, err
}
jobMutators = append(jobMutators, mutator)

default:
return nil, fmt.Errorf("unknown mutator type %s", m.Type)
return nil, resolveToken, fmt.Errorf("unknown mutator type %s", m.Type)
}

}
return jobMutators, nil
return jobMutators, resolveToken, nil
}
func createValidators(c *config.Config, logger hclog.Logger) ([]admissionctrl.JobValidator, error) {
func createValidators(c *config.Config, logger hclog.Logger) ([]admissionctrl.JobValidator, bool, error) {
var jobValidators []admissionctrl.JobValidator
var resolveToken bool
for _, v := range c.Validators {
if v.ResolveToken {
resolveToken = true
}
switch v.Type {
case "opa":
notationVerifier, err := buildVerifierIfEnabled(v.Notation, logger.Named("notation_verifier"))
if err != nil {
return nil, err
return nil, resolveToken, err
}
opaValidator, err := validator.NewOpaValidator(v.Name, v.OpaRule.Filename, v.OpaRule.Query, logger.Named("opa_validator"), notationVerifier)
if err != nil {
return nil, err
return nil, resolveToken, err
}
jobValidators = append(jobValidators, opaValidator)

case "webhook":
validator, err := validator.NewWebhookValidator(v.Name, v.Webhook.Endpoint, v.Webhook.Method, logger.Named("webhook_validator"))
if err != nil {
return nil, err
return nil, resolveToken, err
}
jobValidators = append(jobValidators, validator)
case "notation":
notationVerifier, err := buildVerifier(v.Notation, logger.Named("notation_verifier"))
if err != nil {
return nil, err
return nil, resolveToken, err
}
validator := validator.NewNotationValidator(logger.Named("notation_validator"), v.Name, notationVerifier)

jobValidators = append(jobValidators, validator)

default:
return nil, fmt.Errorf("unknown validator type %s", v.Type)
return nil, resolveToken, fmt.Errorf("unknown validator type %s", v.Type)
}

}
return jobValidators, nil
return jobValidators, resolveToken, nil
}
func buildVerifierIfEnabled(notationVerifierConfig *config.NotationVerifierConfig, logger hclog.Logger) (notation.ImageVerifier, error) {
if notationVerifierConfig == nil {
Expand Down
Loading
Loading