Skip to content
Draft
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
51 changes: 40 additions & 11 deletions backend/auth-core/src/oidc.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::config::CommonConfig;
use anyhow::anyhow;
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use oauth2::{ClientId, ClientSecret, EndpointMaybeSet, EndpointNotSet, EndpointSet, reqwest};
use openidconnect::core::{CoreClient, CoreProviderMetadata, CoreTokenResponse};
use oauth2::{ClientId, ClientSecret, reqwest};
use openidconnect::core::CoreProviderMetadata;
use openidconnect::{IssuerUrl, RefreshToken};
use sea_orm::{Database, DatabaseConnection};
use sodiumoxide::crypto::box_::{PublicKey, SecretKey};
Expand All @@ -26,13 +26,42 @@ pub async fn create_db_connection(config: &CommonConfig) -> Result<DatabaseConne
Database::connect(&database_url).await.map_err(Into::into)
}

pub type OidcClient = CoreClient<
EndpointSet,
EndpointNotSet,
EndpointNotSet,
EndpointNotSet,
EndpointMaybeSet,
EndpointMaybeSet,
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct DiamondAdditionalClaims {
pub fedid: Option<String>,
}

impl openidconnect::AdditionalClaims for DiamondAdditionalClaims {}

pub type DiamondIdTokenFields = openidconnect::IdTokenFields<
DiamondAdditionalClaims,
openidconnect::EmptyExtraTokenFields,
openidconnect::core::CoreGenderClaim,
openidconnect::core::CoreJweContentEncryptionAlgorithm,
openidconnect::core::CoreJwsSigningAlgorithm,
>;

pub type DiamondTokenResponse =
openidconnect::StandardTokenResponse<DiamondIdTokenFields, openidconnect::core::CoreTokenType>;

pub type OidcClient = openidconnect::Client<
DiamondAdditionalClaims,
openidconnect::core::CoreAuthDisplay,
openidconnect::core::CoreGenderClaim,
openidconnect::core::CoreJweContentEncryptionAlgorithm,
openidconnect::core::CoreJsonWebKey,
openidconnect::core::CoreAuthPrompt,
openidconnect::StandardErrorResponse<openidconnect::core::CoreErrorResponseType>,
DiamondTokenResponse,
openidconnect::core::CoreTokenIntrospectionResponse,
openidconnect::core::CoreRevocableToken,
openidconnect::core::CoreRevocationErrorResponse,
openidconnect::EndpointSet,
openidconnect::EndpointNotSet,
openidconnect::EndpointNotSet,
openidconnect::EndpointNotSet,
openidconnect::EndpointMaybeSet,
openidconnect::EndpointMaybeSet,
>;

pub async fn create_oidc_client(config: &CommonConfig) -> Result<(OidcClient, reqwest::Client)> {
Expand All @@ -48,7 +77,7 @@ pub async fn create_oidc_client(config: &CommonConfig) -> Result<(OidcClient, re
)
.await?;

let oidc_client = CoreClient::from_provider_metadata(
let oidc_client = OidcClient::from_provider_metadata(
provider_metadata,
ClientId::new(config.client_id.to_string()),
if config.client_secret.is_empty() {
Expand All @@ -72,7 +101,7 @@ pub async fn exchange_refresh_token(
oidc_client: &OidcClient,
http_client: &reqwest::Client,
refresh_token: &RefreshToken,
) -> Result<CoreTokenResponse> {
) -> Result<DiamondTokenResponse> {
let token_response = oidc_client
.exchange_refresh_token(refresh_token)?
.request_async(http_client)
Expand Down
16 changes: 16 additions & 0 deletions backend/auth-gateway/src/auth_session_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,44 @@ pub struct TokenSessionData {
pub access_token: AccessToken,
pub access_token_expires_at: DateTime<Utc>,
pub refresh_token: RefreshToken,
pub name: Option<String>,
pub preferred_username: Option<String>,
pub fedid: Option<String>,
}

impl TokenSessionData {
pub const SESSION_KEY: &str = "token_session_data";

#[allow(clippy::too_many_arguments)]
pub fn new(
issuer: IssuerUrl,
subject: SubjectIdentifier,
access_token: AccessToken,
access_token_expires_at: DateTime<Utc>,
refresh_token: RefreshToken,
name: Option<String>,
preferred_username: Option<String>,
fedid: Option<String>,
) -> Self {
Self {
issuer,
subject,
access_token,
access_token_expires_at,
refresh_token,
name,
preferred_username,
fedid,
}
}

pub fn from_token_response<T: auth_core::oauth2::TokenResponse>(
token_response: &T,
issuer: IssuerUrl,
subject: SubjectIdentifier,
name: Option<String>,
preferred_username: Option<String>,
fedid: Option<String>,
) -> Result<Self> {
let access_token = token_response.access_token().clone();
let refresh_token = token_response
Expand All @@ -64,6 +77,9 @@ impl TokenSessionData {
access_token,
access_token_expires_at,
refresh_token,
name,
preferred_username,
fedid,
))
}

Expand Down
12 changes: 12 additions & 0 deletions backend/auth-gateway/src/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@ pub async fn callback(
&token_response,
claims.issuer().clone(),
claims.subject().clone(),
claims
.name()
.and_then(|name| name.get(None))
.map(|n| n.to_string()),
claims
.preferred_username()
.map(|username| username.to_string()),
claims
.additional_claims()
.fedid
.as_ref()
.map(|fedid| fedid.to_string()),
)?;
write_token_to_database(&state.database_connection, &token_data, &state.public_key).await?;
session
Expand Down
2 changes: 2 additions & 0 deletions backend/auth-gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod callback;
mod config;
mod login;
mod state;
mod userinfo;

use auth_core::middleware::inject_token::inject_token_with;
use clap::Parser;
Expand Down Expand Up @@ -96,6 +97,7 @@ fn create_router(state: Arc<AppState>, graph_url: String) -> Router {
.route("/auth/login", get(login::login))
.route("/auth/callback", get(callback::callback))
.route("/auth/logout", post(logout))
.route("/auth/me", get(userinfo::userinfo))
.route("/healthcheck", get(auth_core::healthcheck::healthcheck))
.layer(session_layer)
.layer(
Expand Down
34 changes: 34 additions & 0 deletions backend/auth-gateway/src/userinfo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Json},
};
use serde::Serialize;
use tower_sessions::Session;

use crate::Result;
use crate::auth_session_data::TokenSessionData;

#[derive(Debug, Serialize)]
pub struct UserInfo {
pub name: Option<String>,
pub preferred_username: Option<String>,
pub fedid: Option<String>,
}

pub async fn userinfo(session: Session) -> Result<impl IntoResponse> {
let token_session_data: Option<TokenSessionData> =
session.get(TokenSessionData::SESSION_KEY).await?;

match token_session_data {
Some(token) => Ok((
StatusCode::OK,
Json(UserInfo {
name: token.name,
preferred_username: token.preferred_username,
fedid: token.fedid,
}),
)
.into_response()),
None => Ok(StatusCode::UNAUTHORIZED.into_response()),
}
}
2 changes: 2 additions & 0 deletions charts/dashboard/staging-values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ configuration:
sourceDir: /usr/share/nginx/html
useAuthGateway: "true"
authGatewayLoginUrl: https://staging.workflows.diamond.ac.uk/auth/login
authGatewayUserInfoUrl: https://staging.workflows.diamond.ac.uk/auth/userinfo
logoutUrl: https://staging.workflows.diamond.ac.uk/auth/logout

ingress:
hosts:
Expand Down
4 changes: 4 additions & 0 deletions charts/dashboard/templates/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ spec:
value: {{ .Values.configuration.useAuthGateway | toString | quote }}
- name: AUTH_GATEWAY_LOGIN_URL
value: {{ .Values.configuration.authGatewayLoginUrl }}
- name: AUTH_GATEWAY_USER_INFO_URL
value: {{ .Values.configuration.authGatewayUserInfoUrl }}
- name: LOGOUT_URL
value: {{ .Values.configuration.logoutUrl }}
livenessProbe:
httpGet:
path: /healthcheck
Expand Down
2 changes: 2 additions & 0 deletions charts/dashboard/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ configuration:
sourceDir: "/usr/share/nginx/html"
useAuthGateway: "false"
authGatewayLoginUrl: https://workflows.diamond.ac.uk/auth/login
authGatewayUserInfoUrl: https://workflows.diamond.ac.uk/auth/userinfo
logoutUrl: https://identity.diamond.ac.uk/realms/dls/protocol/openid-connect/logout

image:
registry: ghcr.io
Expand Down
2 changes: 2 additions & 0 deletions frontend/configure.sh
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ replace_placeholder KEYCLOAK_SCOPE
replace_placeholder GRAPH_URL
replace_placeholder GRAPH_WS_URL
replace_placeholder AUTH_GATEWAY_LOGIN_URL
replace_placeholder AUTH_GATEWAY_USER_INFO_URL
replace_placeholder LOGOUT_URL
replace_placeholder USE_AUTH_GATEWAY

nginx -g 'daemon off;'
2 changes: 2 additions & 0 deletions frontend/dashboard/.env.production
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ VITE_KEYCLOAK_SCOPE = "{{ KEYCLOAK_SCOPE }}"
VITE_GRAPH_URL = "{{ GRAPH_URL }}"
VITE_GRAPH_WS_URL = "{{ GRAPH_WS_URL }}"
VITE_AUTH_GATEWAY_LOGIN_URL = "{{ AUTH_GATEWAY_LOGIN_URL }}"
VITE_AUTH_GATEWAY_USER_INFO_URL = "{{ AUTH_GATEWAY_USER_INFO_URL }}"
VITE_LOGOUT_URL = "{{ LOGOUT_URL }}"
2 changes: 2 additions & 0 deletions frontend/dashboard/src/vite-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ interface ImportMetaEnv {
readonly VITE_GRAPH_WS_URL: string;
readonly VITE_USE_AUTH_GATEWAY: string;
readonly VITE_AUTH_GATEWAY_LOGIN_URL: string;
readonly VITE_AUTH_GATEWAY_USER_INFO_URL: string;
readonly VITE_LOGOUT_URL: string;
}

interface importMeta {
Expand Down
3 changes: 3 additions & 0 deletions frontend/relay-workflows-lib/.env.test
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
VITE_ENABLE_MOCKING = true
VITE_GRAPH_URL = "https://workflows.diamond.ac.uk/graphql"
VITE_GRAPH_WS_URL = "wss://workflows.diamond.ac.uk/graphql/ws"
VITE_AUTH_GATEWAY_LOGIN_URL = "https://workflows.diamond.ac.uk/auth/login"
VITE_AUTH_GATEWAY_USER_INFO_URL = "https://workflows.diamond.ac.uk/auth/userinfo"
VITE_LOGOUT_URL = "https://identity.diamond.ac.uk/realms/dls/protocol/openid-connect/logout"
35 changes: 33 additions & 2 deletions frontend/relay-workflows-lib/lib/components/RelayEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ const WS_ENDPOINT = import.meta.env.VITE_GRAPH_WS_URL;
const KEYCLOAK_SCOPE = import.meta.env.VITE_KEYCLOAK_SCOPE;
const USE_AUTH_GATEWAY = getUseAuthGateway();
const AUTH_GATEWAY_LOGIN_URL = import.meta.env.VITE_AUTH_GATEWAY_LOGIN_URL;
const AUTH_GATEWAY_USER_INFO_URL =
import.meta.env.VITE_AUTH_GATEWAY_USER_INFO_URL;

const keycloak = await getKeycloak();

Expand Down Expand Up @@ -59,6 +61,11 @@ if (!USE_AUTH_GATEWAY) {
};
}

function redirectToAuthGatewayLogin() {
const returnTo = encodeURIComponent(window.location.href);
window.location.assign(`${AUTH_GATEWAY_LOGIN_URL}?returnTo=${returnTo}`);
}

const fetchFn: FetchFunction = async (request, variables) => {
if (!keycloak.authenticated) {
await ensureKeycloakInit();
Expand Down Expand Up @@ -87,8 +94,7 @@ const fetchFn: FetchFunction = async (request, variables) => {
}
const resp = await fetch(HTTP_ENDPOINT, fetchOptions);
if (USE_AUTH_GATEWAY && resp.status === 401) {
const returnTo = encodeURIComponent(window.location.href);
window.location.assign(`${AUTH_GATEWAY_LOGIN_URL}?returnTo=${returnTo}`);
redirectToAuthGatewayLogin();
return {};
}

Expand Down Expand Up @@ -152,6 +158,31 @@ export async function getRelayEnvironment(): Promise<Environment> {
}

export async function getUser(): Promise<AuthState | null> {
if (USE_AUTH_GATEWAY) {
try {
const resp = await fetch(AUTH_GATEWAY_USER_INFO_URL, {
credentials: "include",
headers: { Accept: "application/json" },
});
if (resp.status === 401) {
redirectToAuthGatewayLogin();
return null;
}
if (!resp.ok) {
return null;
}
const data = (await resp.json()) as JSONObject;
const user: AuthState = {
name: data.name as string,
fedid: data.fedid as string,
};
return user;
} catch (error) {
console.error("Failed to fetch user info: ", error);
return null;
}
}

if (!keycloak.authenticated) {
await ensureKeycloakInit();
}
Expand Down
15 changes: 12 additions & 3 deletions frontend/relay-workflows-lib/lib/components/WorkflowsNavbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,24 @@ import {
import { getUser } from "relay-workflows-lib";
import { useEffect, useState } from "react";
import { externalRedirect } from "../utils/coreUtils";
import { getUseAuthGateway } from "../utils/useAuthGateway";

interface WorkflowsNavbarProps {
sessionInfo?: string;
}

const LOGOUT_URL = import.meta.env.VITE_LOGOUT_URL;

const handleLogout = () => {
externalRedirect(
"https://identity.diamond.ac.uk/realms/dls/protocol/openid-connect/logout",
);
if (getUseAuthGateway()) {
fetch(LOGOUT_URL, { method: "POST", credentials: "include" })
.then(() => { externalRedirect("/") })
.catch((error: unknown) => {
console.error("Logout failed: ", error);
});
} else {
externalRedirect(LOGOUT_URL);
}
};

const WorkflowsNavbar: React.FC<WorkflowsNavbarProps> = ({ sessionInfo }) => {
Expand Down
Loading
Loading