|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "log/slog" |
| 8 | + "net/http" |
| 9 | + "os/exec" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/criteo/command-launcher-registry/internal/config" |
| 13 | +) |
| 14 | + |
| 15 | +// CustomJWTAuth implements custom JWT authentication via external script |
| 16 | +type CustomJWTAuth struct { |
| 17 | + config config.CustomJWTConfig |
| 18 | + logger *slog.Logger |
| 19 | +} |
| 20 | + |
| 21 | +// NewCustomJWTAuth creates a new CustomJWT authenticator |
| 22 | +func NewCustomJWTAuth(cfg config.CustomJWTConfig, logger *slog.Logger) (*CustomJWTAuth, error) { |
| 23 | + if cfg.Script == "" { |
| 24 | + return nil, fmt.Errorf("custom_jwt script is required") |
| 25 | + } |
| 26 | + if _, err := exec.LookPath(cfg.Script); err != nil { |
| 27 | + return nil, fmt.Errorf("custom_jwt script not found or not executable: %v", err) |
| 28 | + } |
| 29 | + |
| 30 | + logger.Info("CustomJWT auth initialized", |
| 31 | + "script", cfg.Script, |
| 32 | + "required_group", cfg.RequiredGroup) |
| 33 | + |
| 34 | + return &CustomJWTAuth{ |
| 35 | + config: cfg, |
| 36 | + logger: logger, |
| 37 | + }, nil |
| 38 | +} |
| 39 | + |
| 40 | +// Authenticate validates Bearer token using external script |
| 41 | +func (a *CustomJWTAuth) Authenticate(r *http.Request) (*User, error) { |
| 42 | + token, err := a.extractBearerToken(r) |
| 43 | + if err != nil { |
| 44 | + return nil, err |
| 45 | + } |
| 46 | + |
| 47 | + groups, username, err := a.executeScript(token) |
| 48 | + if err != nil { |
| 49 | + return nil, err |
| 50 | + } |
| 51 | + |
| 52 | + if a.config.RequiredGroup != "" { |
| 53 | + if !a.hasGroup(groups, a.config.RequiredGroup) { |
| 54 | + a.logger.Warn("User is not a member of required group", |
| 55 | + "required_group", a.config.RequiredGroup, |
| 56 | + "source_ip", r.RemoteAddr) |
| 57 | + return nil, ErrForbidden |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + a.logger.Debug("CustomJWT authentication successful", |
| 62 | + "username", username, |
| 63 | + "source_ip", r.RemoteAddr) |
| 64 | + |
| 65 | + return &User{Username: username}, nil |
| 66 | +} |
| 67 | + |
| 68 | +// Middleware returns HTTP middleware for CustomJWT authentication |
| 69 | +func (a *CustomJWTAuth) Middleware() func(http.Handler) http.Handler { |
| 70 | + return func(next http.Handler) http.Handler { |
| 71 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 72 | + _, err := a.Authenticate(r) |
| 73 | + if err != nil { |
| 74 | + if errors.Is(err, ErrForbidden) { |
| 75 | + http.Error(w, "Forbidden", http.StatusForbidden) |
| 76 | + return |
| 77 | + } |
| 78 | + if errors.Is(err, ErrUnauthorized) { |
| 79 | + http.Error(w, "Unauthorized", http.StatusUnauthorized) |
| 80 | + return |
| 81 | + } |
| 82 | + http.Error(w, "Internal Server Error", http.StatusInternalServerError) |
| 83 | + return |
| 84 | + } |
| 85 | + |
| 86 | + next.ServeHTTP(w, r) |
| 87 | + }) |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +// extractBearerToken extracts the Bearer token from Authorization header |
| 92 | +func (a *CustomJWTAuth) extractBearerToken(r *http.Request) (string, error) { |
| 93 | + authHeader := r.Header.Get("Authorization") |
| 94 | + if authHeader == "" { |
| 95 | + return "", ErrUnauthorized |
| 96 | + } |
| 97 | + |
| 98 | + parts := strings.SplitN(authHeader, " ", 2) |
| 99 | + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { |
| 100 | + return "", ErrUnauthorized |
| 101 | + } |
| 102 | + |
| 103 | + token := strings.TrimSpace(parts[1]) |
| 104 | + if token == "" { |
| 105 | + return "", ErrUnauthorized |
| 106 | + } |
| 107 | + |
| 108 | + return token, nil |
| 109 | +} |
| 110 | + |
| 111 | +// executeScript runs the JWT validation script and returns groups and username |
| 112 | +func (a *CustomJWTAuth) executeScript(token string) ([]string, string, error) { |
| 113 | + cmd := exec.Command(a.config.Script, token) |
| 114 | + |
| 115 | + var stdout, stderr bytes.Buffer |
| 116 | + cmd.Stdout = &stdout |
| 117 | + cmd.Stderr = &stderr |
| 118 | + |
| 119 | + err := cmd.Run() |
| 120 | + if err != nil { |
| 121 | + if exitError, ok := err.(*exec.ExitError); ok { |
| 122 | + a.logger.Warn("Script failed", |
| 123 | + "exit_code", exitError.ExitCode(), |
| 124 | + "stderr", strings.TrimSpace(stderr.String())) |
| 125 | + return nil, "", ErrForbidden |
| 126 | + } |
| 127 | + a.logger.Error("Failed to execute script", |
| 128 | + "error", err) |
| 129 | + return nil, "", ErrInternal |
| 130 | + } |
| 131 | + |
| 132 | + groups, username := a.parseOutput(stdout.String()) |
| 133 | + return groups, username, nil |
| 134 | +} |
| 135 | + |
| 136 | +// parseOutput parses the script output to extract groups and optionally username |
| 137 | +// Expected format: one group per line, optionally with "username:value" on first line |
| 138 | +func (a *CustomJWTAuth) parseOutput(output string) ([]string, string) { |
| 139 | + var groups []string |
| 140 | + username := "jwt-user" |
| 141 | + |
| 142 | + lines := strings.Split(output, "\n") |
| 143 | + for i, line := range lines { |
| 144 | + line = strings.TrimSpace(line) |
| 145 | + if line == "" { |
| 146 | + continue |
| 147 | + } |
| 148 | + |
| 149 | + // First non-empty line might be username |
| 150 | + if i == 0 && strings.HasPrefix(line, "username:") { |
| 151 | + username = strings.TrimSpace(strings.TrimPrefix(line, "username:")) |
| 152 | + continue |
| 153 | + } |
| 154 | + |
| 155 | + groups = append(groups, line) |
| 156 | + } |
| 157 | + |
| 158 | + return groups, username |
| 159 | +} |
| 160 | + |
| 161 | +// hasGroup checks if the user has the required group |
| 162 | +func (a *CustomJWTAuth) hasGroup(groups []string, requiredGroup string) bool { |
| 163 | + for _, group := range groups { |
| 164 | + if group == requiredGroup { |
| 165 | + return true |
| 166 | + } |
| 167 | + } |
| 168 | + return false |
| 169 | +} |
0 commit comments