Skip to content
Snippets Groups Projects

Feature/nat 569 add opa to gui2

Merged Mohammad Torkashvand requested to merge feature/NAT-569-add-opa-to-gui2 into develop
All threads resolved!
Files
8
+ 114
0
import { useGsoConfig } from '@/contexts/GsoConfigContext';
import { LoadedPolicy, loadPolicy } from '@open-policy-agent/opa-wasm';
import {
OrchestratorConfigContext,
WfoAuth,
WfoLoading,
useWfoSession,
} from '@orchestrator-ui/orchestrator-ui-components';
import { join } from 'lodash';
import React, { FC, ReactNode, useContext, useEffect, useState } from 'react';
export type WfoAuthWithPolicyProps = {
children: ReactNode;
};
export enum PolicyLoadingStatus {
LOADING = 'loading',
SUCCESS = 'success',
FAILED = 'failed',
NOT_LOADED = 'notLoaded',
}
type Policy =
| {
loadedPolicy: LoadedPolicy;
policyLoadingStatus: PolicyLoadingStatus.SUCCESS;
}
| {
loadedPolicy: null;
policyLoadingStatus:
| PolicyLoadingStatus.LOADING
| PolicyLoadingStatus.FAILED
| PolicyLoadingStatus.NOT_LOADED;
};
export const WfoAuthWithPolicy: FC<WfoAuthWithPolicyProps> = ({ children }) => {
const { authActive } = useContext(OrchestratorConfigContext);
const { opaPublicBundleUrl, oidcClientId } = useGsoConfig();
const { status: sessionStatus, session } = useWfoSession({
required: authActive,
});
const [policy, setPolicy] = useState<Policy>({
loadedPolicy: null,
policyLoadingStatus: PolicyLoadingStatus.LOADING,
});
useEffect(() => {
const getPolicy = async () => {
try {
const policyResult = await fetch(opaPublicBundleUrl);
const policyWasm = await policyResult.arrayBuffer();
const loadedPolicy = await loadPolicy(policyWasm);
setPolicy({
loadedPolicy,
policyLoadingStatus: PolicyLoadingStatus.SUCCESS,
});
} catch (e) {
console.error('Failed to load policy', e);
setPolicy({
loadedPolicy: null,
policyLoadingStatus: PolicyLoadingStatus.FAILED,
});
}
};
// When auth is disabled, the policy should not be loaded
if (!authActive) {
setPolicy({
loadedPolicy: null,
policyLoadingStatus: PolicyLoadingStatus.NOT_LOADED,
});
return;
}
getPolicy();
}, [authActive, opaPublicBundleUrl, oidcClientId]);
const isAllowedHandler = (routerPath: string, resource?: string) => {
if (session && policy.policyLoadingStatus === PolicyLoadingStatus.SUCCESS) {
const { profile } = session;
// Fix unexpected scope array
if (profile && Array.isArray(profile.scope)) {
profile.scope = join(profile.scope, ' ');
}
const policyInput = {
resource: resource ?? routerPath,
active: true,
client_id: oidcClientId,
method: 'GET',
...profile,
};
const policyTestResult = policy.loadedPolicy.evaluate(policyInput);
return policyTestResult[0].result === true;
}
return false;
};
if (
policy.policyLoadingStatus === PolicyLoadingStatus.LOADING ||
sessionStatus === 'loading'
) {
return <WfoLoading />;
}
return authActive ? (
<WfoAuth isAllowedHandler={isAllowedHandler}>{children}</WfoAuth>
) : (
<WfoAuth>{children}</WfoAuth>
);
};
Loading