Skip to content

Commit

Permalink
Merge pull request #39 from interop-alliance/op-flex-docstore
Browse files Browse the repository at this point in the history
Refactor OidcManager to use flex-docstore.
  • Loading branch information
dmitrizagidulin authored Dec 4, 2019
2 parents 7c73689 + b7ef163 commit 1f81163
Show file tree
Hide file tree
Showing 27 changed files with 322 additions and 341 deletions.
4 changes: 2 additions & 2 deletions bin/lib/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ module.exports = function (program, server) {
})
}

function bin (argv, server) {
async function bin (argv, server) {
if (!argv.email) {
argv.email = {
host: argv.emailHost,
Expand Down Expand Up @@ -106,7 +106,7 @@ function bin (argv, server) {
const solid = require('../../')
let app
try {
app = solid.createServer(argv, server)
app = await solid.createServer(argv, server)
} catch (e) {
if (e.code === 'EACCES') {
if (e.syscall === 'mkdir') {
Expand Down
4 changes: 3 additions & 1 deletion lib/authentication/force-user.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ const { logger } = require('./../logger')
/**
* Enforces the `--force-user` server flag, hardcoding a webid for all requests,
* for testing purposes.
*
* Note: It's async only to match the signature of other auth methods.
*/
function initialize (app, argv) {
async function initialize (app, argv) {
const forceUserId = argv.forceUser
app.use('/', (req, res, next) => {
logger.warn(`Identified user (override): ${forceUserId}`)
Expand Down
3 changes: 1 addition & 2 deletions lib/authentication/multi-rp-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class MultiRpClient {
async clientForIssuer (issuerUri) {
const client = await this.loadClient(issuerUri)
if (client) {
// logger.info(`Client fetched for issuer ${issuerUri}`)
logger.info(`Client fetched for issuer ${issuerUri}`)
return client
}

Expand Down Expand Up @@ -129,7 +129,6 @@ class MultiRpClient {
}

registerClient ({ registration, rpOptions }) {
// logger.info('new OIDCRelyingParty.register()', config)
logger.info('Registering new client for issuer ', registration.issuer)

return OIDCRelyingParty.register(registration.issuer, registration, rpOptions)
Expand Down
69 changes: 36 additions & 33 deletions lib/authentication/oidc-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const { logger } = require('../logger')
const { URL } = require('url')
const validUrl = require('valid-url')
const ResourceAuthenticator = require('@solid/oidc-rs')
const KVPFileStore = require('kvplus-files')
const { FlexDocStore } = require('flex-docstore')
const { MultiRpClient } = require('./multi-rp-client')
const OIDCProvider = require('@interop-alliance/oidc-op')
Expand Down Expand Up @@ -78,8 +77,7 @@ class OidcManager {
*
* Config for OIDCProvider:
* @param config.serverUri {string} URI of the OpenID Connect Provider
* @param [config.host] {Object} Injected host behavior object,
* see `providerFrom()` docstring.
* @param [config.host] {Object} Injected host behavior object.
*
* Config for MultiRpClient:
* @param config.authCallbackUri {string}
Expand Down Expand Up @@ -150,7 +148,7 @@ class OidcManager {
postLogoutUri,
saltRounds: argv.saltRounds,
delayBeforeRegisteringInitialClient: argv.delayBeforeRegisteringInitialClient,
host: {}
host: HostAPI
}

return OidcManager.from(options)
Expand Down Expand Up @@ -190,17 +188,21 @@ class OidcManager {
*
* @return {Promise<RelyingParty>} Initialized local RP client
*/
async initialize () {
async initialize ({ skipInitLocalRp } = {}) {
try {
this.initStorage()
await this.initProviderKeychain()
this.saveProviderConfig()
const shouldSaveConfig = await this.initProviderKeychain()
if (shouldSaveConfig) {
this.saveProviderConfig()
}

await this.sleepIfNeeded()

return this.initLocalRpClient()
if (!skipInitLocalRp) {
await this.initLocalRpClient()
}
} catch (error) {
logger.error('Error initializing OidcManager:', error)
throw error
}
}

Expand All @@ -224,24 +226,20 @@ class OidcManager {
}
}

/**
* Initializes storage collections (creates directories if using
* on-disk stores, etc).
* Synchronous.
*/
initStorage () {
this.provider.backend.initCollections()
}

async initProviderKeychain () {
let shouldSaveConfig = true

if (this.provider.keys) {
logger.info('Provider keys loaded from config')
shouldSaveConfig = false
} else {
logger.info('No provider keys found, generating fresh ones')
}

await this.provider.initializeKeyChain(this.provider.keys)
logger.info('Provider keychain initialized')

return shouldSaveConfig
}

/**
Expand Down Expand Up @@ -318,24 +316,28 @@ class OidcManager {

initProvider () {
const providerConfig = this.loadProviderConfig()
const provider = new OIDCProvider(providerConfig)
if (providerConfig.keys) {
provider.keys = providerConfig.keys
}

const backend = new KVPFileStore({
path: this.storePaths.providerStore,
collections: ['codes', 'clients', 'tokens', 'refresh']
})
provider.inject({ backend })

// Init the injected host API (authenticate / obtainConsent / logout)
let host = this.host || {}
host = Object.assign(host, HostAPI)
// providerConfig.store = {
// codes: FlexDocStore.using('files',
// { dir: path.join(this.storePaths.providerStore, 'codes') }),
// clients: FlexDocStore.using('files',
// { dir: path.join(this.storePaths.providerStore, 'clients') }),
// tokens: FlexDocStore.using('files',
// { dir: path.join(this.storePaths.providerStore, 'tokens') }),
// refresh: FlexDocStore.using('files',
// { dir: path.join(this.storePaths.providerStore, 'refresh') })
// }

providerConfig.store = {
codes: FlexDocStore.using('memory'),
clients: FlexDocStore.using('memory'),
tokens: FlexDocStore.using('memory'),
refresh: FlexDocStore.using('memory')
}

provider.inject({ host })
providerConfig.host = this.host || HostAPI

this.provider = provider
this.provider = new OIDCProvider(providerConfig)
}

providerConfigPath () {
Expand Down Expand Up @@ -390,6 +392,7 @@ class OidcManager {

saveProviderConfig () {
const configPath = this.providerConfigPath()
fs.ensureDirSync(this.storePaths.providerStore)
fs.writeFileSync(configPath, JSON.stringify(this.provider, null, 2))
}

Expand Down
4 changes: 2 additions & 2 deletions lib/authentication/webid-oidc.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ const {
* @param app {Object} Express.js app instance
* @param argv {Object} Config options hashmap
*/
function initialize (app, argv) {
async function initialize (app, argv) {
const oidc = OidcManager.fromServerConfig(argv)
app.locals.oidc = oidc
oidc.initialize()
await oidc.initialize(argv)

// Attach the OIDC API
app.use('/', middleware(oidc))
Expand Down
12 changes: 6 additions & 6 deletions lib/create-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const bodyParser = require('body-parser')
const { ldpRequestHandler } = require('./data-storage/api')
const { corsSettings, initHeaders } = require('./common-headers')

function createApp (argv = {}) {
async function createApp (argv = {}) {
// Override default configs (defaults) with passed-in params (argv)
argv = Object.assign({}, defaults, argv)

Expand Down Expand Up @@ -46,7 +46,7 @@ function createApp (argv = {}) {

// If authentication is enabled, initialize it
if (argv.webid) {
initWebId(argv, app, storage)
await initWebId(argv, app, storage)
}

// Attach the LDP middleware
Expand Down Expand Up @@ -119,7 +119,7 @@ function initViews (app) {
* @param app {Function}
* @param storage {StorageManager}
*/
function initWebId (argv, app, storage) {
async function initWebId (argv, app, storage) {
const { root, multiuser, templates, server, host, skipWelcomePage } = argv
if (!skipWelcomePage) {
// Skip creating server welcome page (useful for tests)
Expand All @@ -146,7 +146,7 @@ function initWebId (argv, app, storage) {
app.use('/', accountMgmtApi.middleware(accountManager))

// Set up authentication-related API endpoints and app.locals
initAuthentication(app, argv)
await initAuthentication(app, argv)

app.get('/api/share', (req, res, next) => ShareRequest.get(req, res).catch(next))
app.post('/api/share', bodyParser.urlencoded({ extended: true }),
Expand All @@ -163,13 +163,13 @@ function initWebId (argv, app, storage) {
* @param app {Object} Express.js app instance
* @param argv {Object} Config options hashmap
*/
function initAuthentication (app, argv) {
async function initAuthentication (app, argv) {
const auth = argv.forceUser ? 'forceUser' : argv.auth
const authenticationApi = require('./authentication')
if (!(auth in authenticationApi)) {
throw new Error(`Unsupported authentication scheme: ${auth}`)
}
authenticationApi[auth].initialize(app, argv)
await authenticationApi[auth].initialize(app, argv)
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/create-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ const http = require('http')
const { logger } = require('./logger')
const createApp = require('./create-app')

function createServer (argv, app) {
async function createServer (argv, app) {
argv = argv || {}
app = app || express()
const ldpApp = createApp(argv)
const ldpApp = await createApp(argv)
let mount = argv.mount || '/'
// Removing ending '/'
if (mount.length > 1 &&
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"homepage": "https://github.com/interop-alliance/life-server",
"bugs": "https://github.com/interop-alliance/life-server/issues",
"dependencies": {
"@interop-alliance/oidc-op": "^0.7.0",
"@interop-alliance/oidc-op": "^0.8.0",
"@interop-alliance/oidc-rp": "^0.11.1",
"@solid/oidc-rs": "^0.4.0",
"bcryptjs": "^2.4.3",
Expand Down
Loading

0 comments on commit 1f81163

Please sign in to comment.