Oc Auth x Hydra x LDAP : draft of claims enrich for traefik + draft of forwarding

This commit is contained in:
mr
2024-10-28 14:58:11 +01:00
parent 05c4aab72a
commit 7198c40d30
37 changed files with 4181 additions and 610 deletions

View File

@@ -1,84 +0,0 @@
package controllers
import (
"fmt"
"net/http"
beego "github.com/beego/beego/v2/server/web"
)
// Operations about auth
type AuthController struct {
beego.Controller
}
// @Title Get
// @Description find auth by authid
// @Param authId path string true "the authid you want to get"
// @Success 200 {auth} models.auth
// @Failure 403 :authId is empty
// @router /discover/:url [get]
func (o *AuthController) GetConfig() {
url := o.Ctx.Input.Param(":url")
response, err := http.Get(url + "/.well-known/openid-configuration")
if err != nil {
fmt.Println(err)
}
fmt.Println(url)
// read response body
data := make([]byte, 1024)
_, err = response.Body.Read(data)
if err != nil {
fmt.Println(err)
}
o.Data["json"] = data
o.ServeJSON()
}
// @Title Create
// @Description create auths
// @Param body body []models.auth true "The auth content"
// @Success 200 {string} models.auth.Id
// @Failure 403 body is empty
// @router / [post]
func (o *AuthController) Post() {
// store and return Id or post with UUID
o.Data["json"] = map[string]string{"Id": "?"}
o.ServeJSON()
}
// @Title Get
// @Description find auth by authid
// @Param authId path string true "the authid you want to get"
// @Success 200 {auth} models.auth
// @Failure 403 :authId is empty
// @router /:authId [get]
func (o *AuthController) Get() {
authId := o.Ctx.Input.Param(":authId")
fmt.Println(authId)
o.ServeJSON()
}
// @Title Find
// @Description find auths with query
// @Param query path string true "the keywords you need"
// @Success 200 {auths} []models.auth
// @Failure 403
// @router /find/:query [get]
func (o *AuthController) Find() {
query := o.Ctx.Input.Param(":query")
fmt.Println(query)
o.ServeJSON()
}
// @Title Delete
// @Description delete the auth
// @Param authId path string true "The authId you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 authId is empty
// @router /:authId [delete]
func (o *AuthController) Delete() {
authId := o.Ctx.Input.Param(":authId")
fmt.Println(authId)
o.ServeJSON()
}

225
controllers/oauth2.go Normal file
View File

@@ -0,0 +1,225 @@
package controllers
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"oc-auth/infrastructure"
auth_connectors "oc-auth/infrastructure/auth_connector"
"oc-auth/infrastructure/claims"
"strings"
oclib "cloud.o-forge.io/core/oc-lib"
model "cloud.o-forge.io/core/oc-lib/models/peer"
"cloud.o-forge.io/core/oc-lib/static"
beego "github.com/beego/beego/v2/server/web"
)
// Operations about auth
type OAuthController struct {
beego.Controller
}
// @Title Logout
// @Description unauthenticate user
// @Param Authorization header string false "auth token"
// @Success 200 {string}
// @router /ldap/logout [delete]
func (o *OAuthController) LogOutLDAP() {
// authorize user
reqToken := o.Ctx.Request.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) < 2 {
reqToken = ""
} else {
reqToken = splitToken[1]
}
var res auth_connectors.Token
json.Unmarshal(o.Ctx.Input.CopyBody(10000000), &res)
token, err := infrastructure.GetAuthConnector().Logout(reqToken)
if err != nil || token == nil {
o.Data["json"] = err
} else {
o.Data["json"] = token
}
o.ServeJSON()
}
// @Title Login
// @Description authenticate user
// @Param body body models.workflow true "The workflow content"
// @Success 200 {string}
// @router /ldap/login [post]
func (o *OAuthController) LoginLDAP() {
// authorize user
var res auth_connectors.Token
json.Unmarshal(o.Ctx.Input.CopyBody(10000000), &res)
ldap := auth_connectors.New()
found, err := ldap.Authenticate(o.Ctx.Request.Context(), res.Username, res.Password)
if err != nil || !found {
o.Data["json"] = err
o.Ctx.ResponseWriter.WriteHeader(401)
o.ServeJSON()
return
}
token, err := infrastructure.GetAuthConnector().Login(res.Username,
&http.Cookie{ // open a session
Name: "csrf_token",
Value: o.XSRFToken(),
})
if err != nil || token == nil {
o.Data["json"] = err
o.Ctx.ResponseWriter.WriteHeader(401)
} else {
o.Data["json"] = token
}
o.ServeJSON()
}
// @Title Claims
// @Description enrich token with claims
// @Param body body models.Token true "The token info"
// @Success 200 {string}
// @router /claims [post]
func (o *OAuthController) Claims() {
// enrich token with claims
var res claims.Claims
json.Unmarshal(o.Ctx.Input.CopyBody(100000), &res)
claims := res.Session.IDToken["id_token_claims"].(map[string]interface{})
userName := claims["sub"].(string)
_, loc := static.GetMyLocalJsonPeer()
o.Data["json"] = infrastructure.GetClaims().AddClaimsToToken(userName, loc["url"].(string))
o.ServeJSON()
}
// @Title Introspection
// @Description introspect token
// @Param body body models.Token true "The token info"
// @Success 200 {string}
// @router /refresh [post]
func (o *OAuthController) Refresh() {
var token auth_connectors.Token
json.Unmarshal(o.Ctx.Input.CopyBody(100000), &token)
// refresh token
newToken, err := infrastructure.GetAuthConnector().Refresh(&token)
if err != nil || newToken == nil {
o.Data["json"] = err
o.Ctx.ResponseWriter.WriteHeader(401)
} else {
o.Data["json"] = newToken
}
o.ServeJSON()
}
// @Title Introspection
// @Description introspect token
// @Param Authorization header string false "auth token"
// @Success 200 {string}
// @router /introspect [get]
func (o *OAuthController) Introspect() {
reqToken := o.Ctx.Request.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) < 2 {
reqToken = ""
} else {
reqToken = splitToken[1]
}
token, err := infrastructure.GetAuthConnector().Introspect(reqToken)
if err != nil || !token {
o.Data["json"] = err
o.Ctx.ResponseWriter.WriteHeader(401)
}
o.ServeJSON()
}
// @Title AuthForward
// @Description auth forward
// @Param Authorization header string false "auth token"
// @Param body body models.workflow true "The workflow content"
// @Success 200 {string}
// @router /forward [get]
func (o *OAuthController) InternalAuthForward() {
reqToken := o.Ctx.Request.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) < 2 {
reqToken = ""
} else {
reqToken = splitToken[1]
}
origin, publicKey, external := o.extractOrigin()
if reqToken != "" && !o.checkAuthForward(reqToken, publicKey) && origin != "" {
fmt.Println("Unauthorized", origin, reqToken)
o.Ctx.ResponseWriter.WriteHeader(401)
o.ServeJSON()
return
}
token, err := infrastructure.GetAuthConnector().Introspect(reqToken, &http.Cookie{
Name: "csrf_token",
Value: o.XSRFToken(),
}) // may be a problem... we should check if token is valid on our side
// prefers a refresh token call
if err != nil || external {
fmt.Println("Unauthorized 2", err, external) // error
o.Ctx.ResponseWriter.WriteHeader(401)
} else if token && !external { // redirect to login
o.Data["json"] = token
}
o.ServeJSON()
}
func (o *OAuthController) extractOrigin() (string, string, bool) {
external := true
publicKey := ""
origin := o.Ctx.Request.Header.Get("X-Forwarded-Host")
if origin == "" {
origin = o.Ctx.Request.Header.Get("Origin")
}
idLoc, loc := static.GetMyLocalJsonPeer()
if origin != "" { // is external
peer := oclib.Search(nil, origin, oclib.LibDataEnum(oclib.PEER))
if peer.Code != 200 {
return "", "", external
}
p := peer.Data[0]
if strings.Contains(origin, "localhost") || strings.Contains(origin, "127.0.0.1") || idLoc == p.GetID() {
external = false
}
publicKey = p.(*model.Peer).PublicKey
} else {
external = false
publicKey = loc["public_key"].(string)
}
return origin, publicKey, external
}
func (o *OAuthController) checkAuthForward(reqToken string, publicKey string) bool {
bytes, err := base64.StdEncoding.DecodeString(reqToken) // Converting data
if err != nil {
fmt.Println("Failed to Decode secret", err)
return false
}
var decodedToken map[string]interface{}
err = json.Unmarshal(bytes, &decodedToken)
if err != nil {
fmt.Println("Failed to parse secret", err)
return false
} else if decodedToken["session"] != nil {
host := o.Ctx.Request.Header.Get("X-Forwarded-Host")
method := o.Ctx.Request.Header.Get("X-Forwarded-Method")
forward := o.Ctx.Request.Header.Get("X-Forwarded-Uri")
if forward == "" || method == "" {
fmt.Println("Forwarded headers are missing")
return false
}
// ask keto for permission is in claims
ok, err := infrastructure.GetClaims().DecodeClaimsInToken(
host, method, forward, decodedToken["session"].(map[string]interface{}), publicKey)
if err != nil {
fmt.Println("Failed to decode claims", err)
}
return ok
}
return false
}

192
controllers/permission.go Normal file
View File

@@ -0,0 +1,192 @@
package controllers
import (
"oc-auth/infrastructure"
beego "github.com/beego/beego/v2/server/web"
)
// Operations about auth
type PermissionController struct {
beego.Controller
}
// @Title GetAll
// @Description find permissions
// @Success 200 {permission} string
// @router / [get]
func (o *PermissionController) GetAll() {
role, err := infrastructure.GetPermissionConnector().GetPermission("", "")
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title GetByRole
// @Description find permission by role id
// @Param id path string true "the id you want to get"
// @Success 200 {auth} string
// @router /role/:id [get]
func (o *PermissionController) GetByRole() {
id := o.Ctx.Input.Param(":id")
role, err := infrastructure.GetPermissionConnector().GetPermissionByRole(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title GetByUser
// @Description find permission by user id
// @Param id path string true "the id you want to get"
// @Success 200 {auth} string
// @router /user/:id [get]
func (o *PermissionController) GetByUser() {
id := o.Ctx.Input.Param(":id")
role, err := infrastructure.GetPermissionConnector().GetPermissionByUser(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Get
// @Description find auth by permission
// @Param id path string true "the permission you want to get"
// @Success 200 {auth} models.auth
// @router /:id/:relation[get]
func (o *PermissionController) Get() {
id := o.Ctx.Input.Param(":id")
rel := o.Ctx.Input.Param(":relation")
role, err := infrastructure.GetPermissionConnector().GetPermission(id, rel)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Clear
// @Description clear the permission
// @Success 200 {string} delete success!
// @router /clear [delete]
func (o *PermissionController) Clear() {
role, code, err := infrastructure.GetPermissionConnector().DeletePermission("", "", true)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Bind
// @Description bind the permission to role
// @Param role_id path string true "The role_id you want to bind"
// @Param method path string true "The method you want to relate role & permission"
// @Param permission_id path string true "The permission_id you want to bind"
// @Success 200 {string} bind success!
// @router /:permission_id/:role_id/:relation [post]
func (o *PermissionController) Bind() {
permission_id := o.Ctx.Input.Param(":permission_id")
role_id := o.Ctx.Input.Param(":role_id")
rel := o.Ctx.Input.Param(":relation")
role, code, err := infrastructure.GetPermissionConnector().BindPermission(role_id, permission_id, rel)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title UnBind
// @Description unbind the permission to role
// @Param role_id path string true "The role_id you want to unbind"
// @Param relation path string true "The method you want to unrelate role & permission"
// @Param permission_id path string true "The permission_id you want to unbind"
// @Success 200 {string} bind success!
// @router /:permission_id/:role_id/:relation [delete]
func (o *PermissionController) UnBind() {
permission_id := o.Ctx.Input.Param(":permission_id")
role_id := o.Ctx.Input.Param(":role_id")
rel := o.Ctx.Input.Param(":relation")
role, code, err := infrastructure.GetPermissionConnector().UnBindPermission(role_id, permission_id, rel)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}

View File

@@ -1,52 +0,0 @@
package controllers
import (
"encoding/json"
"log"
"oc-auth/models"
"strings"
beego "github.com/beego/beego/v2/server/web"
"github.com/nats-io/nats.go"
)
// Operations about auth
type RegistrationController struct {
beego.Controller
}
// @Title Create
// @Description create auths
// @Param body body models.Application true "The app info"
// @Success 200 {string} models.auth.Id
// @Failure 403 body is empty
// @router / [post]
func (o *RegistrationController) Post() {
var app models.Application
// Store the app info in the nats server
err := json.Unmarshal(o.Ctx.Input.RequestBody, &app)
if err != nil {
log.Fatal(err)
}
servers := []string{"nats://127.0.0.1:1222", "nats://127.0.0.1:1223", "nats://127.0.0.1:1224"}
nc, err := nats.Connect(strings.Join(servers, ","))
if err != nil {
log.Fatal(err)
}
defer nc.Close()
js, err := nc.JetStream(nats.PublishAsyncMaxPending(256))
if err != nil {
log.Fatal(err)
}
kv, err := js.KeyValue("auth")
if err != nil {
log.Fatal(err)
}
kv.Put(app.ClientId, o.Ctx.Input.RequestBody)
// register to OIDC server
// store and return Id or post with UUID
o.Data["json"] = map[string]string{"Id": "?"}
o.ServeJSON()
}

213
controllers/role.go Normal file
View File

@@ -0,0 +1,213 @@
package controllers
import (
"oc-auth/infrastructure"
beego "github.com/beego/beego/v2/server/web"
)
// Operations about auth
type RoleController struct {
beego.Controller
}
// @Title Create
// @Description create role
// @Param id path string true "the id you want to get"
// @Success 200 {auth} create success!
// @router /:id [post]
func (o *RoleController) Post() {
// store and return Id or post with UUID
id := o.Ctx.Input.Param(":id")
role, code, err := infrastructure.GetPermissionConnector().CreateRole(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title GetByUser
// @Description find role by user id
// @Param id path string true "the id you want to get"
// @Success 200 {auth} string
// @router /user/:id [get]
func (o *RoleController) GetByUser() {
id := o.Ctx.Input.Param(":id")
role, err := infrastructure.GetPermissionConnector().GetRoleByUser(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title GetAll
// @Description find roles
// @Success 200 {role} string
// @router / [get]
func (o *RoleController) GetAll() {
role, err := infrastructure.GetPermissionConnector().GetRole("")
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Get
// @Description find role by id
// @Param id path string true "the id you want to get"
// @Success 200 {role} string
// @router /:id [get]
func (o *RoleController) Get() {
id := o.Ctx.Input.Param(":id")
role, err := infrastructure.GetPermissionConnector().GetRole(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Delete
// @Description delete the role
// @Param id path string true "The id you want to delete"
// @Success 200 {string} delete success!
// @router /:id [delete]
func (o *RoleController) Delete() {
id := o.Ctx.Input.Param(":id")
role, code, err := infrastructure.GetPermissionConnector().DeleteRole(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Clear
// @Description clear the role
// @Success 200 {string} delete success!
// @router /clear [delete]
func (o *RoleController) Clear() {
role, code, err := infrastructure.GetPermissionConnector().DeleteRole("")
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Bind
// @Description bind the role to user
// @Param user_id path string true "The user_id you want to bind"
// @Param role_id path string true "The role_id you want to bind"
// @Success 200 {string} bind success!
// @router /:user_id/:role_id [post]
func (o *RoleController) Bind() {
user_id := o.Ctx.Input.Param(":user_id")
role_id := o.Ctx.Input.Param(":role_id")
role, code, err := infrastructure.GetPermissionConnector().BindRole(user_id, role_id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title UnBind
// @Description unbind the role to user
// @Param role_id path string true "The role_id you want to unbind"
// @Param user_id path string true "The user_id you want to unbind"
// @Success 200 {string} bind success!
// @router /:user_id/:role_id [delete]
func (o *RoleController) UnBind() {
user_id := o.Ctx.Input.Param(":user_id")
role_id := o.Ctx.Input.Param(":role_id")
role, code, err := infrastructure.GetPermissionConnector().UnBindRole(user_id, role_id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}

View File

@@ -17,3 +17,12 @@ func (c *VersionController) GetAll() {
c.Data["json"] = map[string]string{"version": "1"}
c.ServeJSON()
}
// @Title Get
// @Description get version
// @Success 200
// @router /discovery [get]
func (c *VersionController) Get() {
c.Data["json"] = map[string]string{"version": "1"}
c.ServeJSON()
}