| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | // Package oidcserver provides a minimal mock OIDC server for e2e testing. |
| 16 | // It implements three endpoints: |
| 17 | // - /.well-known/openid-configuration (discovery) |
| 18 | // - /jwks (JSON Web Key Set) |
| 19 | // - /token (client_credentials grant) |
| 20 | package oidcserver |
| 21 |
| 22 | import ( |
| 23 | "crypto" |
| 24 | "crypto/rand" |
| 25 | "crypto/rsa" |
| 26 | "crypto/sha256" |
| 27 | "encoding/base64" |
| 28 | "encoding/json" |
| 29 | "fmt" |
| 30 | "math/big" |
| 31 | "net" |
| 32 | "net/http" |
| 33 | "strconv" |
| 34 | "sync/atomic" |
| 35 | "time" |
| 36 | ) |
| 37 |
| 38 | type Server struct { |
| 39 | bindAddr string |
| 40 | bindPort int |
| 41 | l net.Listener |
| 42 | hs *http.Server |
| 43 |
| 44 | privateKey *rsa.PrivateKey |
| 45 | kid string |
| 46 |
| 47 | clientID string |
| 48 | clientSecret string |
| 49 | audience string |
| 50 | subject string |
| 51 | expiresIn int // seconds; 0 means omit expires_in from token response |
| 52 |
| 53 | tokenRequestCount atomic.Int64 |
| 54 | } |
| 55 |
| 56 | const maxTokenRequestBodySize = 1 << 20 |
| 57 |
| 58 | type Option func(*Server) |
| 59 |
| 60 | func WithBindPort(port int) Option { |
| 61 | return func(s *Server) { s.bindPort = port } |
| 62 | } |
| 63 |
| 64 | func WithExpiresIn(seconds int) Option { |
| 65 | return func(s *Server) { s.expiresIn = seconds } |
| 66 | } |
| 67 |
| 68 | func New(options ...Option) *Server { |
| 69 | s := &Server{ |
| 70 | bindAddr: "127.0.0.1", |
| 71 | kid: "test-key-1", |
| 72 | clientID: "test-client", |
| 73 | clientSecret: "test-secret", |
| 74 | audience: "frps", |
| 75 | subject: "test-service", |
| 76 | expiresIn: 3600, |
| 77 | } |
| 78 | for _, opt := range options { |
| 79 | opt(s) |
| 80 | } |
| 81 | return s |
| 82 | } |
| 83 |
| 84 | func (s *Server) Run() error { |
| 85 | key, err := rsa.GenerateKey(rand.Reader, 2048) |
| 86 | if err != nil { |
| 87 | return fmt.Errorf("generate RSA key: %w", err) |
| 88 | } |
| 89 | s.privateKey = key |
| 90 |
| 91 | s.l, err = net.Listen("tcp", net.JoinHostPort(s.bindAddr, strconv.Itoa(s.bindPort))) |
| 92 | if err != nil { |
| 93 | return err |
| 94 | } |
| 95 | s.bindPort = s.l.Addr().(*net.TCPAddr).Port |
| 96 |
| 97 | mux := http.NewServeMux() |
| 98 | mux.HandleFunc("/.well-known/openid-configuration", s.handleDiscovery) |
| 99 | mux.HandleFunc("/jwks", s.handleJWKS) |
| 100 | mux.HandleFunc("/token", s.handleToken) |
| 101 |
| 102 | s.hs = &http.Server{ |
| 103 | Handler: mux, |
| 104 | ReadHeaderTimeout: time.Minute, |
| 105 | } |
| 106 | go func() { _ = s.hs.Serve(s.l) }() |
| 107 | return nil |
| 108 | } |
| 109 |
| 110 | func (s *Server) Close() error { |
| 111 | if s.hs != nil { |
| 112 | return s.hs.Close() |
| 113 | } |
| 114 | return nil |
| 115 | } |
| 116 |
| 117 | func (s *Server) BindAddr() string { return s.bindAddr } |
| 118 | func (s *Server) BindPort() int { return s.bindPort } |
| 119 |
| 120 | func (s *Server) Issuer() string { |
| 121 | return fmt.Sprintf("http://%s:%d", s.bindAddr, s.bindPort) |
| 122 | } |
| 123 |
| 124 | func (s *Server) TokenEndpoint() string { |
| 125 | return s.Issuer() + "/token" |
| 126 | } |
| 127 |
| 128 | // TokenRequestCount returns the number of successful token requests served. |
| 129 | func (s *Server) TokenRequestCount() int64 { |
| 130 | return s.tokenRequestCount.Load() |
| 131 | } |
| 132 |
| 133 | func (s *Server) handleDiscovery(w http.ResponseWriter, _ *http.Request) { |
| 134 | issuer := s.Issuer() |
| 135 | w.Header().Set("Content-Type", "application/json") |
| 136 | _ = json.NewEncoder(w).Encode(map[string]any{ |
| 137 | "issuer": issuer, |
| 138 | "token_endpoint": issuer + "/token", |
| 139 | "jwks_uri": issuer + "/jwks", |
| 140 | "response_types_supported": []string{"code"}, |
| 141 | "subject_types_supported": []string{"public"}, |
| 142 | "id_token_signing_alg_values_supported": []string{"RS256"}, |
| 143 | }) |
| 144 | } |
| 145 |
| 146 | func (s *Server) handleJWKS(w http.ResponseWriter, _ *http.Request) { |
| 147 | pub := &s.privateKey.PublicKey |
| 148 | w.Header().Set("Content-Type", "application/json") |
| 149 | _ = json.NewEncoder(w).Encode(map[string]any{ |
| 150 | "keys": []map[string]any{ |
| 151 | { |
| 152 | "kty": "RSA", |
| 153 | "alg": "RS256", |
| 154 | "use": "sig", |
| 155 | "kid": s.kid, |
| 156 | "n": base64.RawURLEncoding.EncodeToString(pub.N.Bytes()), |
| 157 | "e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(pub.E)).Bytes()), |
| 158 | }, |
| 159 | }, |
| 160 | }) |
| 161 | } |
| 162 |
| 163 | func (s *Server) handleToken(w http.ResponseWriter, r *http.Request) { |
| 164 | if r.Method != http.MethodPost { |
| 165 | http.Error(w, "method not allowed", http.StatusMethodNotAllowed) |
| 166 | return |
| 167 | } |
| 168 | r.Body = http.MaxBytesReader(w, r.Body, maxTokenRequestBodySize) |
| 169 | if err := r.ParseForm(); err != nil { |
| 170 | w.Header().Set("Content-Type", "application/json") |
| 171 | w.WriteHeader(http.StatusBadRequest) |
| 172 | _ = json.NewEncoder(w).Encode(map[string]any{ |
| 173 | "error": "invalid_request", |
| 174 | }) |
| 175 | return |
| 176 | } |
| 177 |
| 178 | if r.Form.Get("grant_type") != "client_credentials" { |
| 179 | w.Header().Set("Content-Type", "application/json") |
| 180 | w.WriteHeader(http.StatusBadRequest) |
| 181 | _ = json.NewEncoder(w).Encode(map[string]any{ |
| 182 | "error": "unsupported_grant_type", |
| 183 | }) |
| 184 | return |
| 185 | } |
| 186 |
| 187 | // Accept credentials from Basic Auth or form body. |
| 188 | clientID, clientSecret, ok := r.BasicAuth() |
| 189 | if !ok { |
| 190 | clientID = r.Form.Get("client_id") |
| 191 | clientSecret = r.Form.Get("client_secret") |
| 192 | } |
| 193 | if clientID != s.clientID || clientSecret != s.clientSecret { |
| 194 | w.Header().Set("Content-Type", "application/json") |
| 195 | w.WriteHeader(http.StatusUnauthorized) |
| 196 | _ = json.NewEncoder(w).Encode(map[string]any{ |
| 197 | "error": "invalid_client", |
| 198 | }) |
| 199 | return |
| 200 | } |
| 201 |
| 202 | token, err := s.signJWT() |
| 203 | if err != nil { |
| 204 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 205 | return |
| 206 | } |
| 207 |
| 208 | resp := map[string]any{ |
| 209 | "access_token": token, |
| 210 | "token_type": "Bearer", |
| 211 | } |
| 212 | if s.expiresIn > 0 { |
| 213 | resp["expires_in"] = s.expiresIn |
| 214 | } |
| 215 |
| 216 | s.tokenRequestCount.Add(1) |
| 217 | w.Header().Set("Content-Type", "application/json") |
| 218 | _ = json.NewEncoder(w).Encode(resp) |
| 219 | } |
| 220 |
| 221 | func (s *Server) signJWT() (string, error) { |
| 222 | now := time.Now() |
| 223 | header, _ := json.Marshal(map[string]string{ |
| 224 | "alg": "RS256", |
| 225 | "kid": s.kid, |
| 226 | "typ": "JWT", |
| 227 | }) |
| 228 | claims, _ := json.Marshal(map[string]any{ |
| 229 | "iss": s.Issuer(), |
| 230 | "sub": s.subject, |
| 231 | "aud": s.audience, |
| 232 | "iat": now.Unix(), |
| 233 | "exp": now.Add(1 * time.Hour).Unix(), |
| 234 | }) |
| 235 |
| 236 | headerB64 := base64.RawURLEncoding.EncodeToString(header) |
| 237 | claimsB64 := base64.RawURLEncoding.EncodeToString(claims) |
| 238 | signingInput := headerB64 + "." + claimsB64 |
| 239 |
| 240 | h := sha256.Sum256([]byte(signingInput)) |
| 241 | sig, err := rsa.SignPKCS1v15(rand.Reader, s.privateKey, crypto.SHA256, h[:]) |
| 242 | if err != nil { |
| 243 | return "", err |
| 244 | } |
| 245 | return signingInput + "." + base64.RawURLEncoding.EncodeToString(sig), nil |
| 246 | } |