Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zanzibar be client #413

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
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
4 changes: 4 additions & 0 deletions cmd/devinit/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ func (c *Config) makeCore() error {
"schemes": []string{"https"},
},
},
"zanzibar": map[string]interface{}{
"token": c.zanzibarToken,
"prefix": c.zanzibarPrefix,
},
}

yamlBytes, err := yaml.Marshal(coreConfig)
Expand Down
5 changes: 5 additions & 0 deletions cmd/devinit/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ var (
CoreFormsApiDir string
CoreAuthnzApiDir string
CoreAuthnzBouncerDir string
ZanzibarDir string
LoginDir string
RedisDir string
PostgresDir string
Expand Down Expand Up @@ -166,6 +167,8 @@ type Config struct {
rootCaKeyPath string
rootCaPath string
rootDir string
zanzibarToken string
zanzibarPrefix string
}

func Init() error {
Expand Down Expand Up @@ -268,6 +271,7 @@ func createConfig() (*Config, error) {
config.makePostgresInit,
config.makePostgres,
config.makeHydraInit,
config.makeZanzibarConfig,
}

for _, f := range funcs {
Expand Down Expand Up @@ -456,6 +460,7 @@ func init() {
OIDCDir = path.Join(CredsDir, "oidc")
IDPDir = path.Join(CredsDir, "nrc_idp")
CoreDir = path.Join(CredsDir, "core")
ZanzibarDir = path.Join(CredsDir, "zanzibar")
LoginDir = path.Join(CoreDir, "login")
CoreAppFrontendDir = path.Join(CoreDir, "app_frontend")
CoreAdminFrontendDir = path.Join(CoreDir, "admin_frontend")
Expand Down
1 change: 1 addition & 0 deletions cmd/devinit/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

func (c *Config) makePostgres() error {
var err error

c.postgresRootPassword, err = getOrCreateRandomSecretStr(32, PostgresDir, "password")
if err != nil {
return err
Expand Down
8 changes: 7 additions & 1 deletion cmd/devinit/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"os"
"path"
"path/filepath"
"strings"
"time"
)

Expand Down Expand Up @@ -207,7 +208,12 @@ func genServerCert(

func getOrCreateRandomSecretStr(length int, filePaths ...string) (string, error) {
secretBytes, err := getOrCreateRandomSecret(length, filePaths...)
return string(secretBytes), err
if err != nil {
return "", err
}
secretStr := string(secretBytes)
secretStr = strings.Trim(secretStr, "\n")
return secretStr, nil
}

func getOrCreateRandomSecret(length int, filePaths ...string) ([]byte, error) {
Expand Down
17 changes: 17 additions & 0 deletions cmd/devinit/zanzibar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package devinit

func (c *Config) makeZanzibarConfig() error {

var err error
c.zanzibarToken, err = getOrCreateRandomSecretStr(32, ZanzibarDir, "token")
if err != nil {
return err
}

c.zanzibarPrefix, err = getOrCreateRandomSecretStr(32, ZanzibarDir, "prefix")
if err != nil {
return err
}

return nil
}
9 changes: 9 additions & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/nrc-no/core/pkg/logging"
"github.com/nrc-no/core/pkg/server/options"
"github.com/nrc-no/core/pkg/store"
client2 "github.com/nrc-no/core/pkg/zanzibar"
"github.com/spf13/viper"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
Expand All @@ -20,6 +21,7 @@ var osSignal = make(chan os.Signal)
var doneSignal = make(chan struct{})
var ctx = context.Background()
var factory store.Factory
var zanzibarClient client2.ZanzibarClient

// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Expand Down Expand Up @@ -81,6 +83,13 @@ func initStoreFactory() error {
return nil
}

func initZanzibarClient() {
zanzibarClient = client2.NewZanzibarClient(client2.ZanzibarClientConfig{
Token: coreOptions.Zanzibar.Token,
Prefix: coreOptions.Zanzibar.Prefix,
})
}

func init() {
rootCmd.AddCommand(serveCmd)
}
Expand Down
8 changes: 6 additions & 2 deletions cmd/serve_all.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@ var serveAllCmd = &cobra.Command{
if err := initStoreFactory(); err != nil {
return err
}

initZanzibarClient()

if err := serveFormsApi(ctx,
formsapiserver.Options{
ServerOptions: coreOptions.Serve.FormsApi,
StoreFactory: factory,
ServerOptions: coreOptions.Serve.FormsApi,
StoreFactory: factory,
ZanzibarClient: zanzibarClient,
}); err != nil {
return err
}
Expand Down
4 changes: 4 additions & 0 deletions cmd/serve_forms_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@ var servePublicCmd = &cobra.Command{
if err := initStoreFactory(); err != nil {
return err
}

initZanzibarClient()

if err := serveFormsApi(ctx,
formsapiserver.Options{
ServerOptions: coreOptions.Serve.FormsApi,
StoreFactory: factory,
ZanzibarClient: zanzibarClient,
}); err != nil {
return err
}
Expand Down
189 changes: 189 additions & 0 deletions frontend/packages/core-auth/src/components/AuthZWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { getLogger, LogLevelDesc } from 'loglevel';

import Browser from '../types/browser';
import exchangeCodeAsync from '../utils/exchangeCodeAsync';
import useDiscovery from '../hooks/useDiscovery';
import useAuthRequest from '../hooks/useAuthRequest';
import {
AuthWrapperProps,
CodeChallengeMethod,
ResponseType,
} from '../types/types';
import { TokenResponse } from '../types/response';
import { getJSONFromSessionStorage } from '../utils/getJSONFromSessionStorage';

const log = getLogger('AuthWrapper');
const loglevel = process?.env?.LOG_LEVEL as LogLevelDesc;
log.setLevel(loglevel || log.levels.INFO);

const AuthWrapper: React.FC<AuthWrapperProps> = ({
children,
scopes = [],
clientId,
issuer,
redirectUri,
customLoginComponent,
handleLoginErr = log.debug,
onTokenChange,
injectToken = 'access_token',
}) => {
const browser = useMemo(() => new Browser(), []);

browser.maybeCompleteAuthSession();

const discovery = useDiscovery(issuer);

const [tokenResponse, setTokenResponse] = useState<TokenResponse | undefined>(
TokenResponse.createTokenResponse(getJSONFromSessionStorage(injectToken)),
);

const [isLoggedIn, setIsLoggedIn] = useState(false);

const [request, response, promptAsync] = useAuthRequest(
{
clientId,
usePKCE: true,
responseType: ResponseType.Code,
codeChallengeMethod: CodeChallengeMethod.S256,
scopes,
redirectUri,
},
discovery,
browser,
);

// Make initial token request
// trigger login automatically
useEffect(() => {
(async () => {
if (
!discovery ||
request?.codeVerifier == null ||
!response ||
response?.type !== 'success'
) {
return;
}

const exchangeConfig = {
code: response.params.code,
clientId,
redirectUri,
extraParams: {
code_verifier: request?.codeVerifier,
},
};

try {
const tr = await exchangeCodeAsync(exchangeConfig, discovery);
setTokenResponse(tr);
} catch {
setTokenResponse(undefined);
}
})();
}, [request?.codeVerifier, response, discovery]);

// Each second, check if token is fresh
// If not, refresh the token
const refreshTokenInterval = React.useRef<number | null>(null);
React.useEffect(() => {
const refreshToken = async () => {
if (!discovery) return;
if (!tokenResponse) return;
if (!tokenResponse.shouldRefresh()) return;

const refreshConfig = {
clientId,
scopes,
extraParams: {},
refreshToken: tokenResponse.refreshToken,
};

try {
const resp = await TokenResponse.refreshAsync(refreshConfig, discovery);
setTokenResponse(resp);
} catch (err) {
setTokenResponse(undefined);
}
};

if (refreshTokenInterval.current)
window.clearInterval(refreshTokenInterval.current);

if (
tokenResponse &&
tokenResponse.expiresIn &&
tokenResponse.expiresIn > 0
) {
refreshTokenInterval.current = window.setInterval(refreshToken, 1000);
}

return () => {
if (refreshTokenInterval.current)
clearInterval(refreshTokenInterval.current);
};
}, [
tokenResponse?.refreshToken,
tokenResponse?.expiresIn,
JSON.stringify(discovery),
]);

// Run onTokenChange callback
// store token in session storage or remove it when undefined
useEffect(() => {
if (!tokenResponse) {
onTokenChange('');
sessionStorage.removeItem(injectToken);
} else {
const token = (() => {
switch (injectToken) {
case 'access_token':
return tokenResponse?.accessToken ?? '';
case 'id_token':
return tokenResponse?.idToken ?? '';
default:
return '';
}
})();
onTokenChange(token);
sessionStorage.setItem(injectToken, JSON.stringify(tokenResponse));
}
}, [JSON.stringify(tokenResponse)]);

// Update logged in status accordingly
useEffect(() => {
if (tokenResponse) {
if (!isLoggedIn) {
setIsLoggedIn(true);
}
} else if (isLoggedIn) {
setIsLoggedIn(false);
}
}, [JSON.stringify(tokenResponse), isLoggedIn]);

// trigger login manually, by clicking
const handleLogin = useCallback(() => {
promptAsync().catch((err) => {
handleLoginErr(err);
});
}, [discovery, request, promptAsync]);

if (!isLoggedIn) {
return (
<>
{customLoginComponent ? (
customLoginComponent({ login: handleLogin })
) : (
<button type="button" onClick={handleLogin}>
Login
</button>
)}
</>
);
}

return <>{children}</>;
};

export default AuthWrapper;
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ module github.com/nrc-no/core
go 1.16

require (
github.com/authzed/authzed-go v0.6.0
github.com/authzed/grpcutil v0.0.0-20220104222419-f813f77722e5
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff
github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927 // indirect
github.com/coreos/go-oidc/v3 v3.0.0
Expand Down
Loading