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

View File

@@ -1,10 +1,13 @@
package claims
import (
"fmt"
"oc-auth/conf"
"reflect"
"strings"
"cloud.o-forge.io/core/oc-lib/models/peer"
"github.com/google/go-cmp/cmp"
)
// ClaimService builds and verifies OAuth2 session claims
@@ -14,7 +17,7 @@ type ClaimService interface {
BuildConsentSession(clientID string, userId string, peer *peer.Peer) Claims
// DecodeClaimsInToken verifies permissions from claims extracted from a JWT
DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, error)
DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, string, error)
}
// SessionClaims contains access_token and id_token claim maps
@@ -32,6 +35,88 @@ var t = map[string]ClaimService{
"hydra": HydraClaims{},
}
func cleanMap(m map[string]interface{}) map[string]interface{} {
if m == nil {
return map[string]interface{}{}
}
ignored := map[string]bool{
"exp": true,
"iat": true,
"nbf": true,
}
out := make(map[string]interface{})
for k, v := range m {
if ignored[k] {
continue
}
switch val := v.(type) {
case map[string]interface{}:
out[k] = cleanMap(val)
default:
out[k] = val
}
}
return out
}
func (c *Claims) EqualExt(ext map[string]interface{}) bool {
claims := &Claims{}
claims.SessionFromExt(ext)
return c.EqualClaims(claims)
}
func (c *Claims) EqualClaims(claims *Claims, permsKey ...string) bool {
c.normalizeClaims()
claims.normalizeClaims()
if len(permsKey) > 0 {
for _, p := range permsKey {
if !(claims.Session.AccessToken[p] != nil && c.Session.AccessToken[p] != nil && claims.Session.AccessToken[p] == c.Session.AccessToken[p]) {
return false
}
}
return true
}
ok := reflect.DeepEqual(c.Session, claims.Session)
if !ok {
fmt.Println(cmp.Diff(c.Session, claims.Session))
}
return ok
}
func (c *Claims) normalizeClaims() {
c.Session.AccessToken = cleanMap(c.Session.AccessToken)
c.Session.IDToken = cleanMap(c.Session.IDToken)
}
func (c *Claims) SessionFromExt(ext map[string]interface{}) {
var access map[string]interface{}
var id map[string]interface{}
if v, ok := ext["access_token"].(map[string]interface{}); ok && v != nil {
access = v
} else {
access = map[string]interface{}{}
}
if v, ok := ext["id_token"].(map[string]interface{}); ok && v != nil {
id = v
} else {
id = map[string]interface{}{}
}
c.Session = SessionClaims{
AccessToken: access,
IDToken: id,
}
}
func GetClaims() ClaimService {
for k := range t {
if strings.Contains(conf.GetConfig().Auth, k) {

View File

@@ -81,22 +81,21 @@ func (h HydraClaims) clearBlank(path []string) []string {
}
// DecodeClaimsInToken verifies permissions from claims in a standard JWT (via introspection)
func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, error) {
func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, string, error) {
logger := oclib.GetLogger()
idTokenClaims := sessionClaims.Session.IDToken
// Signature verification: skip if signature is empty (internal requests)
if sig, ok := idTokenClaims["signature"].(string); ok && sig != "" {
if ok, err := h.DecodeSignature(host, sig, publicKey); !ok {
return false, err
return false, "", err
}
}
claims := sessionClaims.Session.AccessToken
if claims == nil {
return false, errors.New("no access_token claims found")
return false, "", errors.New("no access_token claims found")
}
path := strings.ReplaceAll(forward, "http://"+host, "")
splittedPath := h.clearBlank(strings.Split(path, "/"))
@@ -105,11 +104,11 @@ func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward str
if !ok {
continue
}
match := true
splittedP := h.clearBlank(strings.Split(pStr, "/"))
if len(splittedP) != len(splittedPath) {
continue
}
match := true
for i, v := range splittedP {
if strings.Contains(v, ":") { // is a param
continue
@@ -127,11 +126,11 @@ func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward str
Relation: "permits" + strings.ToUpper(meth.String()),
Object: pStr,
}
return perms_connectors.GetPermissionConnector("").CheckPermission(perm, nil, true), nil
return perms_connectors.GetPermissionConnector("").CheckPermission(perm, nil, true), m, nil
}
}
logger.Error().Msg("No permission found for " + method + " " + forward)
return false, errors.New("no permission found")
return false, "", errors.New("no permission found")
}
// BuildConsentSession builds the session payload for Hydra consent accept.
@@ -162,7 +161,9 @@ func (h HydraClaims) BuildConsentSession(clientID string, userId string, p *peer
return c
}
c.Session.IDToken["username"] = userId
c.Session.AccessToken["peer_id"] = p.UUID
c.Session.IDToken["user_id"] = userId
c.Session.IDToken["peer_id"] = p.UUID
c.Session.IDToken["client_id"] = clientID
@@ -172,6 +173,13 @@ func (h HydraClaims) BuildConsentSession(clientID string, userId string, p *peer
return c
}
c.Session.IDToken["groups"] = groups
roles, err := perms_connectors.KetoConnector{}.GetRoleByUser(userId)
if err != nil {
logger.Error().Msg("Failed to get roles for user " + userId + ": " + err.Error())
return c
}
c.Session.IDToken["roles"] = roles
c.Session.IDToken["signature"] = sign
return c
}

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"oc-auth/conf"
"oc-auth/infrastructure/utils"
"strings"
oclib "cloud.o-forge.io/core/oc-lib"
"cloud.o-forge.io/core/oc-lib/tools"
@@ -128,8 +129,12 @@ func (k KetoConnector) CreatePermission(permID string, relation string, internal
if err != nil {
return "", 422, err
}
k.BindPermission("admin", permID, "permits"+meth.String())
return k.creates(permID, "permits"+meth.String(), k.scope())
id, code, err := k.creates(permID, "permits"+meth.String(), k.scope())
if err != nil && !strings.Contains(err.Error(), "already exist") {
return id, code, err
}
k.BindPermission(conf.GetConfig().AdminRole, permID, "permits"+meth.String())
return id, code, nil
}
func (k KetoConnector) creates(object string, relation string, subject string) (string, int, error) {