|
| 1 | +require "../controller" |
| 2 | +require "../router" |
| 3 | +require "../oauth2/pkce" |
| 4 | +require "../oauth2/token_exchange" |
| 5 | +require "../../auth/jwt/jwks_fetcher" |
| 6 | + |
| 7 | +module LavinMQ |
| 8 | + module HTTP |
| 9 | + class OAuthController |
| 10 | + include Router |
| 11 | + |
| 12 | + Log = LavinMQ::Log.for "http.oauth" |
| 13 | + |
| 14 | + def initialize(@authenticator : Auth::Authenticator) |
| 15 | + register_routes |
| 16 | + end |
| 17 | + |
| 18 | + private def register_routes |
| 19 | + get "/oauth/enabled" { |context, _params| handle_enabled(context) } |
| 20 | + get "/oauth/authorize" { |context, _params| handle_authorize(context) } |
| 21 | + get "/oauth/callback" { |context, _params| handle_callback(context) } |
| 22 | + end |
| 23 | + |
| 24 | + private def handle_enabled(context) : ::HTTP::Server::Context |
| 25 | + config = Config.instance |
| 26 | + enabled = !!(config.oauth_client_id && config.oauth_issuer_url) |
| 27 | + context.response.content_type = "application/json" |
| 28 | + {enabled: enabled}.to_json(context.response) |
| 29 | + context |
| 30 | + end |
| 31 | + |
| 32 | + private def handle_authorize(context) : ::HTTP::Server::Context |
| 33 | + config = Config.instance |
| 34 | + issuer_url = config.oauth_issuer_url || oauth_error(context, 503, "OAuth not configured") |
| 35 | + client_id = config.oauth_client_id || oauth_error(context, 503, "OAuth not configured") |
| 36 | + |
| 37 | + oidc = Auth::JWT::JWKSFetcher.new(issuer_url, config.oauth_jwks_cache_ttl).fetch_oidc_config |
| 38 | + auth_ep = oidc.authorization_endpoint || raise "OIDC missing authorization_endpoint" |
| 39 | + |
| 40 | + verifier, challenge = OAuth2::PKCE.generate |
| 41 | + state = Random::Secure.urlsafe_base64(32) |
| 42 | + |
| 43 | + context.response.cookies << ::HTTP::Cookie.new( |
| 44 | + name: "oauth_state", |
| 45 | + value: "#{state}:#{verifier}", |
| 46 | + path: "/oauth", |
| 47 | + http_only: true, |
| 48 | + secure: true, |
| 49 | + samesite: ::HTTP::Cookie::SameSite::Lax, |
| 50 | + max_age: 5.minutes |
| 51 | + ) |
| 52 | + |
| 53 | + redirect_uri = build_redirect_uri(context.request) |
| 54 | + params = ::URI::Params.build do |p| |
| 55 | + p.add "client_id", client_id |
| 56 | + p.add "redirect_uri", redirect_uri |
| 57 | + p.add "response_type", "code" |
| 58 | + p.add "scope", "openid profile" |
| 59 | + p.add "code_challenge", challenge |
| 60 | + p.add "code_challenge_method", "S256" |
| 61 | + p.add "state", state |
| 62 | + end |
| 63 | + |
| 64 | + context.response.content_type = "application/json" |
| 65 | + {authorize_url: "#{auth_ep}?#{params}"}.to_json(context.response) |
| 66 | + context |
| 67 | + rescue OAuthError |
| 68 | + context |
| 69 | + rescue ex |
| 70 | + Log.error(exception: ex) { "OAuth authorize failed: #{ex.message}" } |
| 71 | + context.response.status_code = 502 |
| 72 | + context.response.content_type = "application/json" |
| 73 | + {reason: "OAuth authorization failed"}.to_json(context.response) |
| 74 | + context |
| 75 | + end |
| 76 | + |
| 77 | + private def handle_callback(context) : ::HTTP::Server::Context |
| 78 | + config = Config.instance |
| 79 | + issuer_url = config.oauth_issuer_url || oauth_redirect_error(context, "OAuth not configured") |
| 80 | + client_id = config.oauth_client_id || oauth_redirect_error(context, "OAuth not configured") |
| 81 | + |
| 82 | + cookie_value = context.request.cookies["oauth_state"]?.try(&.value) || oauth_redirect_error(context, "Missing OAuth state") |
| 83 | + sep = cookie_value.index(':') || oauth_redirect_error(context, "Invalid OAuth state cookie") |
| 84 | + cookie_state = cookie_value[0...sep] |
| 85 | + code_verifier = cookie_value[sep + 1..] |
| 86 | + |
| 87 | + oauth_redirect_error(context, "State mismatch") unless context.request.query_params["state"]? == cookie_state |
| 88 | + code = context.request.query_params["code"]? || oauth_redirect_error(context, "Missing authorization code") |
| 89 | + |
| 90 | + oidc = Auth::JWT::JWKSFetcher.new(issuer_url, config.oauth_jwks_cache_ttl).fetch_oidc_config |
| 91 | + token_ep = oidc.token_endpoint || raise "OIDC missing token_endpoint" |
| 92 | + |
| 93 | + redirect_uri = build_redirect_uri(context.request) |
| 94 | + token_response = OAuth2::TokenExchange.new(token_ep, client_id).exchange(code, redirect_uri, code_verifier) |
| 95 | + |
| 96 | + auth_context = Auth::Context.new("", token_response.access_token.to_slice, context.request.remote_address) |
| 97 | + oauth_redirect_error(context, "Token validation failed") unless @authenticator.authenticate(auth_context) |
| 98 | + |
| 99 | + context.response.cookies << ::HTTP::Cookie.new( |
| 100 | + name: "m", |
| 101 | + value: token_response.access_token, |
| 102 | + path: "/", |
| 103 | + secure: true, |
| 104 | + samesite: ::HTTP::Cookie::SameSite::Strict, |
| 105 | + max_age: 8.hours |
| 106 | + ) |
| 107 | + context.response.cookies << ::HTTP::Cookie.new( |
| 108 | + name: "oauth_state", |
| 109 | + value: "", |
| 110 | + path: "/oauth", |
| 111 | + max_age: 0.seconds |
| 112 | + ) |
| 113 | + |
| 114 | + context.response.status = ::HTTP::Status::FOUND |
| 115 | + context.response.headers["Location"] = "/" |
| 116 | + context |
| 117 | + rescue OAuthError |
| 118 | + context |
| 119 | + rescue ex |
| 120 | + Log.error(exception: ex) { "OAuth callback failed: #{ex.message}" } |
| 121 | + context.response.status = ::HTTP::Status::FOUND |
| 122 | + context.response.headers["Location"] = "/login?error=#{URI.encode_path_segment("OAuth authentication failed")}" |
| 123 | + context |
| 124 | + end |
| 125 | + |
| 126 | + private def oauth_error(context, status_code, message) : NoReturn |
| 127 | + context.response.status_code = status_code |
| 128 | + context.response.content_type = "application/json" |
| 129 | + {reason: message}.to_json(context.response) |
| 130 | + raise OAuthError.new |
| 131 | + end |
| 132 | + |
| 133 | + private def oauth_redirect_error(context, message) : NoReturn |
| 134 | + context.response.status = ::HTTP::Status::FOUND |
| 135 | + context.response.headers["Location"] = "/login?error=#{URI.encode_path_segment(message)}" |
| 136 | + raise OAuthError.new |
| 137 | + end |
| 138 | + |
| 139 | + private def build_redirect_uri(request : ::HTTP::Request) : String |
| 140 | + if base_url = Config.instance.oauth_mgmt_base_url |
| 141 | + "#{base_url.chomp("/")}/oauth/callback" |
| 142 | + else |
| 143 | + host = request.headers["Host"]? || "localhost" |
| 144 | + scheme = request.headers["X-Forwarded-Proto"]? || "http" |
| 145 | + "#{scheme}://#{host}/oauth/callback" |
| 146 | + end |
| 147 | + end |
| 148 | + |
| 149 | + class OAuthError < Exception; end |
| 150 | + end |
| 151 | + end |
| 152 | +end |
0 commit comments