Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api-contracts/openapi/components/schemas/metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ APIMetaAuth:
example:
- basic
- google
- azure

APIMetaPosthog:
type: object
Expand Down
4 changes: 4 additions & 0 deletions api-contracts/openapi/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ paths:
$ref: "./paths/user/user.yaml#/oauth-start-github"
/api/v1/users/github/callback:
$ref: "./paths/user/user.yaml#/oauth-callback-github"
/api/v1/users/azure/start:
$ref: "./paths/user/user.yaml#/oauth-start-azure"
/api/v1/users/azure/callback:
$ref: "./paths/user/user.yaml#/oauth-callback-azure"
/api/v1/tenants/{tenant}/slack/start:
$ref: "./paths/user/user.yaml#/oauth-start-slack"
/api/v1/users/slack/callback:
Expand Down
30 changes: 30 additions & 0 deletions api-contracts/openapi/paths/user/user.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,36 @@ oauth-callback-github:
summary: Complete OAuth flow
tags:
- User
oauth-start-azure:
get:
description: Starts the OAuth flow
operationId: user:update:azure-oauth-start
responses:
"302":
description: Successfully started the OAuth flow
headers:
location:
schema:
type: string
security: []
summary: Start OAuth flow
tags:
- User
oauth-callback-azure:
get:
description: Completes the OAuth flow
operationId: user:update:azure-oauth-callback
responses:
"302":
description: Successfully completed the OAuth flow
headers:
location:
schema:
type: string
security: []
summary: Complete OAuth flow
tags:
- User
oauth-start-slack:
get:
x-resources: ["tenant"]
Expand Down
2 changes: 2 additions & 0 deletions api/v1/server/authz/rbac.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ roles:
- WebhookCreate
- CloudMetadataGet
- UserUpdateGoogleOauthCallback
- UserUpdateAzureOauthCallback
- UserUpdateSlackOauthCallback
- V1WorkflowRunCreate
- V1WorkflowRunDisplayNamesList
Expand Down Expand Up @@ -111,6 +112,7 @@ roles:
- TenantResourcePolicyGet
- UserUpdateSlackOauthStart
- UserUpdateGoogleOauthStart
- UserUpdateAzureOauthStart
- SlackWebhookDelete
- V1CelDebug
- V1WorkflowRunGetTimings
Expand Down
4 changes: 4 additions & 0 deletions api/v1/server/handlers/metadata/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ func (u *MetadataService) MetadataGet(ctx echo.Context, request gen.MetadataGetR
authTypes = append(authTypes, "github")
}

if u.config.Auth.ConfigFile.Azure.Enabled {
authTypes = append(authTypes, "azure")
}

pylonAppID := u.config.Pylon.AppID

var posthogConfig *gen.APIMetaPosthog
Expand Down
202 changes: 202 additions & 0 deletions api/v1/server/handlers/users/azure_oauth_callback.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
package users

import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"

"github.com/jackc/pgx/v5"
"github.com/labstack/echo/v4"
"golang.org/x/oauth2"

"github.com/hatchet-dev/hatchet/api/v1/server/authn"
"github.com/hatchet-dev/hatchet/api/v1/server/middleware/redirect"
"github.com/hatchet-dev/hatchet/api/v1/server/oas/gen"
"github.com/hatchet-dev/hatchet/pkg/analytics"
"github.com/hatchet-dev/hatchet/pkg/config/server"
v1 "github.com/hatchet-dev/hatchet/pkg/repository"
"github.com/hatchet-dev/hatchet/pkg/repository/sqlcv1"
)

// Note: we want all errors to redirect, otherwise the user will be greeted with raw JSON in the middle of the login flow.
func (u *UserService) UserUpdateAzureOauthCallback(ctx echo.Context, _ gen.UserUpdateAzureOauthCallbackRequestObject) (gen.UserUpdateAzureOauthCallbackResponseObject, error) {
isValid, _, err := authn.NewSessionHelpers(u.config.SessionStore).ValidateOAuthState(ctx, "azure")

if err != nil || !isValid {
return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, err, "Could not log in. Please try again and make sure cookies are enabled.")
}

token, err := u.config.Auth.AzureOAuthConfig.Exchange(context.Background(), ctx.Request().URL.Query().Get("code"))

if err != nil {
return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, err, "Forbidden")
}

if !token.Valid() {
return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, fmt.Errorf("invalid token"), "Forbidden")
}

user, err := u.upsertAzureUserFromToken(ctx.Request().Context(), u.config, token)

if err != nil {
if errors.Is(err, ErrNotInRestrictedDomain) {
return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, err, "Email is not in the restricted domain group.")
}

if errors.Is(err, ErrAzureNoEmail) {
return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, err, "Azure account must have an email.")
}

return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, err, "Internal error.")
}

err = authn.NewSessionHelpers(u.config.SessionStore).SaveAuthenticated(ctx, user)

if err != nil {
return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, err, "Internal error.")
}

analyticsCtx := context.WithValue(ctx.Request().Context(), analytics.UserIDKey, user.ID)
analyticsCtx = context.WithValue(analyticsCtx, analytics.SourceKey, analytics.SourceUI)
u.config.Analytics.Enqueue(
analyticsCtx,
analytics.User, analytics.Login,
user.ID.String(),
map[string]interface{}{"provider": "azure"},
)
return gen.UserUpdateAzureOauthCallback302Response{
Headers: gen.UserUpdateAzureOauthCallback302ResponseHeaders{
Location: u.config.Runtime.ServerURL,
},
}, nil
}

func (u *UserService) upsertAzureUserFromToken(ctx context.Context, config *server.ServerConfig, tok *oauth2.Token) (*sqlcv1.User, error) {
aInfo, err := getAzureUserInfoFromToken(tok)
if err != nil {
return nil, err
}

// Azure AD does not expose a Google-style "hd" (hosted domain) claim, so we
// gate on the email's domain like the GitHub provider does.
if err := u.checkUserRestrictionsForEmail(config, aInfo.Email); err != nil {
return nil, err
}

expiresAt := tok.Expiry

// use the encryption service to encrypt the access and refresh token
accessTokenEncrypted, err := config.Encryption.Encrypt([]byte(tok.AccessToken), "azure_access_token")

if err != nil {
return nil, fmt.Errorf("failed to encrypt access token: %s", err.Error())
}

refreshTokenEncrypted, err := config.Encryption.Encrypt([]byte(tok.RefreshToken), "azure_refresh_token")

if err != nil {
return nil, fmt.Errorf("failed to encrypt refresh token: %s", err.Error())
}

oauthOpts := &v1.OAuthOpts{
Provider: "azure",
ProviderUserId: aInfo.Sub,
AccessToken: accessTokenEncrypted,
RefreshToken: refreshTokenEncrypted,
ExpiresAt: &expiresAt,
}

// Azure AD's OIDC userinfo endpoint does not return an email_verified claim, and
// Hatchet's authz middleware blocks users whose email is unverified. The email is
// sourced from the Azure AD directory (not self-asserted), so we treat it as verified,
// consistent with the Google/GitHub providers whose OAuth users are always verified.
user, err := u.config.V1.User().GetUserByEmail(ctx, aInfo.Email)

switch err {
case nil:
user, err = u.config.V1.User().UpdateUser(ctx, user.ID, &v1.UpdateUserOpts{
EmailVerified: v1.BoolPtr(true),
Name: v1.StringPtr(aInfo.Name),
OAuth: oauthOpts,
})

if err != nil {
return nil, fmt.Errorf("failed to update user: %s", err.Error())
}
case pgx.ErrNoRows:
user, err = u.config.V1.User().CreateUser(ctx, &v1.CreateUserOpts{
Email: aInfo.Email,
EmailVerified: v1.BoolPtr(true),
Name: v1.StringPtr(aInfo.Name),
OAuth: oauthOpts,
})

if err != nil {
return nil, fmt.Errorf("failed to create user: %s", err.Error())
}
default:
return nil, fmt.Errorf("failed to get user: %s", err.Error())
}

return user, nil
}

var ErrAzureNoEmail = fmt.Errorf("azure account must have an email")

// azureUserInfo holds the claims we consume from the Microsoft identity platform
// OIDC userinfo endpoint. Per the Microsoft docs that endpoint returns only sub,
// name, family_name, given_name, picture and (with the "email" scope) email — it
// does not return email_verified or preferred_username, so we don't model those.
type azureUserInfo struct {
Sub string `json:"sub"`
Name string `json:"name"`
Email string `json:"email"`
}

func getAzureUserInfoFromToken(tok *oauth2.Token) (*azureUserInfo, error) {
// use the Microsoft identity platform OIDC userinfo endpoint to get claims
url := "https://graph.microsoft.com/oidc/userinfo"

req, err := http.NewRequest("GET", url, nil)

if err != nil {
return nil, fmt.Errorf("failed creating request: %s", err.Error())
}

req.Header.Add("Authorization", "Bearer "+tok.AccessToken)

client := &http.Client{}

response, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed getting user info: %s", err.Error())
}

defer response.Body.Close()

contents, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed reading response body: %s", err.Error())
}

if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("userinfo endpoint returned status %d: %s", response.StatusCode, string(contents))
}

// parse contents into Azure userinfo claims
aInfo := &azureUserInfo{}
err = json.Unmarshal(contents, &aInfo)

if err != nil {
return nil, fmt.Errorf("failed parsing response body: %s", err.Error())
}

if aInfo.Email == "" {
return nil, ErrAzureNoEmail
}

return aInfo, nil
}
30 changes: 30 additions & 0 deletions api/v1/server/handlers/users/azure_oauth_start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package users

import (
"github.com/labstack/echo/v4"

"github.com/hatchet-dev/hatchet/api/v1/server/authn"
"github.com/hatchet-dev/hatchet/api/v1/server/middleware/redirect"
"github.com/hatchet-dev/hatchet/api/v1/server/oas/gen"
)

// Note: we want all errors to redirect, otherwise the user will be greeted with raw JSON in the middle of the login flow.
func (u *UserService) UserUpdateAzureOauthStart(ctx echo.Context, _ gen.UserUpdateAzureOauthStartRequestObject) (gen.UserUpdateAzureOauthStartResponseObject, error) {
if !u.config.Runtime.AllowSignup {
return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, nil, "User signup is disabled.")
}

state, err := authn.NewSessionHelpers(u.config.SessionStore).SaveOAuthState(ctx, "azure")

if err != nil {
return nil, redirect.GetRedirectWithError(ctx, u.config.Logger, err, "Could not get cookie. Please make sure cookies are enabled.")
}

url := u.config.Auth.AzureOAuthConfig.AuthCodeURL(state)

return gen.UserUpdateAzureOauthStart302Response{
Headers: gen.UserUpdateAzureOauthStart302ResponseHeaders{
Location: url,
},
}, nil
}
Loading