Forward For WS

This commit is contained in:
mr
2026-04-01 17:16:18 +02:00
parent 744caf9a5e
commit 284667e95c
10 changed files with 570 additions and 66 deletions

View File

@@ -12,6 +12,9 @@ type AuthConnector interface {
Status() tools.State
// Login/Consent Provider endpoints (Hydra redirects here)
// InitiateLogin starts a new OAuth2 flow server-side and returns the login_challenge
// generated by Hydra. Useful for thick clients that cannot follow browser redirects.
InitiateLogin(clientID string, redirectURI string) (string, error)
GetLoginChallenge(challenge string) (*LoginChallenge, error)
AcceptLogin(challenge string, subject string) (*Redirect, error)
RejectLogin(challenge string, reason string) (*Redirect, error)
@@ -27,12 +30,21 @@ type AuthConnector interface {
RevokeToken(token string, clientID string) error
RefreshToken(refreshToken string, clientID string) (*TokenResponse, error)
// Server-side flow completion (for thick clients that cannot follow browser redirects)
// FollowToConsentChallenge follows the redirect_to from AcceptLogin to extract the consent_challenge.
// loginChallenge is used to replay the CSRF cookie set during InitiateLogin.
FollowToConsentChallenge(redirectTo string, loginChallenge string) (string, error)
// ExchangeCodeForToken follows the redirect_to from AcceptConsent, extracts the auth code,
// and exchanges it for a token at Hydra's token endpoint.
// loginChallenge is used to replay the CSRF cookie and is cleaned up after use.
ExchangeCodeForToken(redirectTo string, clientID string, loginChallenge string) (*TokenResponse, error)
// CheckAuthForward validates the token and permissions for a forward auth request.
// Returns an HTTP status code:
// 200 — token active and permissions granted
// 401 — token missing, invalid, or inactive → caller should redirect to login
// 403 — token valid but permissions denied → caller should return forbidden
CheckAuthForward(reqToken string, publicKey string, host string, method string, forward string, external bool) int
CheckAuthForward(reqToken string, publicKey string, host string, method string, forward string, external bool) (*claims.Claims, string, int)
}
// Token is the unified token response returned to clients
@@ -60,12 +72,12 @@ type Redirect struct {
// LoginChallenge contains the details of a Hydra login challenge
type LoginChallenge struct {
Skip bool `json:"skip"`
Subject string `json:"subject"`
Challenge string `json:"challenge"`
Client map[string]interface{} `json:"client"`
RequestURL string `json:"request_url"`
SessionID string `json:"session_id"`
Skip bool `json:"skip"`
Subject string `json:"subject"`
Challenge string `json:"challenge"`
Client map[string]interface{} `json:"client"`
RequestURL string `json:"request_url"`
SessionID string `json:"session_id"`
}
// LogoutChallenge contains the details of a Hydra logout challenge

View File

@@ -1,15 +1,19 @@
package auth_connectors
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"oc-auth/conf"
"oc-auth/infrastructure/claims"
"strings"
"sync"
oclib "cloud.o-forge.io/core/oc-lib"
"cloud.o-forge.io/core/oc-lib/models/peer"
@@ -17,7 +21,8 @@ import (
)
type HydraConnector struct {
Caller *tools.HTTPCaller
Caller *tools.HTTPCaller
cookieJars sync.Map // map[loginChallenge] *cookiejar.Jar
}
func (h *HydraConnector) Status() tools.State {
@@ -59,6 +64,59 @@ func (h *HydraConnector) getPath(isAdmin bool, isOauth bool) string {
return "http://" + host + ":" + port + oauth
}
// InitiateLogin starts a new OAuth2 authorization flow with Hydra server-side.
// It calls Hydra's /oauth2/auth endpoint without following the redirect, then extracts
// the login_challenge from the Location header. For thick clients that cannot follow
// browser redirects.
func (h *HydraConnector) InitiateLogin(clientID string, redirectURI string) (string, error) {
stateBytes := make([]byte, 16)
if _, err := rand.Read(stateBytes); err != nil {
return "", fmt.Errorf("failed to generate state: %w", err)
}
state := hex.EncodeToString(stateBytes)
params := fmt.Sprintf("client_id=%s&response_type=code&scope=openid&state=%s",
url.QueryEscape(clientID), state)
if redirectURI != "" {
params += "&redirect_uri=" + url.QueryEscape(redirectURI)
}
authURL := h.getPath(false, false) + "/oauth2/auth?" + params
jar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: jar,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse // do not follow redirects
},
}
resp, err := client.Get(authURL)
if err != nil {
return "", fmt.Errorf("failed to initiate login with Hydra: %w", err)
}
defer resp.Body.Close()
location := resp.Header.Get("Location")
if location == "" {
return "", fmt.Errorf("hydra did not return a redirect location (status %d)", resp.StatusCode)
}
parsed, err := url.Parse(location)
if err != nil {
return "", fmt.Errorf("failed to parse redirect location: %w", err)
}
challenge := parsed.Query().Get("login_challenge")
if challenge == "" {
return "", fmt.Errorf("login_challenge not found in redirect location: %s", location)
}
// Save the cookie jar so server-side flow completion can reuse the CSRF cookie
h.cookieJars.Store(challenge, jar)
return challenge, nil
}
// GetLoginChallenge retrieves login challenge details from Hydra admin API
func (h *HydraConnector) GetLoginChallenge(challenge string) (*LoginChallenge, error) {
logger := oclib.GetLogger()
@@ -192,10 +250,10 @@ func (h *HydraConnector) GetConsentChallenge(challenge string) (*ConsentChalleng
func (h *HydraConnector) AcceptConsent(challenge string, grantScope []string, session claims.Claims) (*Redirect, error) {
logger := oclib.GetLogger()
body := map[string]interface{}{
"grant_scope": grantScope,
"grant_scope": grantScope,
"grant_access_token_audience": grantScope, // grant requested audience
"remember": true,
"remember_for": 3600,
"remember": true,
"remember_for": 3600,
"session": map[string]interface{}{
"access_token": session.Session.AccessToken,
"id_token": session.Session.IDToken,
@@ -303,14 +361,14 @@ func (h *HydraConnector) RefreshToken(refreshToken string, clientID string) (*To
// It introspects the token via Hydra then checks permissions via Keto.
// Only requests from our own peer (external == false) are accepted.
// Returns 200 (OK), 401 (token inactive/invalid → redirect to login), or 403 (permission denied).
func (h *HydraConnector) CheckAuthForward(reqToken string, publicKey string, host string, method string, forward string, external bool) int {
func (h *HydraConnector) CheckAuthForward(reqToken string, publicKey string, host string, method string, forward string, external bool) (*claims.Claims, string, int) {
if forward == "" || method == "" {
return http.StatusUnauthorized
return nil, "", http.StatusUnauthorized
}
// Defense in depth: only SELF peer requests are allowed.
if external {
/*if external {
return http.StatusUnauthorized
}
}*/
logger := oclib.GetLogger()
// Introspect the token via Hydra.
@@ -320,7 +378,7 @@ func (h *HydraConnector) CheckAuthForward(reqToken string, publicKey string, hos
if err != nil {
logger.Error().Msg("Forward auth introspect failed: " + err.Error())
}
return http.StatusUnauthorized
return nil, "", http.StatusUnauthorized
}
// Build session claims from Hydra's introspection "ext" field.
@@ -345,15 +403,147 @@ func (h *HydraConnector) CheckAuthForward(reqToken string, publicKey string, hos
// Check permissions via Keto.
// A valid token with insufficient permissions → 403 (authenticated, not authorized).
ok, err := claims.GetClaims().DecodeClaimsInToken(host, method, forward, sessionClaims, publicKey, external)
ok, permKey, err := claims.GetClaims().DecodeClaimsInToken(host, method, forward, sessionClaims, publicKey, external)
if err != nil {
logger.Error().Msg("Failed to decode claims in forward auth: " + err.Error())
return http.StatusForbidden
return nil, "", http.StatusForbidden
}
if !ok {
return http.StatusForbidden
return nil, "", http.StatusForbidden
}
return http.StatusOK
return &sessionClaims, permKey, http.StatusOK
}
// FollowToConsentChallenge follows the redirect_to returned by AcceptLogin.
// Hydra redirects once to the consent URL — this extracts the consent_challenge from it.
// loginChallenge is used to retrieve the CSRF cookie jar saved during InitiateLogin.
func (h *HydraConnector) FollowToConsentChallenge(redirectTo string, loginChallenge string) (string, error) {
// The redirect_to URL uses the public host (via reverse proxy).
// Rewrite it to hit Hydra directly using its internal address.
internalURL, err := rewriteToInternalHydra(h, redirectTo)
if err != nil {
return "", fmt.Errorf("failed to rewrite redirect URL: %w", err)
}
var jar http.CookieJar
if v, ok := h.cookieJars.Load(loginChallenge); ok {
jar = v.(*cookiejar.Jar)
}
client := &http.Client{
Jar: jar,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Get(internalURL)
if err != nil {
return "", fmt.Errorf("failed to follow login redirect: %w", err)
}
defer resp.Body.Close()
location := resp.Header.Get("Location")
if location == "" {
return "", fmt.Errorf("no redirect location after following login redirect (status %d)", resp.StatusCode)
}
parsed, err := url.Parse(location)
if err != nil {
return "", fmt.Errorf("failed to parse consent redirect: %w", err)
}
challenge := parsed.Query().Get("consent_challenge")
if challenge == "" {
return "", fmt.Errorf("consent_challenge not found in redirect: %s", location)
}
return challenge, nil
}
// ExchangeCodeForToken follows the redirect_to returned by AcceptConsent to extract the
// authorization code, then exchanges it for a token at Hydra's token endpoint.
// loginChallenge is used to retrieve the CSRF cookie jar and clean it up after use.
func (h *HydraConnector) ExchangeCodeForToken(redirectTo string, clientID string, loginChallenge string) (*TokenResponse, error) {
internalURL, err := rewriteToInternalHydra(h, redirectTo)
if err != nil {
return nil, fmt.Errorf("failed to rewrite redirect URL: %w", err)
}
var jar http.CookieJar
if v, ok := h.cookieJars.Load(loginChallenge); ok {
jar = v.(*cookiejar.Jar)
}
client := &http.Client{
Jar: jar,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Get(internalURL)
if err != nil {
return nil, fmt.Errorf("failed to follow consent redirect: %w", err)
}
defer resp.Body.Close()
location := resp.Header.Get("Location")
if location == "" {
return nil, fmt.Errorf("no redirect after consent (status %d)", resp.StatusCode)
}
parsed, err := url.Parse(location)
if err != nil {
return nil, fmt.Errorf("failed to parse code redirect: %w", err)
}
code := parsed.Query().Get("code")
if code == "" {
return nil, fmt.Errorf("code not found in redirect: %s", location)
}
// Reconstruct redirect_uri without query/fragment — must match the registered value
parsed.RawQuery = ""
parsed.Fragment = ""
redirectURI := parsed.String()
cfg := conf.GetConfig()
vals := url.Values{}
vals.Add("grant_type", "authorization_code")
vals.Add("code", code)
vals.Add("client_id", clientID)
vals.Add("client_secret", cfg.ClientSecret)
vals.Add("redirect_uri", redirectURI)
resp2, err := h.Caller.CallForm(http.MethodPost, h.getPath(false, true), "/token", vals,
"application/x-www-form-urlencoded", true)
if err != nil {
return nil, fmt.Errorf("failed to exchange code for token: %w", err)
}
defer resp2.Body.Close()
b, err := io.ReadAll(resp2.Body)
if err != nil {
return nil, err
}
if resp2.StatusCode >= 300 {
return nil, fmt.Errorf("token exchange failed (%s): %s", resp2.Status, string(b))
}
var result TokenResponse
if err := json.Unmarshal(b, &result); err != nil {
return nil, err
}
// Cookie jar no longer needed — clean up
h.cookieJars.Delete(loginChallenge)
return &result, nil
}
// rewriteToInternalHydra rewrites a public-facing Hydra URL to use the internal Hydra address.
// The redirect_to from Hydra uses the public host/port (possibly behind a reverse proxy),
// but server-side follow-ups must hit Hydra directly.
// It keeps the path suffix after "/oauth2" and the full query string.
func rewriteToInternalHydra(h *HydraConnector, publicURL string) (string, error) {
parsed, err := url.Parse(publicURL)
if err != nil {
return "", fmt.Errorf("invalid redirect URL: %w", err)
}
// Extract the path segment from "/oauth2" onward (e.g. "/oauth2/auth")
const marker = "/oauth2"
idx := strings.Index(parsed.Path, marker)
if idx < 0 {
return "", fmt.Errorf("redirect URL has no /oauth2 path segment: %s", publicURL)
}
suffix := parsed.Path[idx:] // e.g. "/oauth2/auth"
internal := h.getPath(false, false) + suffix
if parsed.RawQuery != "" {
internal += "?" + parsed.RawQuery
}
return internal, nil
}
// extractBearerToken extracts the token from a "Bearer xxx" Authorization header value